From bef635c6998aea17caef0a652579c70d18aef43b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:42:53 +1300 Subject: [PATCH 01/51] Complete normal region handoff and retained execution custody --- ...m-architecture-redis-reset-and-recovery.md | 2 +- .../player-access-and-session.md | 8 +- .../game-session-service/build.gradle.kts | 1 + ...calGameplayBindingInventoryRepository.java | 492 ++++++- ...layOriginalNewCapacityExecutionBudget.java | 26 +- ...playOriginalNewCapacityExecutionOwner.java | 156 ++- ...lGameplayProtectedIncarnationReceiver.java | 238 +++- .../CanonicalGameplayRegionLeaseOwner.java | 736 ++++++++-- ...anonicalGameplayRegionLeaseRedisOwner.java | 123 +- ...ameplayRegionOwnerTransferCoordinator.java | 257 ++++ ...yRegionOwnerTransferObservationSource.java | 117 ++ ...GameplayRegionOwnerTransferRepository.java | 1233 +++++++++++++++++ ...GameplayRegionRuntimeStatusRepository.java | 185 ++- ...olledRegionTransferObservationFixture.java | 155 +++ ...CapacityExecutionOwnerIntegrationTest.java | 286 +--- ...CapacityRetentionOwnerIntegrationTest.java | 267 ++-- ...alNewFinalAdmissionCompositionFixture.java | 83 ++ ...NewFinalAdmissionOwnerIntegrationTest.java | 115 +- ...AdmissionOwnerIntegrationTestSupport.java} | 157 ++- ...iginalNewRegionHandoffIntegrationTest.java | 1129 +++++++++++++++ ...onHandoffLeaseDeadlineIntegrationTest.java | 1097 +++++++++++++++ ...meplayRegionLeaseOwnerIntegrationTest.java | 387 +++++- ...GameplayRegionOwnerCompositionFixture.java | 305 +++- ...untimeStatusRepositoryIntegrationTest.java | 70 +- ...tatusRepositoryIntegrationTestSupport.java | 355 +++-- ...ransferCapacityCustodyIntegrationTest.java | 993 +++++++++++++ ...TransferSerializationIntegrationTest.java} | 621 ++++----- ...riginalNewCapacityExecutionBudgetTest.java | 155 ++- ...nOwnerTransferObservationReceiverTest.java | 984 +++++++++++++ 29 files changed, 9499 insertions(+), 1234 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture.java rename services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/{CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport.java => CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java} (81%) create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java rename services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/{CanonicalGameplayOriginalNewCapacityTransferCustodyIntegrationTest.java => CanonicalGameplayRegionTransferSerializationIntegrationTest.java} (58%) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index 368cf93bee..b0b93b40f5 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -231,7 +231,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `session:game:index:character:{tenantGameplayTag}::` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the target `{tenantId, playableStateNamespaceId, characterId}` character-to-session controller uniqueness entry may be dropped; at region scope, only the exact key for an affected binding is retained, removed, or recreated from durable binding inventory, preserving unrelated character keys, regions, and tenants. Takeover, resume, and new admission remain fenced until Game Session rebuilds or reconciles the exact entry and validates the server-derived `playableStateScope` binding/routing evidence plus value/evidence `{sessionId, gameInstanceId, bindingGeneration}` against the session record. An unbound-character decision requires that durable inventory readback to prove there is no active binding; an empty Redis key alone never proves availability. See [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). | Tenant-scoped and namespace-qualified, with the shard-local session CAS; `playableStateScope` remains binding/routing context. Rebuild removes stale entries, recreates missing entries, and rejects conflicting identities. The existing `:` index key is current implementation drift, not the target key. | | `session:game:index:account:` | Coordination | **Reset-sensitive with mandatory account-wide reconciliation** | Account-wide lookup is unavailable while the global index is dropped; narrow parents do not rebuild the untagged key, and account-wide access remains fenced until the complete owner-defined recovery result is consumed. | This is the one retained untagged global account exception: every member is a complete tenant-qualified `accountIndexMember`, so the key is not a tenant-local selector. Its physical layout and member contract are owned by [Global Account Active-Binding Index](./system-architecture-session-behavior.md#global-account-active-binding-index); narrower resets preserve unrelated tenants and cluster reset rebuilds the complete key. | | `session:game:account-admission:{tenantGameplayTag}::` | Coordination | **Reset-sensitive; missing or replaced state denies admission** | Loss, deletion, or storage replacement affecting the exact account/tenant/namespace slot keeps the affected scope closed. Absence is never implicit OPEN, and a retained historical CLOSED receipt does not prove current installation or authorize recreation as OPEN. | This persistent tenant-tagged hash is checked in the same slot as the tenant-local final binding CAS. Game Session must validate current protected incarnation and exact current owner/barrier state under the [Session account-intent protocol](./system-architecture-session-behavior.md#global-account-active-binding-index); reset alone proves neither installation nor account-wide coverage. | -| `session:game:capacity-execution:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory original-attempt reconciliation** | Loss of an exact execution or denying record leaves its outcome indeterminate and keeps the Account reservation held. | Game Session retains the exact attempt, evidence and precharged capacity for unresolved attempts in its durable owner boundary. Prove current storage custody and reconcile the complete affected inventory before reopening. Never recreate a prior outcome from absence or historical authorization. See [original NEW capacity execution evidence](./microservices/game-session-service/runtime-and-data.md#original-new-capacity-execution-evidence). | +| `session:game:capacity-execution:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory original-attempt reconciliation** | Region and tenant resets preserve this family. A cluster reset requires the [Coordination reset qualification](#coordination-reset-model). Loss of an exact execution or denying record leaves its outcome indeterminate and keeps the Account reservation held. | Game Session retains the exact attempt, evidence and precharged capacity for unresolved attempts in its durable owner boundary. Prove current storage custody and reconcile the complete affected inventory before reopening. Never recreate a prior outcome from absence or historical authorization. See [original NEW capacity execution evidence](./microservices/game-session-service/runtime-and-data.md#original-new-capacity-execution-evidence). | | `session:game:index:account-tenant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-qualified account lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant-scoped resume, takeover, and bounded revocation remain fenced until Game Session rebuilds it and the matching session/index obligations are acknowledged. Each index member remains an active `sessionId` value under the owner-defined schema. Reconciliation is inventory-led: it derives the exact expected active `sessionId` set from authoritative durable `GameplayBindingInventory` rows; each row's complete `bindingRef` and tenant/game/session identity supply `gameInstanceId` and directly address its canonical session record. Before deriving or writing a member or accepting readback, it exact-compares the row's canonical binding-owner `accountId` with the key's ``; a missing, malformed, or mismatched owner is rejected or quarantined and keeps the affected account/index scope fenced. It independently validates the exact session record, including controller identity `{tenantId, playableStateNamespaceId, characterId}`, server-derived `playableStateScope`, `gameInstanceId`, `bindingGeneration`, and lifecycle, then reads back the expected `sessionId` set before acknowledging the matching index/session obligations. Reconciliation never infers `gameInstanceId` from a bare member and does not use wildcard scans or invent a separate resolver. This consumes the existing owner-defined schema and producers; it does not change them. | Tenant-scoped and part of the shard-local session CAS. Reconciliation is limited to the gameplay tag and validates the canonical session record rather than treating index membership as authoritative. | | `session:game:index:tenant:{tenantGameplayTag}` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-wide active-session lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant revocation, inspection, and repair remain fenced until Game Session rebuilds or reconciles and reads back the tenant index. | Tenant-scoped and shard-local. Reconciliation must not use the global account index as a substitute or admit a binding from tenant-local key presence alone. | | `session:game:index:realm-grant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the lifecycle-bound private/playtest grant lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Reset tooling enumerates the complete expected tuple set from the exact Account v1 inventory, obtains every key through the shared `grant/v1` lifecycle-qualified realm-grant index builder, and keeps realm admission and grant-driven revocation fenced until Game Session rebuilds or reconciles and reads back those exact entries under current Account grant authority. | `grantScopeId` is the exact canonical scope ID for the complete Account-owned tuple. Reset and reconciliation never concatenate world/realm selectors or other tuple fields independently. The entries are tenant-scoped, shard-local bounded lookup evidence; Account state remains authoritative, and stale, wrong-lifecycle, or cross-tenant entries are removed. Public-production and unscoped bindings have no entry. | 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 40a281347a..f3439c22a5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -30,9 +30,9 @@ The Account source/transport foundation contains unregistered TENANT_OPERATION a Account capacity activation requires an explicit finite V1040.2 refusal budget for each supported tenant. The controlled fixtures install their own limit. A production budget writer, policy sizing and readiness proof for existing tenants remain open. A missing budget leaves the exact attempt and Game Session evidence charge held. -V1065.0.5 adds explicit tenant evidence budgets and immutable per-attempt storage charges. V1065.0.6 permits one-way settlement of an exact unused charge with the Account-owned durable quota refusal receipt. Active execution capacity and total retained history are independently bounded. Account and Game Session retain their original evidence across retries. The local final-admission path obtains a charge before Account commits, and new Game Session execution rows must match it. Physical tests cover count and byte exhaustion independently, concurrent last-slot claims, exact replay, absent-key fencing at capacity, refusal after Redis reset or restoration of older execution evidence, and a populated catalog upgrade. A staged refusal keeps unresolved holds intact. The staged cut has no production budget or predecessor backfill. V1065.0.7 reserves tenant SQL transfer history before the freeze commits, covering the parent and two retained payloads per unresolved execution. A prior frozen transfer can complete and replay at exhaustion. Deployment-wide sizing, coordinated operational restore, evidence retirement, registration and activation remain open. The [Game Session execution owner](../../architecture/microservices/game-session-service/runtime-and-data.md#original-new-capacity-execution-evidence) defines the charge and hold boundary. +V1065.0.5–V1065.0.7 prepare execution evidence budgets, exact Account denial settlement and transfer inventory reservation under the [Game Session execution owner](../../architecture/microservices/game-session-service/runtime-and-data.md#original-new-capacity-execution-evidence). Physical proof covers independent count and byte exhaustion, concurrent last-slot claims, exact replay, absent-key fencing at capacity, stale or restored Redis evidence, a populated catalog upgrade, and frozen-transfer completion and replay at exhaustion. Production budgets, predecessor backfill, deployment-wide sizing, coordinated restore, retention policy, registration and activation remain open. -The Game Session parent owns original-NEW execution, exact local readback, first owner installation and same-grant reuse. An installed owner stays held when a caller presents a replacement grant. The immediate receiving slice owns normal handoff and its protected proof. Authenticated Account recovery read and physical cross-service proof follow. Registration and admission remain held. +The Game Session parent slice builds on the Account capacity foundation. It owns original-NEW execution, its exact local read/proof, and normal owner handoff. The authenticated Account recovery read and physical cross-service proof remain in the dependent receiving slice. The selected owner retains its original execution and handoff evidence while registration and admission remain held. The [shared capacity-admission/v1 schema](../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json), typed contract/digest, exact-presence proto/codec, bounded unregistered Account mTLS receiver, and unregistered [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java) are locally prepared. The complete existing Account bundle is strictly decoded and bound byte-for-byte in the ADR 0047 grammar, including its snapshot/evaluation identities, entitlement fields, authority tuple, billing cutoff and all checkpoints. It is never replaced by a quota read, subset or digest-only surrogate. Game Session and World contexts remain distinct, and the receiver derives the exact workload from TLS rather than a serialized identity. @@ -60,9 +60,9 @@ On local working postimages based on `fb56d3bc465155644323c472496e91e3a0433853`, Remaining qualification includes these exact-source checks, complete Account rearm/stale-worker concurrency through the final owner, deployed source/PKI/Redis custody, source registration and fresh packaged runtime proof. Positive terminal replay is durable only after independent immutable actual-outcome retention. The owner-local continuation now recovers a positive final effect across both pre-receipt and pre-retention crash windows without the original credential or grant; the existing closure lifecycle calls it before refusing negative closure. Ordinary replacement remains blocked by unresolved custody; the separately prepared normal-handoff path below excludes future effects without resolving the retained outcome. The original crash-window, owner-movement and missing-evidence regressions passed within all 22 physical cases of `CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest` on published `c86fae5627edae298e4bbe081091a6bfb3a515ef`: [Validation run 43014202533](https://github.com/benhook1013/FireMUD/actions/runs/43014202533), Game Session partition 3 job `130501225239`, artifact `13853837619`, with zero failures, errors or skips. The retained manifest and source blobs bind that artifact to synthetic merge `6729f6ec9d93ff3cd2b2c266e54488aa1829f6d3` and its exact `d8a3912268398daeb0e0ac90a3e8e48d1dd04301` / `c86fae5627edae298e4bbe081091a6bfb3a515ef` parents. This is historical component proof, not physical execution of the subsequent normal-handoff batch. Serving retirement must await retained proof, and this does not supply the missing real cleanup or teardown owner. Missing current region-owner/fence evidence also stays indeterminate. A genuine never-admitted cleanup owner for this already-acknowledged PROVISIONAL boundary is missing: the existing owner supports only untouched PREPARED dispatches and must not be forced across that boundary. Complete finalized-usage retirement on actual runtime teardown remains unfinished. No bean, scheduled worker, production route or public admission is enabled, and issuer-partition capacity is not tenant capacity. -The immediate [normal-handoff receiving slice](../../architecture/microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing) owns the protected observation, region census and revalidation, deny-only fencing and successor installation. This parent retains V1065 storage, exact SQL guards and original execution evidence. An unqualified owner replacement remains held. +The new [normal-handoff source](../../architecture/microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing) prepares V1065 transfer custody, bounded region census/verification, real signed transfer-purpose currentness and deny-only tenant-slot fencing through the actual lease-owner path. New physical definitions cover abrupt process stop after the real SQL authorization commit, native handoff, predecessor Lua rejection, positive-retention refusal, current marker loss, Account hold/quarantine preservation and retained catalog upgrade. On the integrated local postimages, canonical V1065 jOOQ generation, production and Game Session integration-source compilation, both service Java format checks and documentation checks pass. The focused signed transfer-observation suite passes 101 cases and the Account workload-identity suite passes two cases, with zero failures, errors or skips. Initial compilation exposed a Jackson 3 checked-exception mismatch and generic AssertJ inference in the concurrency definitions; both were corrected before the passing checks. The multi-page/concurrency definitions use controlled reservation envelopes, separate from actual Account composition. All new physical PostgreSQL/Redis execution, complete affected static analysis and final published-source qualification remain pending. Production attestor custody, storage continuity, registration, runtime activation and admission remain held. -The [Account recovery owner](../../architecture/microservices/account-service/runtime-and-data.md) prepares bounded read, exact late positive finalization and durable quarantine. Authenticated recovery composition, production signer custody, registration, operational recovery and activation remain open. +The [Account recovery owner](../../architecture/microservices/account-service/runtime-and-data.md) prepares bounded read, exact late positive finalization and durable quarantine. Controlled proof covers late and ambiguous results, saturation and an active owner refusing a transfer before freeze. The handoff retains a single deadline across source selection and installation revalidation. The combined selected Java units passed 135 cases and the shared Python literal corpus passed four. The physical blocked-selection, pre-install revalidation, recovery and quarantine cases were unrun at that checkpoint. Audited Account remediation and deployed source, Redis and transport custody remain activation prerequisites. At receiving source `037770fe`, the [staged Game Session physical job](https://github.com/benhook1013/FireMUD/actions/runs/43201656649/job/131126337971) passed three exact cases without failures, errors or skips. The verified artifact covers handoff of an already committed original, a real SQL authorization followed by process stop before Redis send, and the 65-original bounded census. This evidence belongs to that source and preserves the separate runtime and teardown holds. diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 7cd5c23200..8b4ef78e01 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -190,6 +190,7 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledInitialObservationFixture*.class") + include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture*.class") include("net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture*.class") } 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 8e6a1240a1..d298c3fb58 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 @@ -81,6 +81,27 @@ public final class CanonicalGameplayBindingInventoryRepository { this.dsl = Objects.requireNonNull(dsl, "dsl"); } + /** Handoff reads retain this repository's exact provider and the caller's frozen deadline. */ + T withinTransferRead( + java.time.Clock clock, + long absoluteDeadlineMillis, + java.util.function.Function read) { + requireNoAmbientTransaction(); + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + clock, + absoluteDeadlineMillis, + budget -> read.apply(new CanonicalGameplayBindingInventoryRepository(budget.sql(dsl)))); + } + + /** Reuses a retained handoff permit while keeping this read's scoped SQL provider. */ + T withinTransferRead( + CanonicalGameplayOriginalNewCapacityExecutionBudget retainedBudget, + java.util.function.Function read) { + requireNoAmbientTransaction(); + Objects.requireNonNull(retainedBudget, "retainedBudget").check(); + return read.apply(new CanonicalGameplayBindingInventoryRepository(retainedBudget.sql(dsl))); + } + CanonicalGameplayBindingTransitionSnapshot prepare( CanonicalGameplayBindingTransitionRequest request) { Objects.requireNonNull(request, "request"); @@ -859,15 +880,62 @@ CanonicalGameplayBindingTransitionSnapshot markOriginalNewCandidateProvisional( */ OriginalNewFinalAdmissionSource readOriginalNewFinalAdmissionSource( CanonicalGameplayAdmissionDecision originalDecision) { + return readOriginalNewSource(originalDecision, OriginalNewSourcePurpose.FINAL_ADMISSION); + } + + /** + * Reads a retained COMMITTED original only as topology input for normal region handoff. + * + *

This terminal observation is deliberately separate from the current final-admission source: + * it preserves the original member-repair acknowledgement and final receipt while permitting a + * later Account-wide fence to make that acknowledgement stale for admission. + */ + OriginalNewFinalAdmissionSource readOriginalNewRegionTopologyObservation( + UUID transitionId, CanonicalGameplayOriginalNewCandidate expectedOriginal) { + Objects.requireNonNull(transitionId, "transitionId"); + Objects.requireNonNull(expectedOriginal, "expectedOriginal"); + if (!transitionId.equals(expectedOriginal.bindingDecisionId())) { + throw conflict("Region topology observation changed its original transition"); + } + var decision = + new CanonicalGameplayAdmissionDecision( + transitionId, + expectedOriginal.leaseEvidence(), + expectedOriginal.bindingIdentity(), + expectedOriginal.transition().bindingGeneration(), + null, + expectedOriginal.targetEvidence()); + OriginalNewFinalAdmissionSource current = + readOriginalNewSource(decision, OriginalNewSourcePurpose.REGION_TOPOLOGY); + if (current.transitionStatus() != CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED + || !expectedOriginal.equals(current.candidate()) + || current.finalReceipt().isEmpty()) { + throw conflict("Region topology observation lacks the exact retained committed original"); + } + return current; + } + + private OriginalNewFinalAdmissionSource readOriginalNewSource( + CanonicalGameplayAdmissionDecision originalDecision, OriginalNewSourcePurpose purpose) { Objects.requireNonNull(originalDecision, "original Account decision"); requireNoAmbientTransaction(); return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); BigInteger revision = lockInventoryRevision(transaction); - requireNoActiveAccountControl( - lockExistingAccountCoverageControl( - transaction, originalDecision.candidate().accountId())); + Record accountControl = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_account_coverage_control " + + "WHERE account_id = ? FOR UPDATE", + originalDecision.candidate().accountId()); + if (accountControl == null) { + throw conflict( + "Account coverage control row is missing; absence is not no-active proof"); + } + if (purpose == OriginalNewSourcePurpose.FINAL_ADMISSION) { + requireNoActiveAccountControl( + toAccountCoverageControl(accountControl, originalDecision.candidate().accountId())); + } String runtimeStatus = lockLeaseBoundRuntimeBeforeTransition( transaction, @@ -888,6 +956,9 @@ OriginalNewFinalAdmissionSource readOriginalNewFinalAdmissionSource( if (row == null) throw conflict("Original NEW transition is missing"); String status = row.get("status", String.class); boolean committed = "COMMITTED".equals(status); + if (purpose == OriginalNewSourcePurpose.REGION_TOPOLOGY && !committed) { + throw conflict("Region topology observation requires a committed original NEW"); + } if (!committed && !"PROVISIONAL".equals(status)) { throw conflict("Only a provisional or committed original NEW can be a final source"); } @@ -1017,7 +1088,13 @@ OriginalNewFinalAdmissionSource readOriginalNewFinalAdmissionSource( throw conflict("Original NEW account obligation is not exact"); } requireCompletedMemberRepairAcknowledgement( - transaction, transition, entry, obligations.getFirst()); + transaction, + transition, + entry, + obligations.getFirst(), + purpose == OriginalNewSourcePurpose.REGION_TOPOLOGY, + accountControl, + revision); CanonicalGameplayIssuerBindingLocalAcknowledgement issuerAcknowledgement = requireOriginalNewFinalIssuerAcknowledgement( transaction, candidate, transition, committed); @@ -1051,6 +1128,237 @@ OriginalNewFinalAdmissionSource readOriginalNewFinalAdmissionSource( }); } + /** Pins original identity only; ordinary provisional handoff needs no final ACK capability. */ + CanonicalGameplayOriginalNewCandidate readRegionTransferOriginalCandidate( + UUID transitionId, CanonicalGameplayBindingProvisionalCasEvidence expectedOriginal) { + requireNoAmbientTransaction(); + Objects.requireNonNull(expectedOriginal, "expected original placement"); + if (!expectedOriginal.transition().transitionId().equals(transitionId) + || expectedOriginal.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || expectedOriginal.expectedPrior() != null) { + throw conflict("Region transfer requires its exact original provisional placement"); + } + CanonicalGameplayAdmissionDecision decision = + dsl.transactionResult( + configuration -> + toAdmissionDecision( + readTransition(DSL.using(configuration), transitionId), expectedOriginal)); + return CanonicalGameplayOriginalNewCandidate.fromOriginalSources(expectedOriginal, decision); + } + + /** + * Selects an already-retained committed original as topology evidence for a first handoff. This + * source is terminal-only and never reconstructs provisional CAS authority. + */ + Optional readRegionTransferCommittedSource(UUID transitionId) { + requireNoAmbientTransaction(); + Objects.requireNonNull(transitionId, "transitionId"); + CanonicalGameplayOriginalNewCandidate candidate = + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record row = readTransition(transaction, transitionId); + if (row == null) throw conflict("Region transfer original transition is missing"); + String status = row.get("status", String.class); + if ("PROVISIONAL".equals(status)) return null; + if (!"COMMITTED".equals(status)) { + throw conflict("Region transfer original has no committed topology source"); + } + byte[] candidateBytes = row.get("original_new_candidate_bytes", byte[].class); + try { + if (candidateBytes == null + || candidateBytes.length == 0 + || candidateBytes.length + > CanonicalGameplayOriginalNewCandidateCodec.MAX_CANDIDATE_BYTES) { + throw conflict("Committed original has no bounded retained candidate"); + } + try { + return CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); + } catch (RuntimeException malformed) { + throw conflict("Committed original candidate bytes are not canonical"); + } + } finally { + if (candidateBytes != null) Arrays.fill(candidateBytes, (byte) 0); + } + }); + if (candidate == null) return Optional.empty(); + return Optional.of( + readRegionTransferCommittedSource(transitionId, candidate) + .orElseThrow( + () -> conflict("Committed topology source changed during exact revalidation"))); + } + + /** Only an explicitly observed COMMITTED original selects the strict terminal source path. */ + Optional readRegionTransferCommittedSource( + UUID transitionId, CanonicalGameplayOriginalNewCandidate expectedOriginal) { + requireNoAmbientTransaction(); + Objects.requireNonNull(expectedOriginal, "pinned original transfer candidate"); + if (!expectedOriginal.bindingDecisionId().equals(transitionId)) { + throw conflict("Region transfer changed its original transition"); + } + boolean committed = + dsl.transactionResult( + configuration -> { + var transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record row = readTransition(transaction, transitionId); + if (row == null) throw conflict("Region transfer original transition is missing"); + String status = row.get("status", String.class); + if ("COMMITTED".equals(status)) return true; + if (!"PROVISIONAL".equals(status)) { + throw conflict("Region transfer original has no current installation lifecycle"); + } + var provisional = loadProvisionalCasEvidence(transaction, transitionId, false); + var decision = toAdmissionDecision(row, provisional); + if (!expectedOriginal.equals( + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + provisional, decision))) { + throw conflict( + "Region transfer original differs from its current provisional source"); + } + return false; + }); + if (!committed) return Optional.empty(); + var current = readOriginalNewRegionTopologyObservation(transitionId, expectedOriginal); + if (current.transitionStatus() != CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED + || !expectedOriginal.equals(current.candidate())) { + throw conflict("Region transfer committed source differs from the pinned original"); + } + return Optional.of(current); + } + + /** + * Revalidates an exact retained first-NEW Account abort for transfer topology only. The abort + * remains terminal and this method never constructs provisional or final-admission evidence. + */ + Optional readRegionTransferAbortedCandidate( + UUID transitionId, CanonicalGameplayOriginalNewCandidate expectedOriginal) { + requireNoAmbientTransaction(); + Objects.requireNonNull(expectedOriginal, "pinned original transfer candidate"); + if (!expectedOriginal.bindingDecisionId().equals(transitionId)) { + throw conflict("Region transfer changed its original transition"); + } + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record row = readTransition(transaction, transitionId); + if (row == null) throw conflict("Region transfer original transition is missing"); + if (!"ABORTED".equals(row.get("status", String.class))) return Optional.empty(); + var aborted = loadFirstNewAdmissionAbortSource(transaction, transitionId, false, true); + if (!aborted.isAccountAborted() + || !sameRegionTransferCandidate(expectedOriginal, aborted)) { + throw conflict( + "Region transfer retained Account abort differs from its pinned original"); + } + return Optional.of(expectedOriginal); + }); + } + + private static boolean sameRegionTransferCandidate( + CanonicalGameplayOriginalNewCandidate expected, + CanonicalGameplayAdmissionAbortSource aborted) { + var transition = aborted.transition(); + var expectedTransition = expected.transition(); + var reservation = aborted.reservation(); + var expectedReservation = expected.reservation(); + return expected.bindingIdentity().equals(aborted.candidate().identity()) + && expected + .leaseEvidence() + .canonicalJson() + .equals(aborted.originalDecision().leaseEvidenceJson()) + && expected.targetEvidence().equals(aborted.originalDecision().targetEvidence()) + && expectedTransition.transitionId().equals(transition.transitionId()) + && expectedTransition.bindingRef().equals(transition.bindingRef()) + && expectedTransition.bindingGeneration().equals(transition.bindingGeneration()) + && expectedTransition.issuerReservationId().equals(transition.issuerReservationId()) + && expectedTransition.reservationFence().equals(transition.reservationFence()) + && expectedTransition + .candidateAccountIndexFence() + .equals(transition.candidateAccountIndexFence()) + && expectedReservation.reservationId().equals(reservation.reservationId()) + && expectedReservation.ownerBindingRef().equals(reservation.owner().bindingRef()) + && expectedReservation.bindingGeneration().equals(reservation.bindingGeneration()) + && expectedReservation.transitionId().equals(reservation.transitionId()) + && expectedReservation.partitionId().equals(reservation.partitionId()) + && expectedReservation.reservationFence().equals(reservation.reservationFence()) + && expectedReservation + .issuerCoverageOperationId() + .equals(reservation.issuerCoverageOperationId()) + && expectedReservation + .issuerCoverageOperationFence() + .equals(reservation.issuerCoverageOperationFence()) + && expectedReservation.coverageFence().equals(reservation.coverageFence()) + && expectedReservation + .inventorySnapshotRevision() + .equals(reservation.inventorySnapshotRevision()); + } + + /** Revalidates actual final lifecycle/receipts; never presents COMMITTED as provisional work. */ + OriginalNewFinalAdmissionSource readRegionTransferOriginalSource( + UUID transitionId, OriginalNewFinalAdmissionSource expectedOriginal) { + requireNoAmbientTransaction(); + Objects.requireNonNull(expectedOriginal, "pinned original transfer source"); + var candidate = expectedOriginal.candidate(); + if (!candidate.bindingDecisionId().equals(transitionId)) { + throw conflict("Region transfer changed its original transition"); + } + if ((expectedOriginal.transitionStatus() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + && expectedOriginal.transitionStatus() + != CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED) + || (expectedOriginal.transitionStatus() + == CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED + && expectedOriginal.finalReceipt().isEmpty())) { + throw conflict("Region transfer source is not a retained committed original"); + } + var current = + readOriginalNewRegionTopologyObservation(transitionId, expectedOriginal.candidate()); + if (!candidate.equals(current.candidate()) + || !expectedOriginal.candidateDigest().equals(current.candidateDigest()) + || !expectedOriginal + .originalCandidateReadbackDigest() + .equals(current.originalCandidateReadbackDigest()) + || !regionTransferAcknowledgementFields(expectedOriginal.regionAcknowledgement()) + .equals(regionTransferAcknowledgementFields(current.regionAcknowledgement())) + || !Arrays.equals( + expectedOriginal.issuerAcknowledgement().exactBytes(), + current.issuerAcknowledgement().exactBytes()) + || (expectedOriginal.finalReceipt().isPresent() + && !expectedOriginal.finalReceipt().equals(current.finalReceipt()))) { + throw conflict("Region transfer original or retained final proof changed"); + } + return current; + } + + private static List regionTransferAcknowledgementFields( + CanonicalGameplayBindingRegionBridgeObligation acknowledgement) { + // The strict source reader separately binds controller identity and current inventory revision. + // Final SQL retention advances that revision, but none of the original ACK proof may change. + return Arrays.asList( + acknowledgement.bridgeOperationId(), + acknowledgement.bridgePreimageState(), + acknowledgement.runtimeEntityId(), + acknowledgement.entityProjectionGeneration(), + acknowledgement.entityProjectionFence(), + acknowledgement.entityWorkloadNamespace(), + acknowledgement.actorOrigin(), + acknowledgement.entityReferenceDigest(), + acknowledgement.worldSourceDigest(), + acknowledgement.canonicalRegionId(), + acknowledgement.worldLifecycleEpoch(), + acknowledgement.worldLifecycleRowVersion(), + acknowledgement.worldCaptureId(), + acknowledgement.worldGraphSha256(), + acknowledgement.worldPreparationInputDigest(), + acknowledgement.executorFence(), + acknowledgement.leaseTokenCorrelation(), + acknowledgement.redisReadbackDigest(), + acknowledgement.acknowledgedAt()); + } + void requireSameProvisionalSource( CanonicalGameplayBindingProvisionalCasEvidence expected, CanonicalGameplayBindingProvisionalCasEvidence current) { @@ -4075,6 +4383,18 @@ private static void requireCompletedMemberRepairAcknowledgement( CanonicalGameplayBindingTransitionSnapshot transition, CanonicalGameplayBindingInventoryEntry candidate, CanonicalGameplayBindingAccountIndexObligation obligation) { + requireCompletedMemberRepairAcknowledgement( + transaction, transition, candidate, obligation, false, null, null); + } + + private static void requireCompletedMemberRepairAcknowledgement( + DSLContext transaction, + CanonicalGameplayBindingTransitionSnapshot transition, + CanonicalGameplayBindingInventoryEntry candidate, + CanonicalGameplayBindingAccountIndexObligation obligation, + boolean regionTopologyOnly, + Record currentAccountControl, + BigInteger currentInventoryRevision) { if (!obligation.transitionId().equals(transition.transitionId()) || obligation.ordinal() != 0 || !obligation.bindingRef().equals(candidate.bindingRef()) @@ -4099,21 +4419,152 @@ private static void requireCompletedMemberRepairAcknowledgement( throw conflict("Account-index obligation was acknowledged before its operation completed"); } requireMemberRepairObligationCurrent(operation, candidate, obligation, true); - toMemberAcknowledgement(operationRow); - Record control = - transaction.fetchOne( - "SELECT * FROM game_session_canonical_account_coverage_control WHERE account_id = ?", - operation.accountId()); - if (control == null) { - throw conflict("Acknowledged member repair lost its positive account-control row"); + var acknowledgement = toMemberAcknowledgement(operationRow); + BigInteger completedRevision = readBigInteger(operationRow, "completed_inventory_revision"); + if (!CanonicalGameplayAccountIndexMember.of(candidate) + .value() + .equals(acknowledgement.member())) { + throw conflict("Completed member repair lost its exact monotonic projection readback"); + } + if (currentInventoryRevision != null + && (completedRevision.compareTo(operation.inventorySnapshotRevision()) <= 0 + || completedRevision.compareTo(currentInventoryRevision) >= 0 + || (operation.originalObligation().projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED + && !completedRevision.equals(obligation.projectionInventoryRevision())))) { + throw conflict("Completed member repair lost its exact monotonic projection readback"); + } + if (regionTopologyOnly) { + requireRegionTopologyAccountControl( + transaction, + currentAccountControl, + operation.accountId(), + operation.accountControlEpoch()); + } else { + Record control = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_account_coverage_control WHERE account_id = ?", + operation.accountId()); + if (control == null) { + throw conflict("Acknowledged member repair lost its positive account-control row"); + } + CanonicalGameplayAccountCoverageEvidence currentControl = + accountCoverageEvidenceFromControl(control, operation.accountId()); + if (!(currentControl instanceof CanonicalGameplayAccountCoverageEvidence.NoActiveFlow) + || !transition.accountCoverageEvidence().equals(currentControl) + || !readBigInteger(control, "last_operation_fence") + .equals(operation.accountControlEpoch())) { + throw conflict("Acknowledged member repair has stale account-control state or fence epoch"); + } + } + } + + /** + * Validates the current control row without treating a later account fence as current repair + * evidence. The original acknowledgement remains bound to its frozen no-active epoch. + */ + private static void requireRegionTopologyAccountControl( + DSLContext transaction, Record control, UUID accountId, BigInteger originalRepairEpoch) { + if (control == null || !accountId.equals(control.get("account_id", UUID.class))) { + throw conflict("Region topology observation has no exact current Account control row"); } - CanonicalGameplayAccountCoverageEvidence currentControl = - accountCoverageEvidenceFromControl(control, operation.accountId()); - if (!(currentControl instanceof CanonicalGameplayAccountCoverageEvidence.NoActiveFlow) - || !transition.accountCoverageEvidence().equals(currentControl) - || !readBigInteger(control, "last_operation_fence") - .equals(operation.accountControlEpoch())) { - throw conflict("Acknowledged member repair has stale account-control state or fence epoch"); + BigInteger currentEpoch = readBigInteger(control, "last_operation_fence"); + String state = control.get("state", String.class); + if (currentEpoch.signum() < 0 || originalRepairEpoch.signum() < 0) { + throw conflict("Region topology observation has an invalid Account control epoch"); + } + if ("NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(state)) { + if (!currentEpoch.equals(originalRepairEpoch) + || control.get("current_operation_id", UUID.class) != null + || control.get("current_fence_intent_id", UUID.class) != null + || nullableBigInteger(control, "current_operation_fence") != null + || control.get("account_admission_fence", UUID.class) != null + || control.get("historical_account_admission_fence", UUID.class) != null + || control.get("coverage_fence", UUID.class) != null + || nullableBigInteger(control, "inventory_snapshot_revision") != null + || nullableBigInteger(control, "coverage_generation") != null) { + throw conflict("No-active Account control does not match the original repair epoch"); + } + return; + } + if (currentEpoch.compareTo(originalRepairEpoch) <= 0) { + throw conflict("Account fence did not advance beyond the original member-repair epoch"); + } + if ("ACQUISITION_INTENT".equals(state)) { + UUID intentId = control.get("current_fence_intent_id", UUID.class); + UUID plannedFence = control.get("account_admission_fence", UUID.class); + BigInteger intentFence = nullableBigInteger(control, "current_operation_fence"); + Record intent = + intentId == null + ? null + : transaction.fetchOne( + "SELECT operation_id, account_id, operation_fence," + + " planned_account_admission_fence, intent_state" + + " FROM game_session_canonical_account_admission_fence_intent" + + " WHERE operation_id = ? AND account_id = ? FOR SHARE", + intentId, + accountId); + if (intent == null + || control.get("current_operation_id", UUID.class) != null + || intentFence == null + || !intentFence.equals(currentEpoch) + || !Objects.equals( + plannedFence, intent.get("planned_account_admission_fence", UUID.class)) + || !intentId.equals(intent.get("operation_id", UUID.class)) + || !accountId.equals(intent.get("account_id", UUID.class)) + || !currentEpoch.equals(readBigInteger(intent, "operation_fence")) + || !"ACQUISITION_INTENT".equals(intent.get("intent_state", String.class)) + || control.get("historical_account_admission_fence", UUID.class) != null + || control.get("coverage_fence", UUID.class) != null + || nullableBigInteger(control, "coverage_generation") != null) { + throw conflict("Current Account acquisition intent is not its exact retained fence owner"); + } + return; + } + if (!"ACTIVE".equals(state) && !"HISTORICAL".equals(state)) { + throw conflict("Region topology observation cannot cross an unresolved Account fence intent"); + } + UUID operationId = control.get("current_operation_id", UUID.class); + BigInteger operationFence = nullableBigInteger(control, "current_operation_fence"); + UUID coverageFence = control.get("coverage_fence", UUID.class); + UUID accountAdmissionFence = control.get("account_admission_fence", UUID.class); + UUID historicalAccountAdmissionFence = + control.get("historical_account_admission_fence", UUID.class); + boolean active = "ACTIVE".equals(state); + if (operationId == null + || operationFence == null + || operationFence.signum() <= 0 + || !operationFence.equals(currentEpoch) + || coverageFence == null + || NIL_UUID.equals(coverageFence) + || (active + ? accountAdmissionFence == null + || NIL_UUID.equals(accountAdmissionFence) + || historicalAccountAdmissionFence != null + : accountAdmissionFence != null + || historicalAccountAdmissionFence == null + || NIL_UUID.equals(historicalAccountAdmissionFence))) { + throw conflict("Current Account fence control tuple is incomplete or inconsistent"); + } + + Record operation = + transaction.fetchOne( + "SELECT operation_id, account_id, lifecycle, operation_fence, coverage_fence," + + " account_admission_fence, historical_account_admission_fence" + + " FROM game_session_canonical_account_coverage_operation " + + "WHERE operation_id = ? AND account_id = ? FOR SHARE", + operationId, + accountId); + if (operation == null + || !state.equals(operation.get("lifecycle", String.class)) + || !operationFence.equals(readBigInteger(operation, "operation_fence")) + || !coverageFence.equals(operation.get("coverage_fence", UUID.class)) + || !Objects.equals( + accountAdmissionFence, operation.get("account_admission_fence", UUID.class)) + || !Objects.equals( + historicalAccountAdmissionFence, + operation.get("historical_account_admission_fence", UUID.class))) { + throw conflict("Current Account fence row differs from its retained operation"); } } @@ -6127,6 +6578,11 @@ enum OriginalNewCandidateInstallationProvenance { HISTORICAL_READBACK_CONFIRMED } + private enum OriginalNewSourcePurpose { + FINAL_ADMISSION, + REGION_TOPOLOGY + } + /** * Durable SQL source for final admission. Its candidate installation is explicitly historical; * this capability contains no claim that the non-admitting preimage remains in Redis. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudget.java index 7320479209..0d47950a43 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudget.java @@ -73,6 +73,7 @@ final class CanonicalGameplayOriginalNewCapacityExecutionBudget { private Statement active; private OwnedConnection activeConnection; private int outstandingAsyncCloses; + private int outstandingRetainedWork; private boolean workerDone; private boolean cancellationStarted; private boolean cancellationDone; @@ -272,6 +273,21 @@ void retainUntilAsyncClose(CompletableFuture closeAttempt) { }); } + /** Keeps this operation's permits until borrowed work has actually exited. */ + void retainUntilCompletion(CompletableFuture work) { + Objects.requireNonNull(work); + synchronized (lifecycle) { + outstandingRetainedWork++; + } + work.whenComplete( + (ignored, failure) -> { + synchronized (lifecycle) { + outstandingRetainedWork--; + releaseIfFinished(); + } + }); + } + /** Waits for one Redis close attempt only through this operation's deadline. */ void awaitAsyncClose(CompletableFuture closeAttempt) { retainUntilAsyncClose(closeAttempt); @@ -343,11 +359,11 @@ public void release(Connection connection) throws DataAccessException { }); } - private void cancel() { + void cancel() { if (!cancelled.compareAndSet(false, true)) return; result.completeExceptionally(unavailable()); synchronized (lifecycle) { - if (workerDone) return; + if (workerDone && outstandingRetainedWork == 0) return; cancellationStarted = true; } // At most one cancellation worker per admitted operation. Its exit also owns the permit. @@ -400,11 +416,17 @@ private void releaseOutstandingConnections() { if (failure != null) throw failure; } + /** Releases SQL connections opened by one retained companion operation. */ + void releaseRetainedWorkConnections() { + releaseOutstandingConnections(); + } + private void releaseIfFinished() { if (!released && workerDone && outstandingConnections.get() == 0 && outstandingAsyncCloses == 0 + && outstandingRetainedWork == 0 && (!cancellationStarted || cancellationDone)) { released = true; OPERATIONS.release(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 4dbf7ee840..dc1b198acd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -5,6 +5,8 @@ import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_CLOSED; import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_CLOSED_OBSERVED; import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_COMMITTED_OBSERVED; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_FENCED_INDETERMINATE; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisFuture; @@ -28,6 +30,7 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.impl.DSL; @@ -563,6 +566,40 @@ private static void retainTerminal( != 1) throw unavailable(); } + void requireRetainedCommittedOriginal( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + CanonicalGameplayRegionRuntimeStatus prior) { + Record transition = + sql() + .fetchOne( + "SELECT original_new_capacity_execution_digest" + + " FROM game_session_canonical_binding_transition WHERE transition_id=?", + source.candidate().bindingDecisionId()); + if (transition == null) throw unavailable(); + String digest = transition.get(0, String.class); + Record row = + sql() + .fetchOne( + "SELECT canonical_execution FROM " + + TABLE + + " WHERE execution_digest=? AND status='COMMITTED'", + digest); + if (row == null) throw unavailable(); + var execution = CanonicalGameplayRegionOwnerTransferRepository.decode(row.get(0, byte[].class)); + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.requireExecutionBinding(source, execution); + var proof = readExact(execution.request(), execution.reservation(), false); + var receipt = + source + .finalReceipt() + .orElseThrow(CanonicalGameplayOriginalNewCapacityExecutionOwner::unavailable); + if (!"COMMITTED".equals(proof.disposition()) + || !proof.physicalDigest().equals("sha256:" + receipt.finalSessionSha256()) + || !prior.ownerInstanceId().equals(proof.currentOwnerId()) + || !prior.executorFence().equals(java.math.BigInteger.valueOf(proof.currentOwnerFence()))) { + throw unavailable(); + } + } + /** Authenticated transport calls this read-only method. Absence and contradictions throw. */ public Snapshot readExact(Request request, Result reservation) { noSql(); @@ -719,7 +756,7 @@ private static void requireSelectedOwner( .regionEpoch() .equals(java.math.BigInteger.valueOf(current.get("region_epoch", Long.class))) || !Boolean.FALSE.equals(current.get("paused", Boolean.class)) - || CanonicalGameplayRegionRuntimeStatusRepository.hasFrozenTransfer( + || CanonicalGameplayRegionOwnerTransferRepository.frozen( tx, binding.tenantId(), binding.gameInstanceId(), binding.regionId())) throw unavailable(); } @@ -747,6 +784,123 @@ void withTransferReadback(Consumer owner.fenceForTransfer(item, dispatch, deadline)); + budget.check(); + UUID dispatchId = dispatch.takeSubmission(item); + if (dispatchId == null) return readTransferFence(item, deadline); + var execution = item.execution(); + Record row = find(sql(), execution); + if (row == null) throw unavailable(); + exact(row, execution); + CanonicalGameplayCapacityEvidenceBudget.requireCharge( + sql(), execution, item.assignment().tenantGameplayTag()); + long result = + scopedFinalOwner() + .fenceCapacityExecutionOnce( + execution, + item.candidate(), + item.assignment(), + dispatchId, + budget.absoluteDeadlineMillis()); + if (result == CAPACITY_EXECUTION_COMMITTED_OBSERVED) { + // Merely seeing a COMMITTED hash must not release old-generation custody. + retainCommittedBeforeCleanup(execution.request(), execution.reservation(), deadline); + } else if (result == CAPACITY_EXECUTION_CLOSED_OBSERVED) { + if ("CLOSED".equals(row.get("status", String.class))) { + readExact(execution.request(), execution.reservation(), false); + } else { + closeOriginalAttempt(execution.request(), execution.reservation()); + } + } else if (result != CAPACITY_EXECUTION_FENCED_INDETERMINATE + && result != CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED) throw unavailable(); + return readTransferFence(item, deadline); + } + + /** Read only. In particular, a lost/reset denying hash is never recreated by verification. */ + TransferFence readTransferFence( + CanonicalGameplayRegionOwnerTransferRepository.Item item, long deadline) { + if (budget == null) return within(deadline, owner -> owner.readTransferFence(item, deadline)); + budget.check(); + var execution = item.execution(); + Map physical = readExecution(execution, item.assignment().tenantGameplayTag()); + String state = text(physical.get("state")); + UUID dispatchId = null; + boolean terminal = !"FENCED_INDETERMINATE".equals(state); + if (!terminal) { + if (physical.containsKey("fenceDispatchId")) { + String encoded = text(physical.get("fenceDispatchId")); + try { + dispatchId = UUID.fromString(encoded); + } catch (IllegalArgumentException invalid) { + throw unavailable(); + } + if (dispatchId.equals(new UUID(0, 0)) || !dispatchId.toString().equals(encoded)) + throw unavailable(); + } + if (physical.size() != (dispatchId == null ? 3 : 4) + || !Arrays.equals(execution.canonicalBytes(), physical.get("binding")) + || !execution.digest().equals(text(physical.get("digest")))) throw unavailable(); + } else { + if (!"COMMITTED".equals(state) && !"CLOSED".equals(state)) throw unavailable(); + exactPhysicalBinding(physical, execution, state); + Record retained = find(sql(), execution); + if (retained == null || !state.equals(retained.get("status", String.class))) + throw unavailable(); + // The immutable terminal reader independently proves the full retained positive/negative + // result. + readExact(execution.request(), execution.reservation(), false); + } + var output = new java.io.ByteArrayOutputStream(); + physical.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .forEach( + entry -> { + for (byte[] value : new byte[][] {bytes(entry.getKey()), entry.getValue()}) { + output.writeBytes(bytes(Integer.toString(value.length))); + output.write(':'); + output.writeBytes(value); + } + }); + return new TransferFence(execution.digest(), output.toByteArray(), dispatchId, terminal); + } + + /** Only physical inspection above constructs this future-exclusion capability. */ + static final class TransferFence { + private final String executionDigest; + private final byte[] canonicalReadback; + private final UUID completedDispatchId; + private final boolean terminal; + + private TransferFence( + String executionDigest, + byte[] canonicalReadback, + UUID completedDispatchId, + boolean terminal) { + this.executionDigest = executionDigest; + this.canonicalReadback = canonicalReadback.clone(); + this.completedDispatchId = completedDispatchId; + this.terminal = terminal; + } + + String executionDigest() { + return executionDigest; + } + + byte[] canonicalReadback() { + return canonicalReadback.clone(); + } + + boolean provesDispatchEnded(UUID expectedDispatchId) { + return terminal || expectedDispatchId.equals(completedDispatchId); + } + } + private CurrentOwner currentOwner(CanonicalGameplayOriginalNewCandidate candidate) { var binding = candidate.bindingIdentity(); Record current = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java index 8f590f928d..7fff91fc50 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -40,6 +40,8 @@ final class CanonicalGameplayProtectedIncarnationReceiver { private static final String OBSERVATION_SCHEMA = "firemud.gs.protected-incarnation-read/v1"; private static final String INITIAL_OBSERVATION_SCHEMA = "firemud.gs.protected-initial-account-barrier-read/v1"; + private static final String REGION_OWNER_TRANSFER_OBSERVATION_SCHEMA = + "firemud.gs.protected-region-owner-transfer-read/v1"; private static final String INCARNATION_BINDING_SCHEMA = "firemud.gs.protected-incarnation-binding/v1"; private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); @@ -91,6 +93,24 @@ final class CanonicalGameplayProtectedIncarnationReceiver { "tenantGameplayTag", "workloadNamespace", "allocationVersion"); + private static final Set REGION_OWNER_TRANSFER_OWNER_FIELDS = + Set.of( + "ownerKind", + "transferId", + "transferIntentDigest", + "frozenSourceDigest", + "oldRegionOwnerId", + "oldRegionOwnerFence", + "gameInstanceId", + "regionId", + "regionEpoch", + "transitionId", + "requestId", + "accountId", + "executionDigest", + "candidateDigest", + "controlState", + "completionDigest"); private static final Set EVIDENCE_FIELDS = Set.of( "deploymentIdentity", @@ -112,6 +132,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { private final CanonicalGameplayAccountAdmissionBarrierRepository intentRepository; private final CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository; + private final CanonicalGameplayRegionOwnerTransferObservationSource regionOwnerTransferSource; private final CanonicalGameplayTenantGameplayTagRepository tenantTagRepository; private final ProtectedObservationChannel observationChannel; private final TrustedConfiguration trustedConfiguration; @@ -127,6 +148,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { this( intentRepository, null, + null, tenantTagRepository, observationChannel, trustedConfiguration, @@ -144,6 +166,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { this( intentRepository, null, + null, tenantTagRepository, observationChannel, trustedConfiguration, @@ -160,6 +183,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { this( null, initialRepository, + null, tenantTagRepository, observationChannel, trustedConfiguration, @@ -167,9 +191,20 @@ final class CanonicalGameplayProtectedIncarnationReceiver { new SecureRandom()); } + static CanonicalGameplayProtectedIncarnationReceiver forRegionOwnerTransfer( + CanonicalGameplayRegionOwnerTransferObservationSource source, + CanonicalGameplayTenantGameplayTagRepository tags, + ProtectedObservationChannel channel, + TrustedConfiguration trust, + Clock clock) { + return new CanonicalGameplayProtectedIncarnationReceiver( + null, null, source, tags, channel, trust, clock, new SecureRandom()); + } + private CanonicalGameplayProtectedIncarnationReceiver( CanonicalGameplayAccountAdmissionBarrierRepository intentRepository, CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, + CanonicalGameplayRegionOwnerTransferObservationSource regionOwnerTransferSource, CanonicalGameplayTenantGameplayTagRepository tenantTagRepository, ProtectedObservationChannel observationChannel, TrustedConfiguration trustedConfiguration, @@ -177,6 +212,7 @@ private CanonicalGameplayProtectedIncarnationReceiver( SecureRandom secureRandom) { this.intentRepository = intentRepository; this.initialRepository = initialRepository; + this.regionOwnerTransferSource = regionOwnerTransferSource; this.tenantTagRepository = tenantTagRepository; this.observationChannel = observationChannel; this.trustedConfiguration = trustedConfiguration; @@ -212,15 +248,75 @@ VerifiedIncarnation observeForInitialAccountBarrier(UUID originalRequestId) { return observeCurrentContext(before, () -> loadInitialCurrentContext(originalRequestId)); } + /** + * Current-read proof for normal transfer or sealed successor currentness, never mutation + * authority. It is not reset recovery or historical no-execution proof. + */ + VerifiedIncarnation observeForRegionOwnerTransfer( + UUID transferId, long targetOrdinal, long absoluteDeadlineMillis) { + requireNoAmbientTransaction(); + requireNonNil(transferId, "transferId"); + if (targetOrdinal < 0L) { + throw new IllegalArgumentException("targetOrdinal must not be negative"); + } + requireAvailable(OwnerKind.REGION_OWNER_TRANSFER); + if (absoluteDeadlineMillis <= clock.millis()) { + throw new ObservationUnavailableException("Protected transfer observation deadline expired"); + } + try { + return regionOwnerTransferSource.withinObservation( + clock, + absoluteDeadlineMillis, + budget -> observeForRegionOwnerTransfer(transferId, targetOrdinal, budget)); + } catch (CanonicalGameplayOriginalNewCapacityExecutionBudget.BudgetUnavailable expired) { + throw new ObservationUnavailableException( + "Protected transfer observation deadline or admission unavailable"); + } + } + + VerifiedIncarnation observeForRegionOwnerTransfer( + UUID transferId, + long targetOrdinal, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + requireNoAmbientTransaction(); + requireAvailable(OwnerKind.REGION_OWNER_TRANSFER); + long absoluteDeadlineMillis = budget.absoluteDeadlineMillis(); + CurrentContext before = + loadRegionOwnerTransferCurrentContext(transferId, targetOrdinal, absoluteDeadlineMillis); + budget.check(); + return observeCurrentContext( + before, + () -> { + budget.check(); + return loadRegionOwnerTransferCurrentContext( + transferId, targetOrdinal, absoluteDeadlineMillis); + }, + absoluteDeadlineMillis); + } + private VerifiedIncarnation observeCurrentContext( CurrentContext before, java.util.function.Supplier reload) { + return observeCurrentContext(before, reload, Long.MAX_VALUE); + } + + private VerifiedIncarnation observeCurrentContext( + CurrentContext before, + java.util.function.Supplier reload, + long absoluteDeadlineMillis) { long issuedAt = clock.millis(); - if (issuedAt <= 0L) { + if (issuedAt <= 0L || absoluteDeadlineMillis <= issuedAt) { throw new ObservationUnavailableException("Protected observation clock is unavailable"); } long expiresAt; try { - expiresAt = Math.addExact(issuedAt, trustedConfiguration.observationTtlMillis()); + expiresAt = + Math.addExact( + issuedAt, + before.ownerKind() == OwnerKind.REGION_OWNER_TRANSFER + ? Math.min( + trustedConfiguration.observationTtlMillis(), + absoluteDeadlineMillis - issuedAt) + : trustedConfiguration.observationTtlMillis()); } catch (ArithmeticException overflow) { throw new ObservationUnavailableException("Protected observation time window is invalid"); } @@ -280,6 +376,7 @@ private VerifiedIncarnation observeCurrentContext( private void requireAvailable(OwnerKind ownerKind) { if ((ownerKind == OwnerKind.ACCOUNT_FENCE && intentRepository == null) || (ownerKind == OwnerKind.INITIAL_ACCOUNT_BARRIER && initialRepository == null) + || (ownerKind == OwnerKind.REGION_OWNER_TRANSFER && regionOwnerTransferSource == null) || tenantTagRepository == null || observationChannel == null || trustedConfiguration == null @@ -347,6 +444,7 @@ private CurrentContext loadCurrentContext(UUID operationId, long targetOrdinal) null, null, null, + null, null); } @@ -388,7 +486,59 @@ private CurrentContext loadInitialCurrentContext(UUID originalRequestId) { context.sourceControlState(), context.sourceControlEpoch().toString(), context.accountLoginEvidenceDigest(), - context.sourceControlDigest()); + context.sourceControlDigest(), + null); + } + + private CurrentContext loadRegionOwnerTransferCurrentContext( + UUID transferId, long targetOrdinal, long deadline) { + requireNoAmbientTransaction(); + CanonicalGameplayRegionOwnerTransferObservationSource.Context context = + regionOwnerTransferSource.readCurrent(transferId, targetOrdinal, deadline); + if (context == null + || !transferId.equals(context.transferId()) + || targetOrdinal != context.targetOrdinal()) { + throw new ObservationRejectedException("Protected transfer observation source differs"); + } + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + regionOwnerTransferSource.readAssignment( + context.transitionId(), tenantTagRepository, deadline); + if (assignment == null + || !assignment.isBindingTransition() + || !context.transitionId().equals(assignment.transitionId()) + || !context.accountId().equals(assignment.accountId()) + || !context.tenantId().equals(assignment.tenantId()) + || !context.gameInstanceId().equals(assignment.gameInstanceId()) + || !context.playableStateNamespaceId().equals(assignment.playableStateNamespaceId()) + || !context.tenantGameplayTag().equals(assignment.tenantGameplayTag()) + || !context.workloadNamespace().equals(assignment.workloadNamespace()) + || context.allocationVersion() != assignment.allocationVersion()) { + throw new ObservationRejectedException( + "Protected transfer observation differs from current transition assignment"); + } + return new CurrentContext( + OwnerKind.REGION_OWNER_TRANSFER, + context.transferId(), + context.requestId(), + context.accountId(), + null, + null, + null, + null, + null, + context.targetOrdinal(), + context.tenantId(), + context.playableStateNamespaceId(), + context.tenantGameplayTag(), + context.workloadNamespace(), + context.allocationVersion(), + null, + 0L, + null, + null, + null, + null, + context); } private VerifiedPayload verifyObservation( @@ -422,9 +572,11 @@ private VerifiedPayload verifyObservation( requireExactFields(root, ROOT_FIELDS); String expectedSchema = - expected.ownerKind() == OwnerKind.ACCOUNT_FENCE - ? OBSERVATION_SCHEMA - : INITIAL_OBSERVATION_SCHEMA; + switch (expected.ownerKind()) { + case ACCOUNT_FENCE -> OBSERVATION_SCHEMA; + case INITIAL_ACCOUNT_BARRIER -> INITIAL_OBSERVATION_SCHEMA; + case REGION_OWNER_TRANSFER -> REGION_OWNER_TRANSFER_OBSERVATION_SCHEMA; + }; requireText(root, "schema", expectedSchema); requireText(root, "attestorBinding", trustedConfiguration.attestorBinding()); requireText(root, "attestorKeyId", keyId); @@ -454,7 +606,7 @@ private VerifiedPayload verifyObservation( requireText(owner, "inventorySnapshotRevision", expected.inventorySnapshotRevision()); requireText(owner, "cohortDigest", expected.cohortDigest()); requireText(owner, "barrierTargetDigest", expected.barrierTargetDigest()); - } else { + } else if (expected.ownerKind() == OwnerKind.INITIAL_ACCOUNT_BARRIER) { requireExactFields(owner, INITIAL_OWNER_FIELDS); requireText(owner, "ownerKind", OwnerKind.INITIAL_ACCOUNT_BARRIER.name()); requireText(owner, "initializerId", expected.operationId().toString()); @@ -470,6 +622,33 @@ private VerifiedPayload verifyObservation( requireText(owner, "accountLoginEvidenceDigest", expected.accountLoginEvidenceDigest()); requireText(owner, "sourceControlDigest", expected.sourceControlDigest()); requireText(owner, "targetDigest", expected.barrierTargetDigest()); + } else { + requireExactFields(owner, REGION_OWNER_TRANSFER_OWNER_FIELDS); + var transfer = expected.regionOwnerTransferContext(); + requireText(owner, "ownerKind", OwnerKind.REGION_OWNER_TRANSFER.name()); + requireText(owner, "transferId", transfer.transferId().toString()); + requireText(owner, "transferIntentDigest", transfer.transferIntentDigest()); + requireText(owner, "frozenSourceDigest", transfer.frozenSourceDigest()); + requireText(owner, "oldRegionOwnerId", transfer.oldRegionOwnerId()); + if (requiredPositiveLong(owner, "oldRegionOwnerFence") != transfer.oldRegionOwnerFence() + || requiredPositiveLong(owner, "regionEpoch") != transfer.regionEpoch()) { + throw new ObservationRejectedException("Protected transfer owner fence or epoch differs"); + } + requireText(owner, "gameInstanceId", transfer.gameInstanceId().toString()); + requireText(owner, "regionId", transfer.regionId().toString()); + requireText(owner, "transitionId", transfer.transitionId().toString()); + requireText(owner, "requestId", transfer.requestId().toString()); + requireText(owner, "accountId", transfer.accountId().toString()); + requireText(owner, "executionDigest", transfer.executionDigest()); + requireText(owner, "candidateDigest", transfer.candidateDigest()); + requireText(owner, "controlState", transfer.controlState()); + if (transfer.completionDigest() == null) { + if (!owner.get("completionDigest").isNull()) { + throw new ObservationRejectedException("Protected FROZEN context has a completion"); + } + } else { + requireText(owner, "completionDigest", transfer.completionDigest()); + } } JsonNode target = requiredObject(root, "target"); @@ -943,7 +1122,8 @@ private static void requireDigestValue(String value, String field) { enum OwnerKind { ACCOUNT_FENCE, - INITIAL_ACCOUNT_BARRIER + INITIAL_ACCOUNT_BARRIER, + REGION_OWNER_TRANSFER } /** Discriminated current owner and exact target tuple obtained from the actual SQL owners. */ @@ -968,7 +1148,8 @@ record CurrentContext( String sourceControlState, String sourceControlEpoch, String accountLoginEvidenceDigest, - String sourceControlDigest) { + String sourceControlDigest, + CanonicalGameplayRegionOwnerTransferObservationSource.Context regionOwnerTransferContext) { CurrentContext { Objects.requireNonNull(ownerKind, "ownerKind"); Objects.requireNonNull(operationId, "operationId"); @@ -983,7 +1164,7 @@ record CurrentContext( Objects.requireNonNull(operationFence, "operationFence"); Objects.requireNonNull(cohortDigest, "cohortDigest"); Objects.requireNonNull(barrierTargetDigest, "barrierTargetDigest"); - } else { + } else if (ownerKind == OwnerKind.INITIAL_ACCOUNT_BARRIER) { Objects.requireNonNull(originalCallerContextId, "originalCallerContextId"); Objects.requireNonNull(sourceControlState, "sourceControlState"); Objects.requireNonNull(accountLoginEvidenceDigest, "accountLoginEvidenceDigest"); @@ -997,6 +1178,35 @@ record CurrentContext( throw new IllegalArgumentException( "INITIAL owner context is not the positively read NO_ACTIVE arm"); } + } else { + Objects.requireNonNull(regionOwnerTransferContext, "regionOwnerTransferContext"); + if (!operationId.equals(regionOwnerTransferContext.transferId()) + || !requestId.equals(regionOwnerTransferContext.requestId()) + || !accountId.equals(regionOwnerTransferContext.accountId()) + || targetOrdinal != regionOwnerTransferContext.targetOrdinal() + || !tenantId.equals(regionOwnerTransferContext.tenantId()) + || !playableStateNamespaceId.equals( + regionOwnerTransferContext.playableStateNamespaceId()) + || !tenantGameplayTag.equals(regionOwnerTransferContext.tenantGameplayTag()) + || !workloadNamespace.equals(regionOwnerTransferContext.workloadNamespace()) + || allocationVersion != regionOwnerTransferContext.allocationVersion() + || operationFence != null + || plannedAccountAdmissionFence != null + || inventorySnapshotRevision != null + || cohortDigest != null + || barrierTargetDigest != null + || originalCallerContextId != null + || originalAttemptFence != 0L + || sourceControlState != null + || sourceControlEpoch != null + || accountLoginEvidenceDigest != null + || sourceControlDigest != null) { + throw new IllegalArgumentException( + "Transfer context must use its separate typed owner arm"); + } + } + if (ownerKind != OwnerKind.REGION_OWNER_TRANSFER && regionOwnerTransferContext != null) { + throw new IllegalArgumentException("Transfer context cannot be used by another owner kind"); } } } @@ -1048,6 +1258,14 @@ OwnerKind ownerKind() { return context.ownerKind(); } + CanonicalGameplayRegionOwnerTransferObservationSource.Context regionOwnerTransferContext() { + if (context.ownerKind() != OwnerKind.REGION_OWNER_TRANSFER) { + throw new ObservationRejectedException( + "Protected observation is not a region-owner transfer"); + } + return context.regionOwnerTransferContext(); + } + UUID requestId() { return context.requestId(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 127d8f7f58..e9a2419998 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -1,15 +1,17 @@ package net.firedevops.firemud.gamesession.repository; +import io.grpc.Deadline; import java.math.BigInteger; import java.time.Clock; import java.time.Duration; -import java.time.Instant; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayActorOrigins; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; @@ -71,39 +73,142 @@ Installation installForTransition( Installation existingRegionInstallation, UUID transitionId, CanonicalInitialPlayerLocationRequest worldRequest) { + return installForTransition( + existingRegionInstallation, transitionId, worldRequest, null, Long.MAX_VALUE); + } + + /** + * Explicit normal handoff, using actual acquire/install/revalidation and transfer-purpose proof. + */ + Installation installForTransition( + Installation existingRegionInstallation, + UUID transitionId, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long absoluteDeadlineMillis) { requireNoAmbientTransaction(); Objects.requireNonNull(transitionId, "transitionId"); Objects.requireNonNull(worldRequest, "worldRequest"); + // Freeze the existing five-second transfer budget once, not once per inventory read. + long startedAt = clock.millis(); + final long handoffDeadline = + transferOwner == null + ? absoluteDeadlineMillis + : Math.min(absoluteDeadlineMillis, Math.addExact(startedAt, 5_000L)); + Deadline worldDeadline = worldDeadline(startedAt, handoffDeadline); + // A prior advance may have retained the positive SQL result before a later observation + // failed. Recover only its captured original, never synthetic provisional authority. + var frozenOriginal = + transferOwner != null && existingRegionInstallation == null + ? transferOwner.frozenOriginal(transitionId, handoffDeadline) + : null; + var transferTopologyCandidate = + frozenOriginal == null + ? null + : readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferAbortedCandidate( + transitionId, frozenOriginal.candidate())) + .orElse(null); + var retainedOriginal = + transferOwner == null || existingRegionInstallation != null + ? null + : frozenOriginal == null + ? readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> inventory.readRegionTransferCommittedSource(transitionId)) + .orElse(null) + : transferTopologyCandidate != null + ? null + : readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferCommittedSource( + transitionId, frozenOriginal.candidate())) + .orElse(null); CanonicalGameplayBindingProvisionalCasEvidence evidence = - readCurrentProvisionalEvidence(transitionId); - ResolvedBridgeSource initialResolved = resolveExactBridgeSource(worldRequest, evidence); + retainedOriginal != null || transferTopologyCandidate != null + ? null + : readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> readCurrentProvisionalEvidence(inventory, transitionId)); + ResolvedBridgeSource initialResolved = + retainedOriginal != null + ? resolveExactBridgeSource( + worldRequest, retainedOriginal.candidate().bindingIdentity(), worldDeadline) + : transferTopologyCandidate != null + ? resolveExactBridgeSource( + worldRequest, transferTopologyCandidate.bindingIdentity(), worldDeadline) + : resolveExactBridgeSource( + worldRequest, evidence.candidate().identity(), worldDeadline); CanonicalGameplayRegionRuntimeStatusRepository.Source source = initialResolved.source; CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation = - readCurrentIncarnation(source); + readInstallationIncarnation(transferOwner, handoffDeadline, source); long expectedRegionEpoch = - exactExpectedRegionEpoch(evidence.candidate().identity().regionEpoch()); - CanonicalGameplayRegionRuntimeStatus prior = statusRepository.find(source).orElse(null); + exactExpectedRegionEpoch( + retainedOriginal != null + ? retainedOriginal.candidate().bindingIdentity().regionEpoch() + : transferTopologyCandidate != null + ? transferTopologyCandidate.bindingIdentity().regionEpoch() + : evidence.candidate().identity().regionEpoch()); + CanonicalGameplayRegionRuntimeStatus prior = + withTransferStatusRepository( + transferOwner, handoffDeadline, repository -> repository.find(source)) + .orElse(null); + // A committed source is topology evidence only. It cannot create an initial timeline or + // establish a region owner where no predecessor owner exists. + if (retainedOriginal != null && prior == null) throw unavailable(); if (prior == null && expectedRegionEpoch != 1L) throw unavailable(); if (prior != null && prior.regionEpoch() != expectedRegionEpoch) throw unavailable(); + if (retainedOriginal != null && frozenOriginal == null) { + transferOwner.requireRetainedCommittedOriginal(retainedOriginal, prior, handoffDeadline); + } + if (frozenOriginal != null) { + if (prior == null || retainedOriginal != null && retainedOriginal.finalReceipt().isEmpty()) { + throw unavailable(); + } + transferOwner.requireFrozenOriginal(frozenOriginal, source, prior, handoffDeadline); + } + CanonicalGameplayRegionLeaseRedisOwner handoffRedisOwner = + transferOwner == null ? redisOwner : redisOwner.forHandoffDeadline(clock, handoffDeadline); + UUID transferId = null; + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource = + retainedOriginal; + CanonicalGameplayOriginalNewCandidate transferCandidate = + retainedOriginal != null ? retainedOriginal.candidate() : transferTopologyCandidate; CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; boolean reusingRegionGrant = false; if (prior == null) { if (existingRegionInstallation != null) throw unavailable(); - preparation = statusRepository.findTimelinePreparation(source).orElse(null); + preparation = + withTransferStatusRepository( + transferOwner, + handoffDeadline, + repository -> repository.findTimelinePreparation(source)) + .orElse(null); if (preparation == null) { CanonicalGameplayRegionLeaseRedisOwner.TimelineAbsenceProof absenceProof = - redisOwner.requireTimelineAbsent(source, incarnation); + handoffRedisOwner.requireTimelineAbsent(source, incarnation); preparation = - statusRepository.prepareInitialTimeline( - evidence, - worldRequest, - initialResolved.resolvedRegion, - source, - incarnation, - absenceProof, - clock.instant()); + withTransferStatusRepository( + transferOwner, + handoffDeadline, + repository -> + repository.prepareInitialTimeline( + evidence, + worldRequest, + initialResolved.resolvedRegion, + source, + incarnation, + absenceProof, + clock.instant())); } if (!statusRepository.matchesTimelinePreparation( preparation, @@ -118,51 +223,82 @@ Installation installForTransition( throw unavailable(); } try (CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization session = - redisOwner.prepareTimelineInitialization(preparation, leaseTtl, runtimeIdentity)) { - CanonicalGameplayBindingProvisionalCasEvidence beforeClaimEvidence = - readCurrentProvisionalEvidence(transitionId); - bindingInventory.requireSameProvisionalSource(evidence, beforeClaimEvidence); - ResolvedBridgeSource beforeClaimWorld = - resolveExactBridgeSource(worldRequest, beforeClaimEvidence); - requireSameSource(source, beforeClaimWorld.source); - CanonicalGameplayRegionIncarnationSource.StableEvidence beforeClaimIncarnation = - readCurrentIncarnation(source); - requireSameIncarnation(incarnation, beforeClaimIncarnation); - if (!statusRepository.matchesTimelinePreparation( - preparation, - beforeClaimEvidence, - worldRequest, - beforeClaimWorld.resolvedRegion, - source, - beforeClaimIncarnation)) { - throw unavailable(); - } + handoffRedisOwner.prepareTimelineInitialization(preparation, leaseTtl, runtimeIdentity)) { + var initializationPreparation = preparation; Optional - permit = statusRepository.beginInitialTimeline(preparation, clock.instant()); + permit = + session.runWithinRetainedPermit( + budget -> { + CanonicalGameplayBindingProvisionalCasEvidence beforeClaimEvidence = + readInstallationInventory( + transferOwner, + handoffDeadline, + budget, + inventory -> readCurrentProvisionalEvidence(inventory, transitionId)); + bindingInventory.requireSameProvisionalSource(evidence, beforeClaimEvidence); + ResolvedBridgeSource beforeClaimWorld = + resolveExactBridgeSource( + worldRequest, + beforeClaimEvidence.candidate().identity(), + worldDeadline); + requireSameSource(source, beforeClaimWorld.source); + CanonicalGameplayRegionIncarnationSource.StableEvidence + beforeClaimIncarnation = readCurrentIncarnation(source); + requireSameIncarnation(incarnation, beforeClaimIncarnation); + if (!statusRepository.matchesTimelinePreparation( + initializationPreparation, + beforeClaimEvidence, + worldRequest, + beforeClaimWorld.resolvedRegion, + source, + beforeClaimIncarnation)) { + throw unavailable(); + } + return withTransferStatusRepository( + transferOwner, + handoffDeadline, + budget, + repository -> + repository.beginInitialTimeline( + initializationPreparation, clock.instant())); + }); grant = session.initialize(permit.orElse(null)); } - redisOwner.verifyInitializedTimeline(grant, preparation); - requireSameIncarnation(incarnation, readCurrentIncarnation(source)); - ResolvedBridgeSource afterInitWorld = resolveExactBridgeSource(worldRequest, evidence); + handoffRedisOwner.verifyInitializedTimeline(grant, preparation); + requireSameIncarnation( + incarnation, readInstallationIncarnation(transferOwner, handoffDeadline, source)); + ResolvedBridgeSource afterInitWorld = + resolveExactBridgeSource(worldRequest, evidence.candidate().identity(), worldDeadline); requireSameSource(source, afterInitWorld.source); bindingInventory.requireSameProvisionalSource( - evidence, readCurrentProvisionalEvidence(transitionId)); + evidence, + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> readCurrentProvisionalEvidence(inventory, transitionId))); + var redisInitializedPreparation = preparation; preparation = - statusRepository.markRedisInitialized( - preparation, - grant.tokenCorrelation(), - CanonicalGameplayRegionBindingBridgeProofs.initialMetaDigest( - preparation.tenantRegionTag(), - preparation.operationId(), - preparation.sourceDigest()), - clock.instant()); + withTransferStatusRepository( + transferOwner, + handoffDeadline, + repository -> + repository.markRedisInitialized( + redisInitializedPreparation, + grant.tokenCorrelation(), + CanonicalGameplayRegionBindingBridgeProofs.initialMetaDigest( + redisInitializedPreparation.tenantRegionTag(), + redisInitializedPreparation.operationId(), + redisInitializedPreparation.sourceDigest()), + clock.instant())); } else { preparation = - statusRepository - .findTimelinePreparation(source) + withTransferStatusRepository( + transferOwner, + handoffDeadline, + repository -> repository.findTimelinePreparation(source)) .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); boolean sameInitializationAttempt = - preparation.transitionId().equals(evidence.transition().transitionId()); + evidence != null && preparation.transitionId().equals(transitionId); boolean matchesInitialization = sameInitializationAttempt ? statusRepository.matchesTimelinePreparation( @@ -189,59 +325,304 @@ Installation installForTransition( throw unavailable(); } if (existingRegionInstallation == null) { - // A prior owner requires normal handoff before any fresh Redis grant may be acquired. - throw unavailable(); + // A stable instance ID can survive a restart. The fresh-token acquire establishes + // scoped lease absence atomically and refuses every live incumbent or competing grant. + grant = handoffRedisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); + if (transferOwner != null) { + redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); + requireSameSource( + source, + resolveCurrentInstallationSource( + worldRequest, + evidence, + transferSource, + transferTopologyCandidate, + transferOwner, + handoffDeadline, + worldDeadline)); + requireSameIncarnation( + incarnation, readInstallationIncarnation(transferOwner, handoffDeadline, source)); + handoffRedisOwner.verifyInitializedTimeline(grant, preparation); + if (transferCandidate == null) { + transferCandidate = + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferOriginalCandidate(transitionId, evidence)); + } + CanonicalGameplayOriginalNewCandidate pinnedTransferCandidate = transferCandidate; + handoffRedisOwner.requireCurrent(grant); + transferId = + frozenOriginal == null + ? transferOwner.advance(source, prior, handoffDeadline) + : transferOwner.resume(frozenOriginal, source, prior, handoffDeadline); + // Advance may retain a COMMITTED winner and activate its SQL inventory row. Keep that + // exact terminal source separate from provisional binding/bridge authority. + transferTopologyCandidate = + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferAbortedCandidate( + transitionId, pinnedTransferCandidate)) + .orElse(null); + transferSource = + transferTopologyCandidate != null + ? null + : readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferCommittedSource( + transitionId, pinnedTransferCandidate)) + .orElse(null); + } + } else { + requireReusableRegionGrant( + existingRegionInstallation, + source, + incarnation, + prior, + expectedRegionEpoch, + transferOwner, + handoffDeadline, + handoffRedisOwner); + grant = existingRegionInstallation.grant; + reusingRegionGrant = true; } - requireReusableRegionGrant( - existingRegionInstallation, source, incarnation, prior, expectedRegionEpoch); - grant = existingRegionInstallation.grant; - reusingRegionGrant = true; } if (reusingRegionGrant) { - redisOwner.requireGrantScope( + handoffRedisOwner.requireGrantScope( grant, existingRegionInstallation.source, expectedRegionEpoch, runtimeIdentity); } else { - redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); + handoffRedisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); } CanonicalGameplayRegionRuntimeStatusRepository.Source afterAcquire = - resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); + resolveCurrentInstallationSource( + worldRequest, + evidence, + transferSource, + transferTopologyCandidate, + transferOwner, + handoffDeadline, + worldDeadline); requireSameSource(source, afterAcquire); - redisOwner.renew(grant, leaseTtl); - redisOwner.requireCurrent(grant); - requireSameIncarnation(incarnation, readCurrentIncarnation(source)); - redisOwner.verifyInitializedTimeline(grant, preparation); - - Instant installedAt = clock.instant(); - CanonicalGameplayRegionRuntimeStatus installed = - statusRepository.installOwner( + handoffRedisOwner.renew(grant, leaseTtl); + handoffRedisOwner.requireCurrent(grant); + requireSameIncarnation( + incarnation, readInstallationIncarnation(transferOwner, handoffDeadline, source)); + handoffRedisOwner.verifyInitializedTimeline(grant, preparation); + + if (transferOwner != null && clock.millis() >= handoffDeadline) throw unavailable(); + if (transferId == null) { + var installed = + withTransferStatusRepository( + transferOwner, + handoffDeadline, + repository -> + repository.installOwner( + source, + expectedRegionEpoch, + prior, + grant.tokenCorrelation(), + grant.ownerService(), + grant.ownerInstanceId(), + clock.instant())); + return verifyInstallation( + transitionId, + worldRequest, + evidence, + source, + incarnation, + preparation, + grant, + installed, + transferSource, + transferTopologyCandidate, + transferOwner, + handoffDeadline, + worldDeadline); + } + var pending = + new PendingTransfer( + this, + transferId, + transferOwner, + transitionId, + worldRequest, + evidence, source, + incarnation, + preparation, expectedRegionEpoch, - prior, - grant.tokenCorrelation(), - grant.ownerService(), - grant.ownerInstanceId(), - installedAt); + grant, + transferCandidate, + transferSource, + transferTopologyCandidate); + try { + var installed = + transferOwner.install( + transferId, + source, + prior, + grant.tokenCorrelation(), + grant.ownerService(), + grant.ownerInstanceId(), + handoffDeadline); + return verifyInstallation( + transitionId, + worldRequest, + evidence, + source, + incarnation, + preparation, + grant, + installed, + transferSource, + transferTopologyCandidate, + transferOwner, + handoffDeadline, + worldDeadline); + } catch (RuntimeException failure) { + throw new TransferCompletionUnconfirmed(pending, failure); + } + } - redisOwner.requireCurrent(grant); - redisOwner.verifyInitializedTimeline(grant, preparation); + /** + * Resumes only the same process's still-current grant after an unconfirmed transfer completion. + */ + Installation resumeCompletedTransfer( + TransferCompletionUnconfirmed interrupted, long absoluteDeadlineMillis) { + requireNoAmbientTransaction(); + var pending = Objects.requireNonNull(interrupted, "interrupted").pending; + if (pending == null || pending.owner() != this) throw unavailable(); + long startedAt = clock.millis(); + long deadline = Math.min(absoluteDeadlineMillis, Math.addExact(startedAt, 5_000L)); + if (startedAt >= deadline) throw unavailable(); + Deadline worldDeadline = worldDeadline(startedAt, deadline); + CanonicalGameplayRegionLeaseRedisOwner handoffRedisOwner = + redisOwner.forHandoffDeadline(clock, deadline); + handoffRedisOwner.requireGrantScope( + pending.grant(), pending.source(), pending.expectedRegionEpoch(), runtimeIdentity); + handoffRedisOwner.requireCurrent(pending.grant()); + handoffRedisOwner.verifyInitializedTimeline(pending.grant(), pending.preparation()); + requireSameIncarnation( + pending.incarnation(), + readInstallationIncarnation(pending.transferOwner(), deadline, pending.source())); + var installed = + pending + .transferOwner() + .recoverCompleted( + pending.transferId(), + pending.grant().ownerInstanceId(), + pending.grant().tokenCorrelation(), + deadline); + if (clock.millis() >= deadline) throw unavailable(); + var transferSource = pending.transferSource(); + var transferTopologyCandidate = pending.transferTopologyCandidate(); + if (transferSource == null && transferTopologyCandidate == null) { + // Account may have retained its definitive abort after transfer installation committed but + // before independent verification. Resolve that exact pinned original as topology only; + // neither the abort row nor its candidate restores provisional admission authority. + var pinnedCandidate = pending.transferCandidate(); + transferTopologyCandidate = + readInstallationInventory( + pending.transferOwner(), + deadline, + inventory -> + inventory.readRegionTransferAbortedCandidate( + pending.transitionId(), pinnedCandidate)) + .orElse(null); + if (transferTopologyCandidate == null) { + transferSource = + readInstallationInventory( + pending.transferOwner(), + deadline, + inventory -> + inventory.readRegionTransferCommittedSource( + pending.transitionId(), pinnedCandidate)) + .orElse(null); + } + } + return verifyInstallation( + pending.transitionId(), + pending.worldRequest(), + transferTopologyCandidate == null && transferSource == null ? pending.evidence() : null, + pending.source(), + pending.incarnation(), + pending.preparation(), + pending.grant(), + installed, + transferSource, + transferTopologyCandidate, + pending.transferOwner(), + deadline, + worldDeadline); + } + + private Installation verifyInstallation( + UUID transitionId, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatus installed, + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource, + CanonicalGameplayOriginalNewCandidate transferTopologyCandidate, + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline, + Deadline worldDeadline) { + CanonicalGameplayRegionLeaseRedisOwner handoffRedisOwner = + transferOwner == null ? redisOwner : redisOwner.forHandoffDeadline(clock, handoffDeadline); + handoffRedisOwner.requireCurrent(grant); + handoffRedisOwner.verifyInitializedTimeline(grant, preparation); CanonicalGameplayRegionRuntimeStatus observed = - statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); + withTransferStatusRepository( + transferOwner, handoffDeadline, repository -> repository.find(source)) + .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!installed.equals(observed) || observed.paused()) throw unavailable(); CanonicalGameplayRegionRuntimeStatusRepository.Source afterInstall = - resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); + resolveCurrentInstallationSource( + worldRequest, + evidence, + transferSource, + transferTopologyCandidate, + transferOwner, + handoffDeadline, + worldDeadline); requireSameSource(source, afterInstall); - redisOwner.requireCurrent(grant); - requireSameIncarnation(incarnation, readCurrentIncarnation(source)); - redisOwner.verifyInitializedTimeline(grant, preparation); - statusRepository.markTimelineInstalled(preparation, installed, clock.instant()); - redisOwner.requireCurrent(grant); - redisOwner.verifyInitializedTimeline(grant, preparation); - requireSameIncarnation(incarnation, readCurrentIncarnation(source)); + handoffRedisOwner.requireCurrent(grant); + requireSameIncarnation( + incarnation, readInstallationIncarnation(transferOwner, handoffDeadline, source)); + handoffRedisOwner.verifyInitializedTimeline(grant, preparation); + withTransferStatusRepository( + transferOwner, + handoffDeadline, + repository -> repository.markTimelineInstalled(preparation, installed, clock.instant())); + handoffRedisOwner.requireCurrent(grant); + handoffRedisOwner.verifyInitializedTimeline(grant, preparation); + requireSameIncarnation( + incarnation, readInstallationIncarnation(transferOwner, handoffDeadline, source)); requireSameSource( - source, resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId))); + source, + resolveCurrentInstallationSource( + worldRequest, + evidence, + transferSource, + transferTopologyCandidate, + transferOwner, + handoffDeadline, + worldDeadline)); CanonicalGameplayRegionRuntimeStatus finalStatus = - statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); - if (!installed.equals(finalStatus) || finalStatus.paused()) throw unavailable(); + withTransferStatusRepository( + transferOwner, handoffDeadline, repository -> repository.find(source)) + .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); + if (!installed.equals(finalStatus) + || finalStatus.paused() + || transferOwner != null && clock.millis() >= handoffDeadline) throw unavailable(); return new Installation( transitionId, worldRequest, evidence, source, incarnation, preparation, grant, installed); } @@ -252,6 +633,26 @@ private void requireReusableRegionGrant( CanonicalGameplayRegionIncarnationSource.StableEvidence currentIncarnation, CanonicalGameplayRegionRuntimeStatus currentStatus, long expectedRegionEpoch) { + requireReusableRegionGrant( + existing, + candidateSource, + currentIncarnation, + currentStatus, + expectedRegionEpoch, + null, + Long.MAX_VALUE, + redisOwner); + } + + private void requireReusableRegionGrant( + Installation existing, + CanonicalGameplayRegionRuntimeStatusRepository.Source candidateSource, + CanonicalGameplayRegionIncarnationSource.StableEvidence currentIncarnation, + CanonicalGameplayRegionRuntimeStatus currentStatus, + long expectedRegionEpoch, + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline, + CanonicalGameplayRegionLeaseRedisOwner grantOwner) { if (existing == null || !existing.owner.equals(this) || !CanonicalGameplayRegionRuntimeStatusRepository.sameRegionSource( @@ -264,8 +665,10 @@ private void requireReusableRegionGrant( } requireSameIncarnation(existing.incarnation, currentIncarnation); CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation persistedPreparation = - statusRepository - .findTimelinePreparation(existing.preparation.source()) + withTransferStatusRepository( + transferOwner, + handoffDeadline, + repository -> repository.findTimelinePreparation(existing.preparation.source())) .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!statusRepository.matchesCurrentInstalledTimelineInitialization( existing.preparation, @@ -275,10 +678,10 @@ private void requireReusableRegionGrant( currentStatus)) { throw unavailable(); } - redisOwner.requireGrantScope( + grantOwner.requireGrantScope( existing.grant, existing.source, expectedRegionEpoch, runtimeIdentity); - redisOwner.requireCurrent(existing.grant); - redisOwner.verifyInitializedTimeline(existing.grant, persistedPreparation); + grantOwner.requireCurrent(existing.grant); + grantOwner.verifyInitializedTimeline(existing.grant, persistedPreparation); } /** @@ -650,9 +1053,14 @@ private void requireOwnedContext(Installation installation, BridgeContext contex private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvidence( UUID transitionId) { + return readCurrentProvisionalEvidence(bindingInventory, transitionId); + } + + private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvidence( + CanonicalGameplayBindingInventoryRepository inventory, UUID transitionId) { requireNoAmbientTransaction(); CanonicalGameplayBindingProvisionalCasEvidence evidence = - bindingInventory.readProvisionalCasEvidence(transitionId); + inventory.readProvisionalCasEvidence(transitionId); if (evidence.transition().status() != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL || evidence.candidate().lifecycle() @@ -667,17 +1075,107 @@ private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvi return evidence; } - private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveExactSource( + private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveCurrentInstallationSource( CanonicalInitialPlayerLocationRequest request, - CanonicalGameplayBindingProvisionalCasEvidence evidence) { - return resolveExactBridgeSource(request, evidence).source; + CanonicalGameplayBindingProvisionalCasEvidence original, + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource, + CanonicalGameplayOriginalNewCandidate transferTopologyCandidate, + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline, + Deadline worldDeadline) { + if (transferSource == null) { + if (transferTopologyCandidate != null) { + var current = + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory + .readRegionTransferAbortedCandidate( + transferTopologyCandidate.bindingDecisionId(), + transferTopologyCandidate) + .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable)); + return resolveExactBridgeSource(request, current.bindingIdentity(), worldDeadline).source; + } + if (original == null) throw unavailable(); + var current = + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + readCurrentProvisionalEvidence(inventory, original.transition().transitionId())); + return resolveExactBridgeSource(request, current.candidate().identity(), worldDeadline) + .source; + } + var current = + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferOriginalSource( + transferSource.candidate().bindingDecisionId(), transferSource)); + return resolveExactBridgeSource(request, current.candidate().bindingIdentity(), worldDeadline) + .source; + } + + private T readInstallationInventory( + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline, + java.util.function.Function read) { + return transferOwner == null + ? read.apply(bindingInventory) + : bindingInventory.withinTransferRead(clock, handoffDeadline, read); + } + + private T readInstallationInventory( + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline, + CanonicalGameplayOriginalNewCapacityExecutionBudget retainedBudget, + java.util.function.Function read) { + if (transferOwner == null) return read.apply(bindingInventory); + return retainedBudget == null + ? bindingInventory.withinTransferRead(clock, handoffDeadline, read) + : bindingInventory.withinTransferRead(retainedBudget, read); + } + + private T withTransferStatusRepository( + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline, + java.util.function.Function operation) { + return transferOwner == null + ? operation.apply(statusRepository) + : transferOwner.withStatusRepository(handoffDeadline, operation); + } + + private T withTransferStatusRepository( + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline, + CanonicalGameplayOriginalNewCapacityExecutionBudget retainedBudget, + java.util.function.Function operation) { + if (transferOwner == null) return operation.apply(statusRepository); + return retainedBudget == null + ? transferOwner.withStatusRepository(handoffDeadline, operation) + : transferOwner.withStatusRepository(retainedBudget, operation); } private ResolvedBridgeSource resolveExactBridgeSource( CanonicalInitialPlayerLocationRequest request, CanonicalGameplayBindingProvisionalCasEvidence evidence) { + return resolveExactBridgeSource(request, evidence.candidate().identity(), null); + } + + private static Deadline worldDeadline(long startedAt, long absoluteDeadlineMillis) { + if (absoluteDeadlineMillis == Long.MAX_VALUE) return null; + return Deadline.after( + absoluteDeadlineMillis <= startedAt ? 0 : absoluteDeadlineMillis - startedAt, + TimeUnit.MILLISECONDS); + } + + private ResolvedBridgeSource resolveExactBridgeSource( + CanonicalInitialPlayerLocationRequest request, + CanonicalGameplayBindingIdentity identity, + Deadline operationDeadline) { requireNoAmbientTransaction(); - var identity = evidence.candidate().identity(); var target = request.getExpectedTarget(); if (!identity.accountId().toString().equals(request.getCanonicalAccountUuid()) || !identity.characterId().toString().equals(request.getCharacterUuid()) @@ -692,7 +1190,9 @@ private ResolvedBridgeSource resolveExactBridgeSource( } CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolved = - worldRegionResolver.resolve(request); + operationDeadline == null + ? worldRegionResolver.resolve(request) + : worldRegionResolver.resolve(request, operationDeadline); var assignment = resolved.lifecycleAssignment(); if (!identity.tenantId().equals(assignment.request().canonicalTenantId()) || !identity.gameInstanceId().equals(assignment.request().canonicalGameInstanceId()) @@ -729,6 +1229,20 @@ private CanonicalGameplayRegionIncarnationSource.StableEvidence readCurrentIncar return current; } + CanonicalGameplayRegionIncarnationSource.StableEvidence readInstallationIncarnation( + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline, + CanonicalGameplayRegionRuntimeStatusRepository.Source source) { + if (transferOwner == null) return readCurrentIncarnation(source); + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + clock, + handoffDeadline, + budget -> { + budget.check(); + return readCurrentIncarnation(source); + }); + } + private static void requireSameIncarnation( CanonicalGameplayRegionIncarnationSource.StableEvidence expected, CanonicalGameplayRegionIncarnationSource.StableEvidence actual) { @@ -770,6 +1284,32 @@ private static IllegalStateException unavailable() { "Canonical Game Session region owner requires current exact assignment and lease evidence"); } + private record PendingTransfer( + CanonicalGameplayRegionLeaseOwner owner, + UUID transferId, + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + UUID transitionId, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + long expectedRegionEpoch, + CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant, + CanonicalGameplayOriginalNewCandidate transferCandidate, + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource, + CanonicalGameplayOriginalNewCandidate transferTopologyCandidate) {} + + static final class TransferCompletionUnconfirmed extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final transient PendingTransfer pending; + + private TransferCompletionUnconfirmed(PendingTransfer pending, RuntimeException cause) { + super("Normal region handoff completion requires current exact verification", cause); + this.pending = pending; + } + } + /** Private construction prevents caller-created installation/readback objects. */ final class Installation { private final CanonicalGameplayRegionLeaseOwner owner; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index b5fe1dbf6f..e4685dfb51 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -25,6 +25,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; import java.util.function.Supplier; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; @@ -388,6 +389,7 @@ static final class PreparedTimelineInitialization implements AutoCloseable { private final CompletableFuture disposal = new CompletableFuture<>(); private boolean initialized; private boolean closed; + private boolean retainedWorkInFlight; private boolean initializationInFlight; private CompletableFuture boundedClose; @@ -410,12 +412,131 @@ private PreparedTimelineInitialization( this.budget = budget; } + /** + * Runs a bounded companion read under this prepared operation's retained background permit. The + * read uses its own worker and does not use or close the prepared Redis connection. + */ + T runWithinRetainedPermit( + Function operation) { + Objects.requireNonNull(operation, "operation"); + CanonicalGameplayOriginalNewCapacityExecutionBudget retainedBudget; + CompletableFuture workLifetime = new CompletableFuture<>(); + synchronized (this) { + requireNoAmbientTransaction(); + if (closed || initialized || retainedWorkInFlight) throw unavailable(); + retainedWorkInFlight = true; + retainedBudget = budget; + if (retainedBudget != null) { + retainedBudget.retainUntilCompletion(workLifetime); + workLifetime.whenComplete( + (ignored, failure) -> { + synchronized (PreparedTimelineInitialization.this) { + retainedWorkInFlight = false; + } + }); + } + } + + if (retainedBudget == null) { + try { + return operation.apply(null); + } finally { + synchronized (this) { + retainedWorkInFlight = false; + } + } + } + + CompletableFuture result = new CompletableFuture<>(); + AtomicReference workerReference = new AtomicReference<>(); + Context.CancellationListener listener = + ignored -> { + Thread worker = workerReference.get(); + if (worker != null) worker.interrupt(); + retainedBudget.cancel(); + result.completeExceptionally(unavailable()); + }; + Context caller = null; + boolean listenerRegistered = false; + boolean workerStarted = false; + Thread worker = null; + try { + caller = Context.current(); + Context workerContext = caller; + worker = + Thread.ofVirtual() + .name("game-session-region-timeline-retained-read") + .unstarted( + () -> { + Context previous = null; + T value = null; + Throwable failure = null; + try { + previous = workerContext.attach(); + retainedBudget.check(); + value = operation.apply(retainedBudget); + retainedBudget.check(); + } catch (RuntimeException | Error operationFailure) { + failure = operationFailure; + } finally { + try { + retainedBudget.releaseRetainedWorkConnections(); + } catch (RuntimeException | Error cleanupFailure) { + if (failure == null) failure = cleanupFailure; + else if (failure != cleanupFailure) failure.addSuppressed(cleanupFailure); + } finally { + try { + if (previous != null) workerContext.detach(previous); + } finally { + workLifetime.complete(null); + } + } + } + if (failure == null) result.complete(value); + else result.completeExceptionally(failure); + }); + workerReference.set(worker); + caller.addListener(listener, Runnable::run); + listenerRegistered = true; + worker.start(); + workerStarted = true; + return result.get(retainedBudget.remainingNanos(), TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + if (worker != null) worker.interrupt(); + retainedBudget.cancel(); + Thread.currentThread().interrupt(); + throw unavailable(); + } catch (ExecutionException failure) { + if (failure.getCause() instanceof RuntimeException runtime) throw runtime; + if (failure.getCause() instanceof Error error) throw error; + throw unavailable(); + } catch (TimeoutException | RuntimeException expired) { + if (workerStarted) { + worker.interrupt(); + retainedBudget.cancel(); + } else { + workLifetime.complete(null); + } + throw expired instanceof RuntimeException runtime ? runtime : unavailable(); + } catch (Error startupFailure) { + if (workerStarted) { + worker.interrupt(); + retainedBudget.cancel(); + } else { + workLifetime.complete(null); + } + throw unavailable(startupFailure); + } finally { + if (listenerRegistered) caller.removeListener(listener); + } + } + LeaseGrant initialize( CanonicalGameplayRegionRuntimeStatusRepository.InitialInitializationPermit permit) { byte[][] evalArguments; synchronized (this) { requireNoAmbientTransaction(); - if (closed || initialized) throw unavailable(); + if (closed || initialized || retainedWorkInFlight) throw unavailable(); boolean mayCreate = permit != null; if (mayCreate && (!permit.operationId().equals(preparation.operationId()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java new file mode 100644 index 0000000000..baa068c1d6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java @@ -0,0 +1,257 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.time.Clock; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import org.jooq.DSLContext; + +/** Explicit normal-handoff composition; not a receiver, scheduler, reset owner or Account owner. */ +final class CanonicalGameplayRegionOwnerTransferCoordinator { + private final DSLContext dsl; + private final Clock clock; + private final CanonicalGameplayRegionOwnerTransferRepository repository; + private final CanonicalGameplayOriginalNewCapacityExecutionOwner capacity; + private final CanonicalGameplayProtectedIncarnationReceiver observations; + + CanonicalGameplayRegionOwnerTransferCoordinator( + DSLContext dsl, + Clock clock, + CanonicalGameplayRegionOwnerTransferRepository repository, + CanonicalGameplayOriginalNewCapacityExecutionOwner capacity, + CanonicalGameplayProtectedIncarnationReceiver observations) { + this.dsl = Objects.requireNonNull(dsl); + this.clock = Objects.requireNonNull(clock); + this.repository = Objects.requireNonNull(repository); + this.capacity = Objects.requireNonNull(capacity); + this.observations = Objects.requireNonNull(observations); + } + + CanonicalGameplayRegionOwnerTransferRepository.FrozenOriginal frozenOriginal( + UUID transitionId, long deadline) { + return repository.within(deadline, ignored -> repository.frozenOriginal(transitionId)); + } + + void requireRetainedCommittedOriginal( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + CanonicalGameplayRegionRuntimeStatus prior, + long deadline) { + repository.within( + deadline, + budget -> { + capacity.forTransferBudget(budget).requireRetainedCommittedOriginal(source, prior); + return null; + }); + } + + /** Runs one lease-owner status operation through the same frozen handoff deadline. */ + T withStatusRepository( + long deadline, Function operation) { + Objects.requireNonNull(operation, "operation"); + return repository.within( + deadline, + budget -> + operation.apply(new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)))); + } + + /** Reuses a prepared region operation's permit for its final pre-claim status read/write. */ + T withStatusRepository( + CanonicalGameplayOriginalNewCapacityExecutionBudget retainedBudget, + Function operation) { + Objects.requireNonNull(retainedBudget, "retainedBudget").check(); + Objects.requireNonNull(operation, "operation"); + return operation.apply( + new CanonicalGameplayRegionRuntimeStatusRepository(retainedBudget.sql(dsl))); + } + + void requireFrozenOriginal( + CanonicalGameplayRegionOwnerTransferRepository.FrozenOriginal original, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + long deadline) { + repository.within( + deadline, + ignored -> { + repository.requireFrozenOriginal(original, source, prior); + return null; + }); + } + + UUID resume( + CanonicalGameplayRegionOwnerTransferRepository.FrozenOriginal original, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + long deadline) { + return advance(source, prior, deadline, original); + } + + /** A bounded step; incomplete progress remains durable and the caller must resume this intent. */ + UUID advance( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + long deadline) { + return advance(source, prior, deadline, null); + } + + private UUID advance( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + long deadline, + CanonicalGameplayRegionOwnerTransferRepository.FrozenOriginal original) { + return repository.within( + deadline, + budget -> { + if (original != null) repository.requireFrozenOriginal(original, source, prior); + UUID transfer = + original == null ? repository.begin(source, prior) : original.transferId(); + if (transfer == null) return null; + var owner = capacity.forTransferBudget(budget); + for (var item : repository.capture(transfer)) { + var before = observe(item, budget); + var dispatch = repository.fenceDispatch(item, before); + var physical = owner.fenceForTransfer(item, dispatch, budget.absoluteDeadlineMillis()); + var after = observe(item, budget); + repository.retainFence(item, physical, before, after); + } + // A verification round re-reads every retained marker, including older generations, + // through bounded restartable pages. It never reinstalls a missing retained fence. + long cursor = repository.verificationCursor(transfer); + List page = + repository.page(transfer, cursor); + for (var item : page) { + var before = observe(item, budget); + var actual = owner.readTransferFence(item, budget.absoluteDeadlineMillis()); + var after = observe(item, budget); + repository.retainVerification(item, actual, before, after); + } + if (!repository.finishVerification(transfer)) throw held(); + return transfer; + }); + } + + CanonicalGameplayRegionRuntimeStatus install( + UUID transferId, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + String leaseCorrelation, + String ownerService, + String ownerInstanceId, + long deadline) { + return repository.within( + deadline, + budget -> { + var first = repository.page(transferId, -1); + if (first.isEmpty()) { + return new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) + .installOwner( + source, + prior.regionEpoch(), + prior, + leaseCorrelation, + ownerService, + ownerInstanceId, + clock.instant()); + } + var before = observe(first.getFirst(), budget); + var owner = capacity.forTransferBudget(budget); + // Stream the entire frozen inventory through bounded pages under this one absolute + // operation budget. Earlier page receipts cannot hide a subsequently lost marker. + // An inventory that cannot be currently proved inside the deadline stays frozen. + owner.withTransferReadback( + reader -> { + var page = first; + while (!page.isEmpty()) { + budget.check(); + for (var item : page) { + var actual = reader.readTransferFence(item, budget.absoluteDeadlineMillis()); + repository.requireRetainedPhysical(item, actual); + } + page = repository.page(transferId, page.getLast().ordinal()); + } + }); + var after = observe(first.getFirst(), budget); + var proof = + repository.qualify(transferId, before, after, budget.absoluteDeadlineMillis()); + var installed = + new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) + .installOwner( + source, + prior.regionEpoch(), + prior, + leaseCorrelation, + ownerService, + ownerInstanceId, + clock.instant(), + proof); + // Completion grants no historical-fence exemption. The source now independently checks + // the immutable completed successor against the actual current region owner. + var completed = + observations.observeForRegionOwnerTransfer( + transferId, first.getFirst().ordinal(), budget); + if (!after.incarnationDigest().equals(completed.incarnationDigest())) throw held(); + repository.requireRetainedPhysical( + first.getFirst(), + owner.readTransferFence(first.getFirst(), budget.absoluteDeadlineMillis())); + return installed; + }); + } + + /** Rechecks the exact completed successor. This path cannot enroll, fence or install. */ + CanonicalGameplayRegionRuntimeStatus recoverCompleted( + UUID transferId, String ownerInstance, String correlation, long deadline) { + return repository.within( + deadline, + budget -> { + var completed = repository.completedSuccessor(transferId, ownerInstance, correlation); + var firstPage = repository.completedPage(transferId, -1); + if (firstPage.isEmpty()) { + repository.requireTerminalOnlyCompletion(transferId, completed); + return completed.status(); + } + var first = firstPage.getFirst(); + var before = observe(first, budget); + if (!before.incarnationDigest().equals(completed.incarnationDigest())) throw held(); + var owner = capacity.forTransferBudget(budget); + owner.withTransferReadback( + reader -> { + var page = firstPage; + while (!page.isEmpty()) { + for (var item : page) { + budget.check(); + repository.requireRetainedPhysical( + item, reader.readTransferFence(item, budget.absoluteDeadlineMillis())); + } + page = repository.completedPage(transferId, page.getLast().ordinal()); + } + }); + var after = observe(first, budget); + if (!after.incarnationDigest().equals(completed.incarnationDigest()) + || !completed.equals( + repository.completedSuccessor(transferId, ownerInstance, correlation))) { + throw held(); + } + return completed.status(); + }); + } + + private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observe( + CanonicalGameplayRegionOwnerTransferRepository.Item item, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + var value = + observations.observeForRegionOwnerTransfer(item.transferId(), item.ordinal(), budget); + if (!repository + .readCurrent(item.transferId(), item.ordinal()) + .equals(value.regionOwnerTransferContext()) + || value.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER) + throw held(); + return value; + } + + private static IllegalStateException held() { + return new IllegalStateException( + "Normal region handoff requires complete current transfer evidence"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java new file mode 100644 index 0000000000..bf2282ad5d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.time.Clock; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Current SQL transfer intent/item or sealed completion, never transfer mutation authority. */ +@FunctionalInterface +interface CanonicalGameplayRegionOwnerTransferObservationSource { + Context readCurrent(UUID transferId, long targetOrdinal); + + /** The caller waits only to the deadline. The worker keeps admission until observation exits. */ + default T withinObservation( + Clock clock, + long deadline, + Function observation) { + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + clock, deadline, observation); + } + + default Context readCurrent(UUID transferId, long targetOrdinal, long deadline) { + return readCurrent(transferId, targetOrdinal); + } + + /** Independent topology read; SQL implementations retain their operation's admitted budget. */ + default CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository tags) { + return tags.assignmentForTransition(transitionId); + } + + default CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository tags, long deadline) { + return readAssignment(transitionId, tags); + } + + /** + * One frozen item and its original owner, with its exact current control phase. A COMPLETED + * context requires independently current sealed successor evidence and is read-only currentness, + * never permission for mutation. Mutable per-item progress is deliberately excluded: completing a + * different item must not change this item's observation identity. + */ + record Context( + UUID transferId, + long targetOrdinal, + String transferIntentDigest, + String frozenSourceDigest, + String oldRegionOwnerId, + long oldRegionOwnerFence, + UUID tenantId, + UUID gameInstanceId, + UUID regionId, + long regionEpoch, + UUID transitionId, + UUID requestId, + UUID accountId, + UUID playableStateNamespaceId, + String executionDigest, + String candidateDigest, + String tenantGameplayTag, + String workloadNamespace, + int allocationVersion, + String controlState, + String completionDigest) { + public Context { + requireNonNil(transferId, "transferId"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(gameInstanceId, "gameInstanceId"); + requireNonNil(regionId, "regionId"); + requireNonNil(transitionId, "transitionId"); + requireNonNil(requestId, "requestId"); + requireNonNil(accountId, "accountId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireDigest(transferIntentDigest, "transferIntentDigest"); + requireDigest(frozenSourceDigest, "frozenSourceDigest"); + requireDigest(executionDigest, "executionDigest"); + requireDigest(candidateDigest, "candidateDigest"); + if (targetOrdinal < 0L || oldRegionOwnerFence <= 0L || regionEpoch <= 0L) { + throw new IllegalArgumentException( + "Transfer ordinal, owner fence or region epoch is invalid"); + } + if (oldRegionOwnerId == null + || oldRegionOwnerId.isBlank() + || !oldRegionOwnerId.equals(oldRegionOwnerId.trim()) + || oldRegionOwnerId.codePointCount(0, oldRegionOwnerId.length()) > 120) { + throw new IllegalArgumentException("Transfer original region owner id is invalid"); + } + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag(tenantGameplayTag); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) || allocationVersion <= 0) { + throw new IllegalArgumentException("Transfer workload or allocation version is invalid"); + } + if ("FROZEN".equals(controlState)) { + if (completionDigest != null) { + throw new IllegalArgumentException("FROZEN transfer context cannot contain a completion"); + } + } else if ("COMPLETED".equals(controlState)) { + requireDigest(completionDigest, "completionDigest"); + } else { + throw new IllegalArgumentException("Transfer observation control state is invalid"); + } + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } + + private static void requireDigest(String value, String field) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(field + " must be canonical SHA-256"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java new file mode 100644 index 0000000000..dbc2161754 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -0,0 +1,1233 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Retained normal-handoff custody. It supplies neither an execution outcome nor Account authority. + */ +final class CanonicalGameplayRegionOwnerTransferRepository + implements CanonicalGameplayRegionOwnerTransferObservationSource { + static final int PAGE_SIZE = 32; + private static final String TRANSFER = "game_session_region_owner_transfer"; + private static final String ITEM = "game_session_region_owner_transfer_item"; + // Join predicates prove the four shared identity fields equal; project them only once. + private static final String CURRENT_PROJECTION = + "SELECT t.*,r.canonical_region_id,r.tenant_region_tag,r.lifecycle_epoch," + + "r.lifecycle_row_version,r.lifecycle_request_bytes,r.capture_id,r.graph_sha256," + + "r.preparation_input_digest,r.executor_fence,r.lease_token_correlation," + + "r.owner_service,r.owner_instance_id,r.paused,r.last_committed_tick_batch_id," + + "r.last_committed_tick_id,r.updated_at FROM "; + private static final String PENDING = + " FROM game_session_original_new_capacity_execution e" + + " JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=e.transition_id" + + " WHERE b.tenant_id=? AND b.game_instance_id=? AND b.region_id=?" + + " AND e.status IN ('INSTALL_DISPATCHED','AUTHORIZED')"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private final DSLContext dsl; + private final Clock clock; + private final CanonicalGameplayTenantGameplayTagRepository tags; + private final ThreadLocal admitted = + new ThreadLocal<>(); + + CanonicalGameplayRegionOwnerTransferRepository( + DSLContext dsl, Clock clock, CanonicalGameplayTenantGameplayTagRepository tags) { + this.dsl = Objects.requireNonNull(dsl); + this.clock = Objects.requireNonNull(clock); + this.tags = Objects.requireNonNull(tags); + } + + T within( + long deadline, Function work) { + noSql(); + if (admitted.get() != null) return work.apply(admitted.get()); + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + clock, + deadline, + budget -> { + admitted.set(budget); + try { + return work.apply(budget); + } finally { + admitted.remove(); + } + }); + } + + @Override + public T withinObservation( + Clock observationClock, + long deadline, + Function observation) { + return within(deadline, observation); + } + + DSLContext sql() { + var budget = admitted.get(); + if (budget == null) throw unavailable(); + return budget.sql(dsl); + } + + /** + * Pins the captured original or the exact original whose transition became terminal before + * capture. Neither path creates a transfer, an inventory item or provisional admission authority. + */ + FrozenOriginal frozenOriginal(UUID transitionId) { + noSql(); + return sql() + .transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return readFrozenOriginal(transaction, transitionId); + }); + } + + private FrozenOriginal readFrozenOriginal(DSLContext tx, UUID transitionId) { + var rows = + tx.fetch( + "SELECT i.transfer_id,i.target_ordinal,i.execution_digest FROM " + + ITEM + + " i JOIN " + + TRANSFER + + " t ON t.transfer_id=i.transfer_id" + + " JOIN game_session_original_new_capacity_execution e ON e.execution_digest=i.execution_digest" + + " WHERE e.transition_id=? AND t.state='FROZEN' LIMIT 2", + transitionId); + if (rows.size() > 1) throw unavailable(); + if (rows.size() == 1) { + var row = rows.getFirst(); + UUID id = row.get("transfer_id", UUID.class); + current(tx, id, false); + var item = + loadItem( + tx, + id, + row.get("target_ordinal", Long.class), + row.get("execution_digest", String.class)); + return new FrozenOriginal(id, item.execution().digest(), item.candidate()); + } + + // An Account abort changes the transition, not its capacity outcome. An unresolved execution + // still belongs to the normal capture and fencing pass when this transfer resumes. + var terminalRows = + tx.fetch( + "SELECT t.transfer_id,e.execution_digest,e.canonical_execution," + + "e.selected_owner_id,e.selected_owner_fence," + + "c.original_new_candidate_bytes,c.original_new_candidate_digest" + + " FROM game_session_canonical_binding_transition c" + + " JOIN game_session_original_new_capacity_execution e ON e.transition_id=c.transition_id" + + " AND e.tenant_id=c.tenant_id AND e.request_id=c.admission_request_id" + + " AND e.admission_id=c.transition_id" + + " JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=c.transition_id" + + " JOIN " + + TRANSFER + + " t ON t.tenant_id=b.tenant_id AND t.game_instance_id=b.game_instance_id" + + " AND t.region_id=b.region_id AND t.region_epoch=b.region_epoch" + + " WHERE c.transition_id=? AND t.state='FROZEN'" + + " AND e.selected_owner_fence<=t.old_owner_fence" + + " AND c.original_new_candidate_state='READBACK_CONFIRMED'" + + " AND ((c.status='COMMITTED' AND e.status='COMMITTED'" + + " AND e.execution_digest=c.original_new_capacity_execution_digest" + + " AND c.original_new_final_session_sha256 IS NOT NULL)" + + " OR (c.status='ABORTED' AND c.admission_orphan_cleanup_id IS NOT NULL" + + " AND c.original_new_final_session_sha256 IS NULL" + + " AND e.status IN ('INSTALL_DISPATCHED','AUTHORIZED','CLOSED'))) LIMIT 2", + transitionId); + if (terminalRows.isEmpty()) return null; + if (terminalRows.size() != 1) throw unavailable(); + var row = terminalRows.getFirst(); + UUID id = row.get("transfer_id", UUID.class); + var transfer = current(tx, id, false); + byte[] candidateBytes = row.get("original_new_candidate_bytes", byte[].class); + var candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); + var execution = decode(row.get("canonical_execution", byte[].class)); + String candidateDigest = digest(candidateBytes); + var binding = candidate.bindingIdentity(); + if (!candidate.bindingDecisionId().equals(transitionId) + || !execution.transitionId().equals(transitionId) + || !execution.digest().equals(row.get("execution_digest", String.class)) + || !execution.candidateDigest().equals(candidateDigest) + || !candidateDigest.equals(row.get("original_new_candidate_digest", String.class)) + || !execution + .request() + .identity() + .requestId() + .toString() + .equals(candidate.leaseEvidence().carrier().get("requestId")) + || !execution.selectedOwnerId().equals(row.get("selected_owner_id", String.class)) + || execution.selectedOwnerFence() != row.get("selected_owner_fence", Long.class) + || execution.selectedOwnerFence() > transfer.get("old_owner_fence", Long.class) + || !binding.tenantId().equals(transfer.get("tenant_id", UUID.class)) + || !binding.gameInstanceId().equals(transfer.get("game_instance_id", UUID.class)) + || !binding.regionId().equals(transfer.get("region_id", UUID.class)) + || binding.regionEpoch().longValueExact() != transfer.get("region_epoch", Long.class)) + throw unavailable(); + requireExecutionPlayerBinding(execution, candidate); + return new FrozenOriginal(id, execution.digest(), candidate); + } + + /** Revalidate a pinned continuation without creating a replacement transfer intent. */ + void requireFrozenOriginal( + FrozenOriginal original, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior) { + noSql(); + sql() + .transaction( + configuration -> { + var tx = DSL.using(configuration); + // Bridge retries take inventory before region. Retained tag validation below must + // join this transaction, so no separate connection waits behind our own clock lock. + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(tx); + requireOldOwner(tx, source, prior); + var row = current(tx, original.transferId(), true); + if (!sourceDigest(source, prior).equals(row.get("source_digest", String.class)) + || !original.equals( + readFrozenOriginal(tx, original.candidate().bindingDecisionId()))) + throw unavailable(); + }); + } + + UUID begin( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior) { + noSql(); + String sourceDigest = sourceDigest(source, prior); + return sql() + .transactionResult( + configuration -> { + var tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + requireOldOwner(tx, source, prior); + Record old = + tx.fetchOne( + "SELECT * FROM " + TRANSFER + " WHERE old_owner_fence=?", + prior.executorFence().longValueExact()); + if (old != null) { + if (!sourceDigest.equals(old.get("source_digest", String.class)) + || !"FROZEN".equals(old.get("state", String.class))) throw unavailable(); + return old.get("transfer_id", UUID.class); + } + if (!exists( + tx, + "SELECT 1" + PENDING, + source.tenantId(), + source.gameInstanceId(), + source.regionId())) return null; + UUID id = UUID.randomUUID(); + String intentDigest = + digest(bytes("region-owner-transfer/v1/" + id + "/" + sourceDigest)); + if (tx.execute( + "INSERT INTO " + + TRANSFER + + " (transfer_id,tenant_id,game_instance_id,region_id,region_epoch,old_owner_id,old_owner_fence,old_lease_correlation,source_digest,intent_digest,state) VALUES (?,?,?,?,?,?,?,?,?,?,'FROZEN')", + id, + source.tenantId(), + source.gameInstanceId(), + source.regionId(), + prior.regionEpoch(), + prior.ownerInstanceId(), + prior.executorFence().longValueExact(), + prior.leaseTokenCorrelation(), + sourceDigest, + intentDigest) + != 1) throw unavailable(); + return id; + }); + } + + /** + * One bounded enrollment step. The final anti-join, not a cursor or page size, proves + * completeness. + */ + List capture(UUID transferId) { + noSql(); + sql() + .transaction( + configuration -> { + var tx = DSL.using(configuration); + Record transfer = current(tx, transferId, true); + var rows = + tx.fetch( + "SELECT DISTINCT e.execution_digest" + + PENDING + + " AND NOT EXISTS (SELECT 1 FROM " + + ITEM + + " i WHERE i.transfer_id=? AND i.execution_digest=e.execution_digest)" + + " ORDER BY e.execution_digest LIMIT ?", + transfer.get("tenant_id", UUID.class), + transfer.get("game_instance_id", UUID.class), + transfer.get("region_id", UUID.class), + transferId, + PAGE_SIZE); + long ordinal = + tx.fetchSingle( + "SELECT coalesce(max(target_ordinal),-1) FROM " + + ITEM + + " WHERE transfer_id=?", + transferId) + .get(0, Long.class); + for (Record row : rows) { + String executionDigest = row.get("execution_digest", String.class); + // The actual retained execution and original candidate, never a caller selector. + Record retained = + tx.fetchSingle( + "SELECT canonical_execution,tenant_gameplay_tag FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + executionDigest); + var execution = decode(retained.get("canonical_execution", byte[].class)); + ordinal = Math.incrementExact(ordinal); + String tag = retained.get("tenant_gameplay_tag", String.class); + String namespace = execution.request().targetNamespace(); + int allocation = + tags.requireRetainedAllocation( + tx, execution.request().identity().tenantId(), tag, namespace); + tx.execute( + "INSERT INTO " + + ITEM + + " (transfer_id,target_ordinal,execution_digest,canonical_execution,candidate_digest,tenant_gameplay_tag,workload_namespace,allocation_version) VALUES (?,?,?,?,?,?,?,?)", + transferId, + ordinal, + executionDigest, + execution.canonicalBytes(), + execution.candidateDigest(), + tag, + namespace, + allocation); + } + }); + List result = new ArrayList<>(); + for (Record row : + sql() + .fetch( + "SELECT target_ordinal,execution_digest FROM " + + ITEM + + " WHERE transfer_id=? AND fence_readback IS NULL ORDER BY target_ordinal LIMIT ?", + transferId, + PAGE_SIZE)) { + result.add( + readItem( + transferId, + row.get("target_ordinal", Long.class), + row.get("execution_digest", String.class))); + } + return List.copyOf(result); + } + + List page(UUID transferId, long afterOrdinal) { + current(sql(), transferId, false); + return readPage(transferId, afterOrdinal); + } + + List completedPage(UUID transferId, long afterOrdinal) { + requireCompleted(transferId); + return readPage(transferId, afterOrdinal); + } + + CompletedTransfer completedSuccessor(UUID transferId, String ownerInstance, String correlation) { + Record completed = requireCompleted(transferId); + var status = CanonicalGameplayRegionRuntimeStatusRepository.toStatus(completed); + if (status.paused() + || !ownerInstance.equals(status.ownerInstanceId()) + || !correlation.equals(status.leaseTokenCorrelation())) throw unavailable(); + return new CompletedTransfer(status, completed.get("incarnation_digest", String.class)); + } + + /** Requalifies the existing no-item installation path without synthesizing an observation. */ + void requireTerminalOnlyCompletion(UUID transferId, CompletedTransfer expected) { + var status = expected.status(); + if (expected.incarnationDigest() != null + || exists(sql(), "SELECT 1 FROM " + ITEM + " WHERE transfer_id=?", transferId)) + throw unavailable(); + Record retained = requireCompleted(transferId); + if (retained.get("incarnation_digest") != null + || !status.equals(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(retained)) + || exists( + sql(), + "SELECT 1" + PENDING + " AND e.selected_owner_fence<=?", + status.tenantId(), + status.gameInstanceId(), + status.regionId(), + retained.get("old_owner_fence", Long.class))) throw unavailable(); + } + + private Record requireCompleted(UUID transferId) { + Record completed = observationCurrent(sql(), transferId); + if (!"COMPLETED".equals(completed.get("state", String.class))) throw unavailable(); + return completed; + } + + record CompletedTransfer(CanonicalGameplayRegionRuntimeStatus status, String incarnationDigest) {} + + private List readPage(UUID transferId, long afterOrdinal) { + List result = new ArrayList<>(); + for (Record row : + sql() + .fetch( + "SELECT target_ordinal,execution_digest FROM " + + ITEM + + " WHERE transfer_id=? AND target_ordinal>? ORDER BY target_ordinal LIMIT ?", + transferId, + afterOrdinal, + PAGE_SIZE)) { + result.add( + readItem( + transferId, + row.get("target_ordinal", Long.class), + row.get("execution_digest", String.class))); + } + return List.copyOf(result); + } + + FenceDispatch fenceDispatch( + Item item, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before) { + return sql() + .transactionResult( + configuration -> { + var tx = DSL.using(configuration); + Record transfer = current(tx, item.transferId(), true); + requireObservation(readCurrent(tx, item.transferId(), item.ordinal()), before); + String incarnation = transfer.get("incarnation_digest", String.class); + if (incarnation != null && !incarnation.equals(before.incarnationDigest())) + throw unavailable(); + Record dispatched = + tx.fetchOne( + "SELECT fence_dispatch_incarnation FROM " + + ITEM + + " WHERE execution_digest=? AND fence_dispatch_id IS NOT NULL", + item.execution().digest()); + if (dispatched != null + && !before + .incarnationDigest() + .equals(dispatched.get("fence_dispatch_incarnation"))) throw unavailable(); + if (dispatched != null + || exists( + tx, + "SELECT 1 FROM " + + ITEM + + " WHERE execution_digest=? AND fence_readback IS NOT NULL", + item.execution().digest())) return new FenceDispatch(item, null); + if (clock.millis() >= before.expiresAtEpochMillis()) throw unavailable(); + UUID dispatchId = UUID.randomUUID(); + if (tx.execute( + "UPDATE " + + ITEM + + " SET fence_dispatch_id=?,fence_dispatch_incarnation=?" + + " WHERE transfer_id=? AND target_ordinal=?" + + " AND execution_digest=? AND fence_readback IS NULL AND fence_dispatch_id IS NULL", + dispatchId, + before.incarnationDigest(), + item.transferId(), + item.ordinal(), + item.execution().digest()) + != 1) throw unavailable(); + return new FenceDispatch(item, dispatchId); + }); + } + + void retainFence( + Item item, + CanonicalGameplayOriginalNewCapacityExecutionOwner.TransferFence actual, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after) { + var context = readCurrent(item.transferId(), item.ordinal()); + requireObservation(context, before); + requireObservation(context, after); + if (!before.incarnationDigest().equals(after.incarnationDigest()) + || !item.execution().digest().equals(actual.executionDigest())) throw unavailable(); + sql() + .transaction( + configuration -> { + var tx = DSL.using(configuration); + Record transfer = current(tx, item.transferId(), true); + String retained = transfer.get("incarnation_digest", String.class); + if (retained != null && !retained.equals(after.incarnationDigest())) + throw unavailable(); + tx.execute( + "UPDATE " + + TRANSFER + + " SET incarnation_digest=? WHERE transfer_id=? AND incarnation_digest IS NULL", + after.incarnationDigest(), + item.transferId()); + Record row = + tx.fetchSingle( + "SELECT * FROM " + + ITEM + + " WHERE transfer_id=? AND target_ordinal=? FOR UPDATE", + item.transferId(), + item.ordinal()); + byte[] prior = row.get("fence_readback", byte[].class); + if (prior != null && !Arrays.equals(prior, actual.canonicalReadback())) + throw unavailable(); + UUID dispatchId = row.get("fence_dispatch_id", UUID.class); + if (dispatchId != null + && (!actual.provesDispatchEnded(dispatchId) + || !before.incarnationDigest().equals(row.get("fence_dispatch_incarnation")))) + throw unavailable(); + if (exists( + tx, + "SELECT 1 FROM " + + ITEM + + " WHERE execution_digest=? AND fence_readback IS NOT NULL" + + " AND (fence_readback IS DISTINCT FROM ? OR incarnation_digest IS DISTINCT FROM ?)", + item.execution().digest(), + actual.canonicalReadback(), + after.incarnationDigest())) throw unavailable(); + tx.execute( + "UPDATE " + + ITEM + + " SET fence_readback=?,incarnation_digest=?,before_payload_digest=?,after_payload_digest=? WHERE transfer_id=? AND target_ordinal=? AND fence_readback IS NULL", + actual.canonicalReadback(), + after.incarnationDigest(), + before.payloadDigest(), + after.payloadDigest(), + item.transferId(), + item.ordinal()); + }); + } + + /** Private capability is minted only after a complete current physical verification pass. */ + Completion qualify( + UUID transferId, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after, + long deadline) { + if (clock.millis() >= deadline + || !before.incarnationDigest().equals(after.incarnationDigest()) + || !"FROZEN".equals(before.regionOwnerTransferContext().controlState()) + || !"FROZEN".equals(after.regionOwnerTransferContext().controlState())) throw unavailable(); + requireObservation(readCurrent(transferId, before.targetOrdinal()), before); + requireObservation(readCurrent(transferId, after.targetOrdinal()), after); + Record transfer = current(sql(), transferId, false); + if (!before.incarnationDigest().equals(transfer.get("incarnation_digest", String.class))) + throw unavailable(); + UUID round = transfer.get("verification_round", UUID.class); + if (round == null + || !Boolean.TRUE.equals(transfer.get("verification_complete", Boolean.class)) + || exists( + sql(), + "SELECT 1 FROM " + ITEM + " WHERE transfer_id=? AND verified_round IS DISTINCT FROM ?", + transferId, + round)) throw unavailable(); + requireComplete(sql(), transferId); + long evidenceDeadline = + Math.min(deadline, Math.min(before.expiresAtEpochMillis(), after.expiresAtEpochMillis())); + if (clock.millis() >= evidenceDeadline) throw unavailable(); + return new Completion( + transferId, + transfer.get("source_digest", String.class), + after.incarnationDigest(), + round, + evidenceDeadline, + clock); + } + + long verificationCursor(UUID transferId) { + Record transfer = current(sql(), transferId, false); + requireComplete(sql(), transferId); + if (transfer.get("verification_round") == null) { + UUID round = UUID.randomUUID(); + sql() + .execute( + "UPDATE " + + TRANSFER + + " SET verification_round=?,verification_cursor=-1,verification_complete=false WHERE transfer_id=? AND verification_round IS NULL", + round, + transferId); + return -1; + } + return transfer.get("verification_cursor", Long.class); + } + + void retainVerification( + Item item, + CanonicalGameplayOriginalNewCapacityExecutionOwner.TransferFence actual, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after) { + requireObservation(readCurrent(item.transferId(), item.ordinal()), before); + requireObservation(readCurrent(item.transferId(), item.ordinal()), after); + if (!before.incarnationDigest().equals(after.incarnationDigest())) throw unavailable(); + sql() + .transaction( + configuration -> { + var tx = DSL.using(configuration); + Record transfer = current(tx, item.transferId(), true); + if (!after + .incarnationDigest() + .equals(transfer.get("incarnation_digest", String.class))) throw unavailable(); + Record row = + tx.fetchSingle( + "SELECT fence_readback FROM " + + ITEM + + " WHERE transfer_id=? AND target_ordinal=?", + item.transferId(), + item.ordinal()); + if (!Arrays.equals( + actual.canonicalReadback(), row.get("fence_readback", byte[].class))) + throw unavailable(); + tx.execute( + "UPDATE " + + ITEM + + " SET verified_round=? WHERE transfer_id=? AND target_ordinal=?", + transfer.get("verification_round", UUID.class), + item.transferId(), + item.ordinal()); + tx.execute( + "UPDATE " + + TRANSFER + + " SET verification_cursor=? WHERE transfer_id=? AND verification_cursor readCurrent(transferId, targetOrdinal, deadline)); + if (deadline < admitted.get().absoluteDeadlineMillis()) throw unavailable(); + return sql() + .transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return readCurrent(transaction, transferId, targetOrdinal); + }); + } + + private Context readCurrent(DSLContext transaction, UUID transferId, long targetOrdinal) { + Record transfer = observationCurrent(transaction, transferId); + Record row = + transaction.fetchOne( + "SELECT execution_digest FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=?", + transferId, + targetOrdinal); + if (row == null) throw unavailable(); + Item item = + loadItem(transaction, transferId, targetOrdinal, row.get("execution_digest", String.class)); + var binding = item.candidate().bindingIdentity(); + return new Context( + transferId, + targetOrdinal, + transfer.get("intent_digest", String.class), + transfer.get("source_digest", String.class), + transfer.get("old_owner_id", String.class), + transfer.get("old_owner_fence", Long.class), + binding.tenantId(), + binding.gameInstanceId(), + binding.regionId(), + transfer.get("region_epoch", Long.class), + item.execution().transitionId(), + item.execution().request().identity().requestId(), + binding.accountId(), + binding.playableStateNamespaceId(), + item.execution().digest(), + item.execution().candidateDigest(), + item.assignment().tenantGameplayTag(), + item.assignment().workloadNamespace(), + item.assignment().allocationVersion(), + transfer.get("state", String.class), + completionDigest(transfer)); + } + + @Override + public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository sourceTags) { + return readAssignment(transitionId, sourceTags, Long.MAX_VALUE); + } + + @Override + public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository sourceTags, long deadline) { + if (admitted.get() == null) + return within(deadline, ignored -> readAssignment(transitionId, sourceTags, deadline)); + if (deadline < admitted.get().absoluteDeadlineMillis()) throw unavailable(); + return sourceTags + .withCapacityExecutionDsl(sql()) + .readAssignmentForRetainedCapacityExecution(transitionId); + } + + private static Record observationCurrent(DSLContext tx, UUID id) { + Record row = + tx.fetchOne( + CURRENT_PROJECTION + + TRANSFER + + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND r.region_epoch=t.region_epoch AND ((t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence) OR (t.state='COMPLETED' AND r.owner_instance_id=t.new_owner_id AND r.executor_fence=t.new_owner_fence AND r.lease_token_correlation=t.new_lease_correlation))", + id); + if (row == null) throw unavailable(); + var actual = CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row); + if (!"game-session-service".equals(actual.ownerService())) throw unavailable(); + String observed = + sourceDigest( + actual, + row.get("old_owner_id", String.class), + row.get("old_owner_fence", Long.class), + row.get("old_lease_correlation", String.class)); + if (!observed.equals(row.get("source_digest", String.class))) throw unavailable(); + return row; + } + + private static String completionDigest(Record transfer) { + if (!"COMPLETED".equals(transfer.get("state", String.class))) return null; + return digest( + bytes( + transfer.get("transfer_id", UUID.class) + + "/" + + transfer.get("new_owner_id", String.class) + + "/" + + transfer.get("new_owner_fence", Long.class) + + "/" + + transfer.get("new_lease_correlation", String.class))); + } + + private Item readItem(UUID transferId, long ordinal, String executionDigest) { + return sql() + .transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return loadItem(transaction, transferId, ordinal, executionDigest); + }); + } + + private Item loadItem(DSLContext tx, UUID transferId, long ordinal, String executionDigest) { + Record row = + tx.fetchOne( + "SELECT e.*,t.original_new_candidate_bytes FROM game_session_original_new_capacity_execution e JOIN game_session_canonical_binding_transition t ON t.transition_id=e.transition_id WHERE e.execution_digest=?", + executionDigest); + if (row == null) throw unavailable(); + var candidate = + CanonicalGameplayOriginalNewCandidate.parseCanonical( + row.get("original_new_candidate_bytes", byte[].class)); + var execution = decode(row.get("canonical_execution", byte[].class)); + if (!execution.digest().equals(executionDigest) + || !execution.transitionId().equals(candidate.bindingDecisionId()) + || !execution.candidateDigest().equals(digest(candidate.canonicalBytes())) + || !execution.selectedOwnerId().equals(row.get("selected_owner_id", String.class)) + || execution.selectedOwnerFence() != row.get("selected_owner_fence", Long.class) + || !execution.request().identity().requestId().equals(row.get("request_id", UUID.class)) + || !execution + .request() + .admissionAttemptId() + .equals(row.get("admission_attempt_id", UUID.class))) throw unavailable(); + var assignment = tags.readAssignmentForRetainedCapacityExecution(tx, execution.transitionId()); + if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class))) + throw unavailable(); + var binding = candidate.bindingIdentity(); + Record transfer = observationCurrent(tx, transferId); + if (!binding.tenantId().equals(transfer.get("tenant_id", UUID.class)) + || !binding.gameInstanceId().equals(transfer.get("game_instance_id", UUID.class)) + || !binding.regionId().equals(transfer.get("region_id", UUID.class)) + || binding.regionEpoch().longValueExact() != transfer.get("region_epoch", Long.class) + || execution.selectedOwnerFence() > transfer.get("old_owner_fence", Long.class)) + throw unavailable(); + Record retained = + tx.fetchOne( + "SELECT * FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=?", + transferId, + ordinal); + if (retained == null + || !executionDigest.equals(retained.get("execution_digest", String.class)) + || !Arrays.equals( + execution.canonicalBytes(), retained.get("canonical_execution", byte[].class)) + || !execution.candidateDigest().equals(retained.get("candidate_digest", String.class)) + || !assignment.tenantGameplayTag().equals(retained.get("tenant_gameplay_tag", String.class)) + || !assignment.workloadNamespace().equals(retained.get("workload_namespace", String.class)) + || assignment.allocationVersion() != retained.get("allocation_version", Integer.class)) + throw unavailable(); + requireExecutionPlayerBinding(execution, candidate); + return new Item(transferId, ordinal, execution, candidate, assignment); + } + + private static void requireExecutionPlayerBinding( + OriginalNewCapacityExecution execution, CanonicalGameplayOriginalNewCandidate candidate) { + var player = (TenantCapacityAdmission.PlayerContext) execution.request().context(); + var binding = candidate.bindingIdentity(); + if (!binding.accountId().equals(player.accountId()) + || !binding.tenantId().equals(player.tenantId()) + || !binding.gameInstanceId().equals(player.gameInstanceId()) + || !binding.playableStateNamespaceId().equals(player.playableStateNamespaceId()) + || !binding.characterId().equals(player.characterId()) + || !binding.sessionId().equals(player.sessionId().toString())) throw unavailable(); + } + + private static Record current(DSLContext tx, UUID id, boolean lock) { + Record row = + tx.fetchOne( + CURRENT_PROJECTION + + TRANSFER + + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence AND r.region_epoch=t.region_epoch" + + (lock ? " FOR UPDATE OF r,t" : ""), + id); + if (row == null) throw unavailable(); + if (!sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row)) + .equals(row.get("source_digest", String.class))) throw unavailable(); + return row; + } + + private static void requireComplete(DSLContext tx, UUID id) { + Record transfer = current(tx, id, false); + boolean missing = + exists( + tx, + "SELECT 1" + + PENDING + + " AND NOT EXISTS (SELECT 1 FROM " + + ITEM + + " i WHERE i.transfer_id=? AND i.execution_digest=e.execution_digest AND i.canonical_execution=e.canonical_execution AND i.fence_readback IS NOT NULL AND i.incarnation_digest=?)", + transfer.get("tenant_id", UUID.class), + transfer.get("game_instance_id", UUID.class), + transfer.get("region_id", UUID.class), + id, + transfer.get("incarnation_digest", String.class)); + if (missing) throw unavailable(); + } + + private static void requireOldOwner( + DSLContext tx, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior) { + Record row = + tx.fetchOne( + "SELECT * FROM game_session_region_runtime_status WHERE tenant_id=? AND game_instance_id=? AND region_id=? FOR UPDATE", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + if (row == null + || !prior.ownerInstanceId().equals(row.get("owner_instance_id", String.class)) + || prior.executorFence().longValueExact() != row.get("executor_fence", Long.class) + || prior.regionEpoch() != row.get("region_epoch", Long.class) + || !Arrays.equals( + prior.lifecycleRequest().canonicalBytes(), + row.get("lifecycle_request_bytes", byte[].class)) + || !sourceDigest(source, prior) + .equals(sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row)))) + throw unavailable(); + } + + static String sourceDigest( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior) { + if (!source.tenantId().equals(prior.tenantId()) + || !source.gameInstanceId().equals(prior.gameInstanceId()) + || !source.regionId().equals(prior.regionId()) + || !source.canonicalRegionId().equals(prior.canonicalRegionId()) + || source.lifecycleEpoch() != prior.lifecycleEpoch() + || source.lifecycleRowVersion() != prior.lifecycleRowVersion() + || !source.captureId().equals(prior.captureId()) + || !source.graphSha256().equals(prior.graphSha256()) + || !source.preparationInputDigest().equals(prior.preparationInputDigest()) + || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( + source.lifecycleRequest(), prior.lifecycleRequest())) throw unavailable(); + return sourceDigest(prior); + } + + private static String sourceDigest(CanonicalGameplayRegionRuntimeStatus prior) { + return sourceDigest( + prior, + prior.ownerInstanceId(), + prior.executorFence().longValueExact(), + prior.leaseTokenCorrelation()); + } + + private static String sourceDigest( + CanonicalGameplayRegionRuntimeStatus prior, String owner, long fence, String lease) { + return digest( + bytes( + prior.tenantId() + + "/" + + prior.gameInstanceId() + + "/" + + prior.regionId() + + "/" + + prior.canonicalRegionId() + + "/" + + prior.lifecycleEpoch() + + "/" + + prior.lifecycleRowVersion() + + "/" + + Base64.getEncoder().encodeToString(prior.lifecycleRequest().canonicalBytes()) + + "/" + + prior.captureId() + + "/" + + prior.graphSha256() + + "/" + + prior.preparationInputDigest() + + "/" + + prior.regionEpoch() + + "/" + + prior.ownerService() + + "/" + + owner + + "/" + + fence + + "/" + + lease)); + } + + private void requireObservation( + Context context, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation value) { + if (value.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER + || !context.equals(value.regionOwnerTransferContext()) + || clock.millis() >= value.expiresAtEpochMillis()) throw unavailable(); + } + + /** + * Strictly reconstruct the existing retained envelope; canonical re-encoding excludes alternate + * grammars. + */ + static OriginalNewCapacityExecution decode(byte[] canonical) { + try { + if (canonical == null || canonical.length == 0 || canonical.length > 1048576) + throw unavailable(); + JsonNode node = JSON.readTree(canonical); + byte[] payload = Base64.getDecoder().decode(node.get("canonicalAttemptPayload").textValue()); + var parser = new Frame(payload); + if (!"mutationDigest/v1".equals(parser.segment())) throw unavailable(); + Map fields = parser.fields(7, 0); + var scope = object(fields, "scope"); + var target = object(fields, "target"); + var player = object(target, "ownerContext"); + var expected = object(fields, "expectedVersion"); + var mutation = object(fields, "mutation"); + var identity = + new TenantCapacityAdmission.Identity( + uuid(scope, "tenantId"), uuid(scope, "requestId"), uuid(scope, "admissionId")); + var request = + new TenantCapacityAdmission.Request( + identity, + uuid(expected, "admissionAttemptId"), + number(expected, "capacityRearmFence"), + text(target, "targetNamespace"), + new TenantCapacityAdmission.PlayerContext( + uuid(player, "accountId"), + uuid(player, "tenantId"), + uuid(player, "playableStateNamespaceId"), + uuid(player, "gameInstanceId"), + uuid(player, "characterId"), + uuid(player, "sessionId"), + uuid(player, "realmId"), + uuid(player, "requestId"), + text(player, "playableStateScope")), + TenantCapacityAdmission.Operation.valueOf(text(mutation, "operation")), + shape(object(mutation, "priorShape")), + shape(object(mutation, "requestedShape")), + TenantCapacityAdmission.Evidence.parse( + Base64.getDecoder().decode(text(mutation, "accountEvidence")), + TenantCapacityAdmission.Owner.GAME_SESSION), + number(mutation, "capacityDelta"), + node.get("mutationDigest").textValue()); + if (!parser.done() || !Arrays.equals(payload, CapacityAdmissionDigest.preimage(request))) + throw unavailable(); + var reservation = + new TenantCapacityAdmission.Result( + identity, + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.fromString(node.get("reservationId").textValue()), + Long.parseLong(node.get("reservationFence").textValue()), + Instant.parse(node.get("expiresAt").textValue()), + TenantCapacityAdmission.State.RESERVED, + node.get("snapshotIdentity").textValue(), + node.get("evaluationIdentity").textValue()); + var result = + new OriginalNewCapacityExecution( + request, + reservation, + UUID.fromString(node.get("transitionId").textValue()), + node.get("candidateDigest").textValue(), + node.get("selectedOwnerId").textValue(), + Long.parseLong(node.get("selectedOwnerFence").textValue())); + if (!Arrays.equals(canonical, result.canonicalBytes())) throw unavailable(); + return result; + } catch (RuntimeException invalid) { + throw unavailable(); + } + } + + private static TenantCapacityAdmission.Shape shape(Map value) { + return new TenantCapacityAdmission.Shape( + number(value, "activeSessions"), + number(value, "concurrentGameInstances"), + number(value, "storageBytes")); + } + + @SuppressWarnings("unchecked") + private static Map object(Map value, String key) { + if (!(value.get(key) instanceof Map)) throw unavailable(); + return (Map) value.get(key); + } + + private static String text(Map value, String key) { + if (!(value.get(key) instanceof String text)) throw unavailable(); + return text; + } + + private static long number(Map value, String key) { + if (!(value.get(key) instanceof Long number)) throw unavailable(); + return number; + } + + private static UUID uuid(Map value, String key) { + return UUID.fromString(text(value, key)); + } + + private static byte[] bytes(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + private static String digest(byte[] value) { + return "sha256:" + OriginalNewCapacityExecution.sha256(value); + } + + private static boolean exists(DSLContext tx, String query, Object... bindings) { + return Boolean.TRUE.equals( + tx.fetchSingle("SELECT EXISTS (" + query + ")", bindings).get(0, Boolean.class)); + } + + private static void noSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Normal region owner transfer is held"); + } + + private static final class Frame { + private final byte[] data; + private int offset; + + private Frame(byte[] data) { + if (data.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES) throw unavailable(); + this.data = data; + } + + private String segment() { + int start = offset; + while (offset < data.length && data[offset] >= '0' && data[offset] <= '9') offset++; + if (offset == start || offset >= data.length || data[offset++] != ':' || offset - start > 8) + throw unavailable(); + int size = + Integer.parseInt(new String(data, start, offset - start - 1, StandardCharsets.US_ASCII)); + if (size < 0 + || size > CapacityAdmissionDigest.MAX_SEGMENT_BYTES + || size > data.length - offset) throw unavailable(); + String result = new String(data, offset, size, StandardCharsets.UTF_8); + offset += size; + return result; + } + + private Map fields(int count, int depth) { + if (count < 0 || count > 16 || depth > 8) throw unavailable(); + Map result = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String name = segment(), type = segment(); + if (offset >= data.length || data[offset++] != '1') throw unavailable(); + String payload = segment(); + Object value; + if (type.equals("object")) { + Frame nested = new Frame(bytes(payload)); + value = nested.fields(Integer.parseInt(nested.segment()), depth + 1); + if (!nested.done()) throw unavailable(); + } else if (type.equals("string")) value = payload; + else if (type.equals("number") && payload.matches("0|[1-9][0-9]{0,18}")) + value = Long.parseLong(payload); + else throw unavailable(); + if (result.put(name, value) != null) throw unavailable(); + } + return result; + } + + private boolean done() { + return offset == data.length; + } + } + + record FrozenOriginal( + UUID transferId, String executionDigest, CanonicalGameplayOriginalNewCandidate candidate) {} + + record Item( + UUID transferId, + long ordinal, + OriginalNewCapacityExecution execution, + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) {} + + static final class FenceDispatch { + private final Item item; + private final UUID id; + private boolean submitted; + + private FenceDispatch(Item item, UUID id) { + this.item = item; + this.id = id; + } + + synchronized UUID takeSubmission(Item expected) { + if (item != expected) throw unavailable(); + if (submitted) return null; + submitted = true; + return id; + } + } + + static final class Completion { + private final UUID transferId; + private final String sourceDigest; + private final String incarnationDigest; + private final UUID round; + private final long deadline; + private final Clock clock; + + private Completion( + UUID transferId, + String sourceDigest, + String incarnationDigest, + UUID round, + long deadline, + Clock clock) { + this.transferId = transferId; + this.sourceDigest = sourceDigest; + this.incarnationDigest = incarnationDigest; + this.round = round; + this.deadline = deadline; + this.clock = clock; + } + + void requireFresh() { + if (clock.millis() >= deadline) throw unavailable(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index 031db67cb9..f6520d8c2a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -28,7 +28,6 @@ final class CanonicalGameplayRegionRuntimeStatusRepository { private static final String TABLE = "game_session_region_runtime_status"; private static final String PREPARATION_TABLE = "game_session_region_timeline_preparation"; - private static final String TRANSFER_TABLE = "game_session_region_owner_transfer"; private static final String FENCE_SEQUENCE = "game_session_region_executor_fence_seq"; private final DSLContext dsl; @@ -36,17 +35,6 @@ final class CanonicalGameplayRegionRuntimeStatusRepository { this.dsl = Objects.requireNonNull(dsl, "dsl"); } - static boolean hasFrozenTransfer( - DSLContext transaction, UUID tenantId, UUID gameId, UUID regionId) { - return transaction.fetchExists( - DSL.selectOne() - .from(DSL.table(TRANSFER_TABLE)) - .where(DSL.field("tenant_id").eq(tenantId)) - .and(DSL.field("game_instance_id").eq(gameId)) - .and(DSL.field("region_id").eq(regionId)) - .and(DSL.field("state").eq("FROZEN"))); - } - Optional find(Source source) { requireNoAmbientTransaction(); Objects.requireNonNull(source, "source"); @@ -687,7 +675,7 @@ public byte[] incarnationQualificationBytes() { } } - /** Installs the first durable fence for an acquired and source-bound Redis grant. */ + /** Installs a new durable fence for an already acquired and source-bound Redis grant. */ CanonicalGameplayRegionRuntimeStatus installOwner( Source source, long expectedRegionEpoch, @@ -696,6 +684,26 @@ CanonicalGameplayRegionRuntimeStatus installOwner( String ownerService, String ownerInstanceId, Instant now) { + return installOwner( + source, + expectedRegionEpoch, + prior, + leaseTokenCorrelation, + ownerService, + ownerInstanceId, + now, + null); + } + + CanonicalGameplayRegionRuntimeStatus installOwner( + Source source, + long expectedRegionEpoch, + CanonicalGameplayRegionRuntimeStatus prior, + String leaseTokenCorrelation, + String ownerService, + String ownerInstanceId, + Instant now, + CanonicalGameplayRegionOwnerTransferRepository.Completion transferProof) { requireNoAmbientTransaction(); Objects.requireNonNull(source, "source"); requireDigest(leaseTokenCorrelation); @@ -745,45 +753,133 @@ CanonicalGameplayRegionRuntimeStatus installOwner( } throw unavailable(); } - // This parent keeps replacement held under the existing owner and scope locks. - throw unavailable(); + if (prior == null || !current.equals(prior)) throw unavailable(); + // Past-outcome custody remains with the original. Only exact terminal retention + // or privately qualified future exclusion permits this normal owner handoff. + // Lease expiry alone cannot satisfy either condition. + // Capacity authorization takes this same row lock before creating that custody. + if (transaction.fetchExists( + DSL.selectOne() + .from( + DSL.table("game_session_original_new_capacity_execution") + .as("execution")) + .join( + DSL.table("game_session_canonical_binding_region_bridge_obligation") + .as("binding")) + .on( + DSL.field("binding.transition_id") + .eq(DSL.field("execution.transition_id"))) + .where(DSL.field("binding.tenant_id").eq(source.tenantId())) + .and(DSL.field("binding.game_instance_id").eq(source.gameInstanceId())) + .and(DSL.field("binding.region_id").eq(source.regionId())) + .and( + DSL.field("execution.status").in("INSTALL_DISPATCHED", "AUTHORIZED"))) + && transferProof == null) { + throw unavailable(); + } } else if (prior != null || expectedRegionEpoch != 1L) { throw unavailable(); } + if (transferProof != null) transferProof.requireFresh(); Record fenceRow = transaction.fetchOne("SELECT nextval('" + FENCE_SEQUENCE + "') AS fence"); Long fence = fenceRow == null ? null : fenceRow.get("fence", Long.class); if (fence == null || fence <= 0L) throw unavailable(); - Record installed = - transaction.fetchOne( - "INSERT INTO " - + TABLE - + " (tenant_id, game_instance_id, canonical_region_id, region_id," - + " tenant_region_tag, lifecycle_epoch, lifecycle_row_version, capture_id," - + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," - + " region_epoch, executor_fence," - + " lease_token_correlation, owner_service, owner_instance_id, paused," - + " last_committed_tick_id, updated_at)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?)" - + " ON CONFLICT (tenant_id, game_instance_id, region_id) DO NOTHING" - + " RETURNING *", - source.tenantId(), - source.gameInstanceId(), - source.canonicalRegionId(), - source.regionId(), - expectedTag, - source.lifecycleEpoch(), - source.lifecycleRowVersion(), - source.captureId(), - source.lifecycleRequest().canonicalBytes(), - source.graphSha256(), - source.preparationInputDigest(), - fence, - leaseTokenCorrelation, - ownerService, - ownerInstanceId, - localDateTime(now)); + if (transferProof != null) { + if (current == null) throw unavailable(); + CanonicalGameplayRegionOwnerTransferRepository.requireAndComplete( + transaction, + transferProof, + source, + current, + ownerInstanceId, + fence, + leaseTokenCorrelation); + } else if (current != null + && CanonicalGameplayRegionOwnerTransferRepository.frozen( + transaction, + current.tenantId(), + current.gameInstanceId(), + current.regionId())) { + CanonicalGameplayRegionOwnerTransferRepository.completeTerminalOnly( + transaction, current, ownerInstanceId, fence, leaseTokenCorrelation); + } + Record installed; + if (current == null) { + if (expectedRegionEpoch != 1L) throw unavailable(); + installed = + transaction.fetchOne( + "INSERT INTO " + + TABLE + + " (tenant_id, game_instance_id, canonical_region_id, region_id," + + " tenant_region_tag, lifecycle_epoch, lifecycle_row_version, capture_id," + + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," + + " region_epoch, executor_fence," + + " lease_token_correlation, owner_service, owner_instance_id, paused," + + " last_committed_tick_id, updated_at)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?)" + + " ON CONFLICT (tenant_id, game_instance_id, region_id) DO NOTHING" + + " RETURNING *", + source.tenantId(), + source.gameInstanceId(), + source.canonicalRegionId(), + source.regionId(), + expectedTag, + source.lifecycleEpoch(), + source.lifecycleRowVersion(), + source.captureId(), + source.lifecycleRequest().canonicalBytes(), + source.graphSha256(), + source.preparationInputDigest(), + fence, + leaseTokenCorrelation, + ownerService, + ownerInstanceId, + localDateTime(now)); + } else { + installed = + transaction.fetchOne( + "UPDATE " + + TABLE + + " SET executor_fence = ?, lease_token_correlation = ?," + + " owner_service = ?, owner_instance_id = ?, updated_at = ?" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " AND tenant_region_tag = ? AND canonical_region_id = ?" + + " AND lifecycle_epoch = ? AND lifecycle_row_version = ?" + + " AND capture_id = ? AND lifecycle_request_bytes = ?" + + " AND graph_sha256 = ?" + + " AND preparation_input_digest = ? AND region_epoch = ?" + + " AND executor_fence = ? AND lease_token_correlation = ?" + + " AND owner_service = ? AND owner_instance_id = ? AND paused = ?" + + " AND last_committed_tick_id = ?" + + " AND last_committed_tick_batch_id IS NOT DISTINCT FROM ?" + + " RETURNING *", + fence, + leaseTokenCorrelation, + ownerService, + ownerInstanceId, + localDateTime(now), + current.tenantId(), + current.gameInstanceId(), + current.regionId(), + current.tenantRegionTag(), + current.canonicalRegionId(), + current.lifecycleEpoch(), + current.lifecycleRowVersion(), + current.captureId(), + current.lifecycleRequest().canonicalBytes(), + current.graphSha256(), + current.preparationInputDigest(), + current.regionEpoch(), + current.executorFence().longValueExact(), + current.leaseTokenCorrelation(), + current.ownerService(), + current.ownerInstanceId(), + current.paused(), + current.lastCommittedTickId(), + current.lastCommittedTickBatchId()); + } if (installed == null) throw unavailable(); CanonicalGameplayRegionRuntimeStatus result = toStatus(installed); if (!matchesSource(result, source) @@ -793,6 +889,7 @@ CanonicalGameplayRegionRuntimeStatus installOwner( || !result.tenantRegionTag().equals(expectedTag)) { throw unavailable(); } + if (transferProof != null) transferProof.requireFresh(); return result; }); } catch (RuntimeException failure) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture.java new file mode 100644 index 0000000000..7312cf40c3 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** + * Controlled transfer-purpose signer custody only. Actual FROZEN or sealed-COMPLETED context and + * mapping must come from the SQL owners and are independently rechecked by the real receiver. + * COMPLETED observations supply read-only currentness, never mutation authority. This fixture + * supplies no transfer outcome, Account settlement, deployment custody or reset proof. + */ +final class CanonicalGameplayControlledRegionTransferObservationFixture { + private static final String KEY_ID = "controlled-region-transfer-attestor"; + private static final String BINDING = "controlled-region-transfer-attestor-binding"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final KeyPair keys; + private final Clock clock; + private final Duration observationTtl; + + CanonicalGameplayControlledRegionTransferObservationFixture() throws Exception { + this(Clock.systemUTC()); + } + + CanonicalGameplayControlledRegionTransferObservationFixture(Clock clock) throws Exception { + this(clock, Duration.ofSeconds(30)); + } + + CanonicalGameplayControlledRegionTransferObservationFixture(Clock clock, Duration observationTtl) + throws Exception { + this.clock = Objects.requireNonNull(clock, "clock"); + this.observationTtl = Objects.requireNonNull(observationTtl, "observationTtl"); + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + keys = generator.generateKeyPair(); + } + + CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayRegionOwnerTransferObservationSource source, + CanonicalGameplayTenantGameplayTagRepository tags) { + return receiver(source, tags, "storage-1"); + } + + CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayRegionOwnerTransferObservationSource source, + CanonicalGameplayTenantGameplayTagRepository tags, + String storageGeneration) { + var expected = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-transfer-target", + "generation-1", + List.of("redis-node-a"), + "controlled-redis-build", + "controlled-registry-v1", + "sha256:" + "d".repeat(64), + "READY", + "boot-1", + "startup-1", + storageGeneration, + "aof-1"); + var trust = + new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + BINDING, + "sha256:" + "a".repeat(64), + Map.of(KEY_ID, (RSAPublicKey) keys.getPublic()), + expected, + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64), + 16 * 1024, + 1, + observationTtl); + return CanonicalGameplayProtectedIncarnationReceiver.forRegionOwnerTransfer( + source, tags, this::observe, trust, clock); + } + + private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + var context = request.context(); + if (context.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER) { + throw new IllegalArgumentException("Controlled channel is limited to transfer observations"); + } + var transfer = context.regionOwnerTransferContext(); + Map owner = new LinkedHashMap<>(); + owner.put("ownerKind", context.ownerKind().name()); + owner.put("transferId", transfer.transferId().toString()); + owner.put("transferIntentDigest", transfer.transferIntentDigest()); + owner.put("frozenSourceDigest", transfer.frozenSourceDigest()); + owner.put("oldRegionOwnerId", transfer.oldRegionOwnerId()); + owner.put("oldRegionOwnerFence", transfer.oldRegionOwnerFence()); + owner.put("gameInstanceId", transfer.gameInstanceId().toString()); + owner.put("regionId", transfer.regionId().toString()); + owner.put("regionEpoch", transfer.regionEpoch()); + owner.put("transitionId", transfer.transitionId().toString()); + owner.put("requestId", transfer.requestId().toString()); + owner.put("accountId", transfer.accountId().toString()); + owner.put("executionDigest", transfer.executionDigest()); + owner.put("candidateDigest", transfer.candidateDigest()); + owner.put("controlState", transfer.controlState()); + owner.put("completionDigest", transfer.completionDigest()); + Map target = new LinkedHashMap<>(); + target.put("targetOrdinal", context.targetOrdinal()); + target.put("tenantId", context.tenantId().toString()); + target.put("playableStateNamespaceId", context.playableStateNamespaceId().toString()); + target.put("tenantGameplayTag", context.tenantGameplayTag()); + target.put("workloadNamespace", context.workloadNamespace()); + target.put("allocationVersion", context.allocationVersion()); + var evidence = request.expectedEvidence(); + Map deployment = new LinkedHashMap<>(); + deployment.put("deploymentIdentity", evidence.deploymentIdentity()); + deployment.put("deploymentGeneration", evidence.deploymentGeneration()); + deployment.put("canonicalNodeSet", evidence.canonicalNodeSet()); + deployment.put("redisBuildIdentity", evidence.redisBuildIdentity()); + deployment.put("luaScriptRegistryVersion", evidence.luaScriptRegistryVersion()); + deployment.put("luaScriptRegistryDigest", evidence.luaScriptRegistryDigest()); + deployment.put("startupState", evidence.startupState()); + deployment.put("bootGeneration", evidence.bootGeneration()); + deployment.put("startupGeneration", evidence.startupGeneration()); + deployment.put("storageGeneration", evidence.storageGeneration()); + deployment.put("aofGeneration", evidence.aofGeneration()); + Map root = new LinkedHashMap<>(); + root.put("schema", "firemud.gs.protected-region-owner-transfer-read/v1"); + root.put("attestorBinding", request.attestorBinding()); + root.put("attestorKeyId", KEY_ID); + root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); + root.put("observationNonce", request.nonce()); + root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis()); + root.put("owner", owner); + root.put("target", target); + root.put("targetDeploymentEvidence", deployment); + root.put("coordOpsRoAclDigest", request.coordOpsRoAclDigest()); + root.put("coordRedisConfigObservedDigest", request.coordRedisConfigObservedDigest()); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keys.getPrivate()); + signer.update(canonical); + return new CanonicalGameplayProtectedIncarnationReceiver.SignedObservation( + KEY_ID, canonical, signer.sign()); + } catch (java.security.GeneralSecurityException | java.io.IOException failure) { + throw new IllegalStateException("Controlled transfer observation signing failed", failure); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java index b10fae4cbe..f13d2949d0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java @@ -12,17 +12,41 @@ import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; 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; /** - * Physical component tests for original NEW capacity dispatch custody and owner-movement refusal. + * Native component composition: actual GS SQL/candidate/account-member/issuer/region/final owners. + * Account lease, signer/JWKS, physical Account OPEN, World/Entity RPC response DTOs, incarnation, + * launch and empty legacy cohort are controlled fixtures. Real mTLS clients mint private Entity + * references; real region owners mint grants and ACKs. This does not exercise Account callbacks, + * INITIAL protected observation, the full coordinator, external source custody or activation. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest - extends CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport { + extends CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Override + PostgreSQLContainer postgresContainer() { + return POSTGRES; + } + + @Override + GenericContainer redisContainer() { + return REDIS; + } @Test void committedCapacityWithoutExecutionCustodyRemainsIndeterminate() throws Exception { @@ -55,48 +79,6 @@ void committedCapacityWithoutExecutionCustodyRemainsIndeterminate() throws Excep assertThat(physicalImage()).isEqualTo(before); } - @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) - void abortedOriginalRetainsPhysicalClosureAcrossAbortOrdering(boolean closeBeforeAbort) - throws Exception { - repairAccountMember(); - bridge(); - if (closeBeforeAbort) - capacityOwner() - .closeOriginalAttempt(controlledCapacity.request(), controlledCapacity.reservation()); - assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); - if (!closeBeforeAbort) - capacityOwner() - .closeOriginalAttempt(controlledCapacity.request(), controlledCapacity.reservation()); - var proof = - capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); - assertThat(proof.disposition()).isEqualTo("NOT_EXECUTED_AFTER_AUTHORIZATION"); - var terminal = - fixture - .dsl() - .fetchSingle( - "SELECT status, terminal_readback FROM game_session_original_new_capacity_execution"); - assertThat(terminal.get("status", String.class)).isEqualTo("CLOSED"); - assertThat(terminal.get("terminal_readback", byte[].class)).isNotEmpty(); - byte[] tombstone = - CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( - admin, - ascii( - capacityKey(tags.assignmentForRetainedCapacityExecution(fixture.transitionId())))); - assertThat( - capacityOwner() - .readExact(controlledCapacity.request(), controlledCapacity.reservation()) - .canonicalReadback()) - .containsExactly(proof.canonicalReadback()); - assertThat( - CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( - admin, - ascii( - capacityKey( - tags.assignmentForRetainedCapacityExecution(fixture.transitionId()))))) - .containsExactly(tombstone); - } - @Test void physicalImageRetainsAbsoluteExpiryRatherThanOnlyItsPresence() { byte[] key = "physical-image-expiry".getBytes(StandardCharsets.US_ASCII); @@ -183,14 +165,16 @@ void lastPrechargedCapacityEvidenceSlotSurvivesFullBudgetAndSameAttemptReplay( fixture .dsl() .fetchOne( - "SELECT 1 FROM game_session_capacity_evidence_charge WHERE admission_attempt_id = ?", + "SELECT 1 FROM game_session_capacity_evidence_charge WHERE admission_attempt_id" + + " = ?", unsupported.admissionAttemptId())) .isNull(); assertThat( fixture .dsl() .fetchSingle( - "SELECT count(*) FROM game_session_capacity_evidence_charge WHERE tenant_id = ?", + "SELECT count(*) FROM game_session_capacity_evidence_charge WHERE tenant_id =" + + " ?", controlledCapacity.request().identity().tenantId()) .get(0, Long.class)) .isEqualTo(1L); @@ -202,14 +186,16 @@ void lastPrechargedCapacityEvidenceSlotSurvivesFullBudgetAndSameAttemptReplay( fixture .dsl() .fetchOne( - "SELECT 1 FROM game_session_capacity_evidence_charge WHERE admission_attempt_id = ?", + "SELECT 1 FROM game_session_capacity_evidence_charge WHERE admission_attempt_id" + + " = ?", refusedRequest.admissionAttemptId())) .isNull(); assertThat( fixture .dsl() .fetchOne( - "SELECT 1 FROM game_session_original_new_capacity_execution WHERE admission_attempt_id = ?", + "SELECT 1 FROM game_session_original_new_capacity_execution WHERE" + + " admission_attempt_id = ?", refusedRequest.admissionAttemptId())) .isNull(); var assignment = tags.assignmentForTransition(fixture.transitionId()); @@ -231,7 +217,8 @@ void lastPrechargedCapacityEvidenceSlotSurvivesFullBudgetAndSameAttemptReplay( fixture .dsl() .fetchSingle( - "SELECT status FROM game_session_original_new_capacity_execution WHERE admission_attempt_id = ?", + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " admission_attempt_id = ?", controlledCapacity.request().admissionAttemptId()) .get(0, String.class)) .isEqualTo("AUTHORIZED"); @@ -240,7 +227,8 @@ void lastPrechargedCapacityEvidenceSlotSurvivesFullBudgetAndSameAttemptReplay( fixture .dsl() .fetchSingle( - "SELECT count(*) FROM game_session_capacity_evidence_charge WHERE tenant_id = ?", + "SELECT count(*) FROM game_session_capacity_evidence_charge WHERE tenant_id =" + + " ?", controlledCapacity.request().identity().tenantId()) .get(0, Long.class)) .isEqualTo(1L); @@ -327,7 +315,8 @@ source, template, account, issuer, controlledCapacity, deadline())) fixture .dsl() .fetchSingle( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest = ?", controlledCapacity.digest()) .get(0, String.class)) .isEqualTo("INSTALL_DISPATCHED"); @@ -441,7 +430,8 @@ source, null, accountOpen, issuerOpen, controlledCapacity, deadline())) fixture .dsl() .fetchOne( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest = ?", controlledCapacity.digest())) .isNull(); assertThat(admin.type(ascii(capacityKey))).isEqualTo("none"); @@ -476,198 +466,12 @@ source, null, accountOpen, issuerOpen, controlledCapacity, deadline())) fixture .dsl() .fetchOne( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest = ?", controlledCapacity.digest())) .isNull(); assertThat(admin.type(ascii(capacityKey))).isEqualTo("none"); assertThat(sqlImage()).isEqualTo(sqlBefore); assertThat(physicalImage()).isEqualTo(physicalBefore); } - - @Test - void lostDispatchCommitReplyBeforeRedisSendRetainsIndeterminateOriginal() throws Exception { - repairAccountMember(); - bridge(false); - String schema = fixture.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); - DriverManagerDataSource raw = new DriverManagerDataSource(); - raw.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = POSTGRES.getJdbcUrl(); - raw.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); - raw.setUsername(POSTGRES.getUsername()); - raw.setPassword(POSTGRES.getPassword()); - var stoppedAfterCommit = new java.util.concurrent.atomic.AtomicBoolean(); - var stoppingDataSource = - new org.springframework.jdbc.datasource.DelegatingDataSource(raw) { - @Override - public java.sql.Connection getConnection() throws java.sql.SQLException { - return failDispatchCommitReplyAfterMarker( - super.getConnection(), raw, controlledCapacity.digest(), stoppedAfterCommit); - } - }; - var stoppingDsl = org.jooq.impl.DSL.using(stoppingDataSource, org.jooq.SQLDialect.POSTGRES); - var stoppingOwner = - new CanonicalGameplayOriginalNewCapacityExecutionOwner( - stoppingDsl, ownerClient, catalog, CLOCK, tags); - var source = inventory.readOriginalNewFinalAdmissionSource(decision); - var accountOpen = controlledAccountOpen(); - var issuerOpen = issuerOpen(); - var physicalBefore = physicalImage(); - try (var credential = - new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); - var rawTemplate = credential.template(); - var template = rawTemplate.bindCapacityExecution(controlledCapacity)) { - assertThatThrownBy( - () -> - stoppingOwner.authorize( - source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) - .isInstanceOf(RuntimeException.class); - } - assertThat(stoppedAfterCommit).isTrue(); - String originalKey = capacityKey(tags.assignmentForTransition(fixture.transitionId())); - assertThat(admin.type(ascii(originalKey))).isEqualTo("none"); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", - controlledCapacity.digest()) - .get(0, String.class)) - .isEqualTo("INSTALL_DISPATCHED"); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", - controlledCapacity.digest()) - .get(0, String.class)) - .isEqualTo("INSTALL_DISPATCHED"); - assertThatThrownBy( - () -> - capacityOwner() - .readExact(controlledCapacity.request(), controlledCapacity.reservation())) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - capacityOwner() - .closeOriginalAttempt( - controlledCapacity.request(), controlledCapacity.reservation())) - .isInstanceOf(IllegalStateException.class); - assertThat(physicalImage()).isEqualTo(physicalBefore); - } - - private static java.sql.Connection failDispatchCommitReplyAfterMarker( - java.sql.Connection actual, - javax.sql.DataSource independentDataSource, - String executionDigest, - java.util.concurrent.atomic.AtomicBoolean stopped) - throws java.sql.SQLException { - try { - return (java.sql.Connection) - java.lang.reflect.Proxy.newProxyInstance( - java.sql.Connection.class.getClassLoader(), - new Class[] {java.sql.Connection.class}, - (proxy, method, values) -> { - Object result; - try { - result = method.invoke(actual, values); - } catch (java.lang.reflect.InvocationTargetException failure) { - throw failure.getCause(); - } - if (method.getName().equals("commit") && !stopped.get()) { - try (var independent = independentDataSource.getConnection(); - var check = - independent.prepareStatement( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?")) { - check.setString(1, executionDigest); - try (var rows = check.executeQuery()) { - if (rows.next() - && "INSTALL_DISPATCHED".equals(rows.getString(1)) - && stopped.compareAndSet(false, true)) { - throw new java.sql.SQLException( - "Controlled lost INSTALL_DISPATCHED commit reply"); - } - } - } - } - return result; - }); - } catch (RuntimeException | Error failure) { - try { - actual.close(); - } catch (java.sql.SQLException closeFailure) { - failure.addSuppressed(closeFailure); - } - throw failure; - } - } - - @Test - void ownerMovementBeforeCapacityAuthorizationRefusesOriginalDispatchWithoutMutation() - throws Exception { - repairAccountMember(); - bridge(false); - var source = inventory.readOriginalNewFinalAdmissionSource(decision); - var binding = source.candidate().bindingIdentity(); - assertThat( - fixture - .dsl() - .execute( - "UPDATE game_session_region_runtime_status SET executor_fence = executor_fence + 1 WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", - binding.tenantId(), - binding.gameInstanceId(), - binding.regionId())) - .isEqualTo(1); - var account = controlledAccountOpen(); - var issuer = issuerOpen(); - String rows = sqlImage(); - var physical = physicalImage(); - try (var credential = - new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); - var raw = credential.template(); - var bound = raw.bindCapacityExecution(controlledCapacity)) { - assertThatThrownBy( - () -> - capacityOwner() - .authorize(source, bound, account, issuer, controlledCapacity, deadline())) - .isInstanceOf(IllegalStateException.class); - } - assertThat(sqlImage()).isEqualTo(rows); - assertThat(physicalImage()).isEqualTo(physical); - } - - @Test - void unresolvedOriginalExecutionBlocksOwnerMovementUntilExactClosure() throws Exception { - repairAccountMember(); - bridge(); - var source = inventory.readOriginalNewFinalAdmissionSource(decision); - admin.pexpire(ascii(regionBinding.installation().grant.key()), 0); - String rows = sqlImage(); - var physical = physicalImage(); - assertThatThrownBy( - () -> - regionBinding - .owner() - .revalidateOriginalNewFinalBinding(regionBinding.installation(), source)) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(() -> replaceRegionOwner("successor-before-closure")) - .isInstanceOf(IllegalStateException.class); - // The positive continuation cannot turn an unexecuted/missing final result into proof. - assertThatThrownBy( - () -> - capacityOwner() - .retainCommittedBeforeCleanup( - controlledCapacity.request(), controlledCapacity.reservation())) - .isInstanceOf(IllegalStateException.class); - assertThat(sqlImage()).isEqualTo(rows); - assertThat(physicalImage()).isEqualTo(physical); - capacityOwner() - .closeOriginalAttempt(controlledCapacity.request(), controlledCapacity.reservation()); - assertThatThrownBy(() -> replaceRegionOwner("successor-after-closure")) - .isInstanceOf(IllegalStateException.class); - assertThat( - capacityOwner() - .readExact(controlledCapacity.request(), controlledCapacity.reservation()) - .disposition()) - .isEqualTo("NOT_EXECUTED_AFTER_AUTHORIZATION"); - } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java index 9b2a9f6126..96c9dcde9d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java @@ -3,16 +3,73 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.Map; import java.util.UUID; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -/** Physical component tests for retained original NEW capacity outcomes and exact closure. */ +/** + * Native component composition: actual GS SQL/candidate/account-member/issuer/region/final owners. + * Account lease, signer/JWKS, physical Account OPEN, World/Entity RPC response DTOs, incarnation, + * launch and empty legacy cohort are controlled fixtures. Real mTLS clients mint private Entity + * references; real region owners mint grants and ACKs. This does not exercise Account callbacks, + * INITIAL protected observation, the full coordinator, external source custody or activation. + */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest - extends CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport { + extends CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Override + PostgreSQLContainer postgresContainer() { + return POSTGRES; + } + + @Override + GenericContainer redisContainer() { + return REDIS; + } + + @Test + void transferFenceRejectsChangedCandidateDigestBeforeSubmittingRedis() throws Exception { + repairAccountMember(); + bridge(false); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var assignment = tags.assignmentForTransition(fixture.transitionId()); + var changed = + new net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution( + controlledCapacity.request(), + controlledCapacity.reservation(), + controlledCapacity.transitionId(), + "sha256:" + "0".repeat(64), + controlledCapacity.selectedOwnerId(), + controlledCapacity.selectedOwnerFence()); + String retained = sqlImage(); + Map physical = physicalImage(); + + assertThatThrownBy( + () -> + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + ownerClient, catalog, CLOCK, tags) + .fenceCapacityExecutionOnce( + changed, source.candidate(), assignment, UUID.randomUUID(), deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(admin.type(ascii(capacityKey(assignment)))).isEqualTo("none"); + assertThat(sqlImage()).isEqualTo(retained); + assertThat(physicalImage()).isEqualTo(physical); + } @Test void failedPositiveRetentionRollsBackFinalReceiptAndExactRecoveryCommitsBoth() throws Exception { @@ -110,8 +167,9 @@ void historicalFinalReceiptWithoutCapacityEvidenceCannotMintCurrentSource() thro historical.execute("SET LOCAL session_replication_role = replica"); assertThat( historical.execute( - "UPDATE game_session_canonical_binding_transition" - + " SET original_new_capacity_execution_digest = NULL WHERE transition_id = ?", + "UPDATE game_session_canonical_binding_transition SET" + + " original_new_capacity_execution_digest = NULL WHERE transition_id" + + " = ?", fixture.transitionId())) .isEqualTo(1); }); @@ -149,8 +207,8 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .execute( - "UPDATE game_session_original_new_capacity_execution" - + " SET status = 'CLOSED', terminal_readback = ? WHERE execution_digest = ?", + "UPDATE game_session_original_new_capacity_execution SET status = 'CLOSED'," + + " terminal_readback = ? WHERE execution_digest = ?", new byte[] {1}, controlledCapacity.digest())) .isInstanceOf(org.jooq.exception.DataAccessException.class) @@ -201,7 +259,8 @@ void committedFinalAdmissionReplayAtomicallyRetainsPreviouslySplitExecutionEvide fixture .dsl() .fetchSingle( - "SELECT status, terminal_readback FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + "SELECT status, terminal_readback FROM" + + " game_session_original_new_capacity_execution WHERE execution_digest = ?", readback.execution().digest()); assertThat(authorized.get("status", String.class)).isEqualTo("AUTHORIZED"); assertThat(authorized.get("terminal_readback", byte[].class)).isNull(); @@ -212,7 +271,8 @@ void committedFinalAdmissionReplayAtomicallyRetainsPreviouslySplitExecutionEvide fixture .dsl() .fetchSingle( - "SELECT status, terminal_readback FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + "SELECT status, terminal_readback FROM" + + " game_session_original_new_capacity_execution WHERE execution_digest = ?", readback.execution().digest()); assertThat(retainedRow.get("status", String.class)).isEqualTo("COMMITTED"); assertThat(retainedRow.get("terminal_readback", byte[].class)).isNotNull(); @@ -233,7 +293,8 @@ void committedFinalAdmissionReplayAtomicallyRetainsPreviouslySplitExecutionEvide } @Test - void committedRedisWinnerRecoversFullPositiveSqlRetentionBeforeCleanup() throws Exception { + void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff() + throws Exception { repairAccountMember(); bridge(); var source = inventory.readOriginalNewFinalAdmissionSource(decision); @@ -257,119 +318,51 @@ void committedRedisWinnerRecoversFullPositiveSqlRetentionBeforeCleanup() throws fixture .dsl() .fetchSingle( - "SELECT original_new_final_session_sha256 FROM game_session_canonical_binding_transition WHERE transition_id=?", + "SELECT original_new_final_session_sha256 FROM" + + " game_session_canonical_binding_transition WHERE transition_id=?", fixture.transitionId()) .get(0, String.class)) .isNull(); - var retained = - capacityOwner() - .retainCommittedBeforeCleanup( - controlledCapacity.request(), controlledCapacity.reservation()); - assertThat(retained.disposition()).isEqualTo("COMMITTED"); - assertThat(retained.physicalDigest()) - .isEqualTo( - "sha256:" - + net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution - .sha256(committed)); + var original = regionBinding.installation(); + var pinned = source; + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); assertThat( fixture .dsl() .fetchSingle( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest=?", controlledCapacity.digest()) .get(0, String.class)) .isEqualTo("COMMITTED"); assertThat( capacityOwner() .readExact(controlledCapacity.request(), controlledCapacity.reservation()) - .canonicalReadback()) - .containsExactly(retained.canonicalReadback()); + .disposition()) + .isEqualTo("COMMITTED"); assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); - } - - @Test - void committedOriginalRetainsExactTerminalEvidenceAndReplay() throws Exception { - repairAccountMember(); - bridge(); - var source = inventory.readOriginalNewFinalAdmissionSource(decision); - byte[] committed; - try (var credential = - new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); - var template = credential.template(); - var readback = - finalOwner() - .finalizeOriginalNewOnce( - source, - template, - controlledAccountOpen(), - issuerOpen(), - controlledCapacity, - deadline())) { - inventory.commitOriginalNewFinalAdmission(readback); - committed = admin.get(ascii(installation.sessionKey())); - } - var retained = - capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); - assertThat(retained.disposition()).isEqualTo("COMMITTED"); - assertThat(retained.physicalDigest()) + var retained = inventory.readRegionTransferOriginalSource(fixture.transitionId(), pinned); + assertThat(retained.transitionStatus()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED); + assertThat(retained.candidate()).isEqualTo(pinned.candidate()); + assertThat(retained.finalReceipt().orElseThrow().finalSessionSha256()) .isEqualTo( - "sha256:" - + net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution - .sha256(committed)); + net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution.sha256( + committed)); assertThat( - capacityOwner() - .readExact(controlledCapacity.request(), controlledCapacity.reservation()) - .canonicalReadback()) - .containsExactly(retained.canonicalReadback()); - assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); - } - - @Test - void committedHashWithoutCompletePositiveServingProofStillBlocksOwnerMovement() throws Exception { - repairAccountMember(); - bridge(); - var source = inventory.readOriginalNewFinalAdmissionSource(decision); - try (var credential = - new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); - var template = credential.template(); - var ignored = - finalOwner() - .finalizeOriginalNewOnce( - source, - template, - controlledAccountOpen(), - issuerOpen(), - controlledCapacity, - deadline())) { - admin.del(ascii(installation.sessionKey())); - } - var original = regionBinding.installation(); - assertThatThrownBy(() -> replaceRegionOwner("successor-without-positive-serving-proof")) - .isInstanceOf(IllegalStateException.class); - assertThat( - new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) - .find(original.source) - .orElseThrow() - .executorFence()) - .isEqualTo(original.status.executorFence()); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", - controlledCapacity.digest()) - .get(0, String.class)) - .isEqualTo("AUTHORIZED"); - assertThat( - admin.hget( - ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))), - ascii("state"))) - .containsExactly(ascii("COMMITTED")); + inventory + .readRegionTransferOriginalSource(fixture.transitionId(), retained) + .finalReceipt()) + .isEqualTo(retained.finalReceipt()); + assertThatThrownBy(() -> inventory.readProvisionalCasEvidence(fixture.transitionId())) + .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("A first binding cannot proceed while an active controller exists"); assertThatThrownBy( - () -> - capacityOwner() - .readExact(controlledCapacity.request(), controlledCapacity.reservation())) - .isInstanceOf(IllegalStateException.class); + () -> inventory.readRegionTransferOriginalSource(UUID.randomUUID(), retained)) + .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("Region transfer changed its original transition"); } @Test @@ -455,7 +448,8 @@ void concurrentExactClosuresReplayIdenticalRetainedProof() throws Exception { fixture .dsl() .fetchSingle( - "SELECT status, terminal_readback FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + "SELECT status, terminal_readback FROM game_session_original_new_capacity_execution" + + " WHERE execution_digest = ?", retained.execution().digest()); assertThat(row.get("status", String.class)).isEqualTo("CLOSED"); assertThat(row.get("terminal_readback", byte[].class)) @@ -546,7 +540,12 @@ void closedExecutionRejectsContradictoryFinalSqlReceiptWithoutLosingItsRetainedP fixture .dsl() .execute( - "UPDATE game_session_canonical_binding_transition SET original_new_final_session_sha256 = ?, original_new_capacity_execution_digest = ?, original_new_admission_at_ms = ?, original_new_continuity_expires_at_ms = ?, original_new_session_duration_ms = ? WHERE transition_id = ?", + "UPDATE game_session_canonical_binding_transition SET" + + " original_new_final_session_sha256 = ?," + + " original_new_capacity_execution_digest = ?," + + " original_new_admission_at_ms = ?," + + " original_new_continuity_expires_at_ms = ?," + + " original_new_session_duration_ms = ? WHERE transition_id = ?", "a".repeat(64), controlledCapacity.digest(), CLOCK.millis(), @@ -595,7 +594,8 @@ void physicalClosureBeforeSqlProofRetentionRemainsIndeterminateEvenAfterServingR fixture .dsl() .fetchSingle( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest = ?", controlledCapacity.digest()) .get(0, String.class)) .isEqualTo("AUTHORIZED"); @@ -679,7 +679,8 @@ void actualFinalBeforeAccountFenceRetainsPhysicalPositiveButRecoveryRemainsIndet fixture .dsl() .fetchSingle( - "SELECT status, original_new_final_session_sha256 FROM game_session_canonical_binding_transition WHERE transition_id=?", + "SELECT status, original_new_final_session_sha256 FROM" + + " game_session_canonical_binding_transition WHERE transition_id=?", fixture.transitionId()); assertThat(pending.get("status", String.class)).isEqualTo("PROVISIONAL"); assertThat(pending.get("original_new_final_session_sha256", String.class)).isNull(); @@ -768,55 +769,11 @@ void actualFinalBeforeAccountFenceRetainsPhysicalPositiveButRecoveryRemainsIndet fixture .dsl() .fetchSingle( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest=?", controlledCapacity.digest()) .get(0, String.class)) .isEqualTo("AUTHORIZED"); } } - - @Test - void missingCommittedServingEvidenceCannotReleaseOriginalOwnerCustody() throws Exception { - repairAccountMember(); - bridge(); - var source = inventory.readOriginalNewFinalAdmissionSource(decision); - try (var credential = - new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); - var template = credential.template(); - var actual = - finalOwner() - .finalizeOriginalNewOnce( - source, - template, - controlledAccountOpen(), - issuerOpen(), - controlledCapacity, - deadline())) { - commitHistoricalSplitReceipt(actual); - } - assertThat(admin.del(ascii(installation.sessionKey()))).isEqualTo(1L); - String rows = sqlImage(); - var physical = physicalImage(); - assertThatThrownBy( - () -> - capacityOwner() - .closeOriginalAttempt( - controlledCapacity.request(), controlledCapacity.reservation())) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - capacityOwner() - .retainCommittedBeforeCleanup( - controlledCapacity.request(), controlledCapacity.reservation())) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(() -> replaceRegionOwner("successor-with-missing-committed-evidence")) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - capacityOwner() - .readExact(controlledCapacity.request(), controlledCapacity.reservation())) - .isInstanceOf(IllegalStateException.class); - assertThat(sqlImage()).isEqualTo(rows); - assertThat(physicalImage()).isEqualTo(physical); - } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java index b923f1be9e..317cc22834 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java @@ -816,6 +816,89 @@ public Candidate candidate() { return binding.candidate(); } + /** Real Account hold/credential and GS authorization, intentionally stopped before FINAL. */ + public net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result + authorizeThenFenceAndHandoffWithoutFinal( + AccountGameplayAdmissionLeaseClient account, + AccountPublicJwksCache jwks, + String originalLoginJwt, + net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient capacityClient, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, + long deadline) + throws Exception { + var inventory = new CanonicalGameplayBindingInventoryRepository(binding.dsl()); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var executionOwner = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + binding.dsl(), coordination, scripts, CLOCK, tags); + var selected = executionOwner.requireRequestBinding(source, request, deadline); + executionOwner.precharge(source, request, selected, deadline); + var reservation = capacityClient.commit(request, deadline); + var execution = executionOwner.bind(source, request, reservation, deadline, selected); + var issuerSource = binding.currentIssuerSource(); + var issuer = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + coordination, + scripts, + new CanonicalGameplayIssuerAdmissionBarrierRepository( + binding.dsl(), tags, issuerSource), + issuerSource); + try (var credential = + account.issueOriginalNewBoundGameplayCredential( + originalLoginJwt, + decision.leaseEvidence().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var raw = + CanonicalGameplayOriginalNewAuthenticatedSession.template( + source.candidate(), + credential, + new CanonicalGameplayOriginalNewBoundCredentialVerifier(jwks, CLOCK), + 120_000L); + var template = raw.bindCapacityExecution(execution)) { + var current = + initialOwner() + .verifyCurrentOpenForTarget( + request.context() + instanceof + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .PlayerContext + player + ? player.accountId() + : null, + request.identity().tenantId(), + source.candidate().bindingIdentity().playableStateNamespaceId()); + if (!(current instanceof CanonicalGameplayAccountInitialOpenProof.CurrentOpen open)) + throw new IllegalStateException("Actual INITIAL source is not OPEN"); + executionOwner.authorize( + source, + template, + open, + issuer.initializeAndRead(source.issuerAcknowledgement().operationId()), + execution, + deadline); + } + var repository = new CanonicalGameplayRegionOwnerTransferRepository(binding.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + binding.dsl(), CLOCK, repository, executionOwner, receiver); + administration.sync().pexpire(ascii(regionInstallation.grant.key()), 0); + regionInstallation = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + binding.dsl(), + coordination, + coordinationUri, + scripts, + regionInstallation, + sources.resolver, + CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture + ::controlledRegionIncarnation, + transfer, + deadline); + return reservation; + } + public Target target() { return binding.target(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 083dd9070c..8f2933f76f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -15,7 +15,11 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIssuerIndexObligation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; /** @@ -28,7 +32,24 @@ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest - extends CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport { + extends CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Override + PostgreSQLContainer postgresContainer() { + return POSTGRES; + } + + @Override + GenericContainer redisContainer() { + return REDIS; + } @Test void recreatedCapacityOwnerRecoversCommittedRedisWithoutOriginalCredentialOrGrant() @@ -76,8 +97,9 @@ source, template, account, issuer, controlledCapacity, deadline())) { assertThat(retained.physicalDigest()).isEqualTo("sha256:" + finalDigest); assertThat(inventory.readOriginalNewFinalAdmissionSource(decision).transitionStatus()) .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED); - assertThatThrownBy(() -> replaceRegionOwner("successor-after-reconciliation")) - .isInstanceOf(IllegalStateException.class); + var successor = replaceRegionOwner("successor-after-reconciliation"); + assertThat(successor.executorFence().longValueExact()) + .isGreaterThan(controlledCapacity.selectedOwnerFence()); controlledRemoveServingKeys(source, assignment); assertThat( capacityOwner() @@ -156,8 +178,8 @@ void committedReceiptSurvivesDeleteRefusalAndClockUnavailabilityUntilCatchup() t source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { inventory.commitOriginalNewFinalAdmission(actual); String retainedReceiptQuery = - "SELECT xmin::text || '/' || to_jsonb(transition)::text" - + " FROM game_session_canonical_binding_transition transition WHERE transition_id = ?"; + "SELECT xmin::text || '/' || to_jsonb(transition)::text FROM" + + " game_session_canonical_binding_transition transition WHERE transition_id = ?"; String retainedReceipt = fixture .dsl() @@ -172,7 +194,8 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .execute( - "DELETE FROM game_session_canonical_binding_transition WHERE transition_id = ?", + "DELETE FROM game_session_canonical_binding_transition WHERE" + + " transition_id = ?", fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .satisfies( @@ -245,7 +268,8 @@ void alreadyPresentAccountProjectionFinalizesAndReadsWithItsOriginalRevision() t .fetchSingle( "SELECT original_projection_state, original_projection_member," + " original_projection_inventory_revision FROM" - + " game_session_canonical_account_member_repair_operation WHERE transition_id = ?", + + " game_session_canonical_account_member_repair_operation WHERE transition_id" + + " = ?", fixture.transitionId()); assertThat(repair.get("original_projection_state", String.class)) .isEqualTo("PRESENT_AWAITING_COVERAGE"); @@ -308,8 +332,8 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .execute( - "UPDATE game_session_canonical_binding_issuer_index_obligation" - + " SET status = 'ACKNOWLEDGED', inventory_revision = inventory_revision + 1" + "UPDATE game_session_canonical_binding_issuer_index_obligation SET status" + + " = 'ACKNOWLEDGED', inventory_revision = inventory_revision + 1" + " WHERE transition_id = ?", fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) @@ -319,7 +343,8 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { failure, "23514", "gs_original_new_issuer_obligation_source", - "Final issuer obligation requires matching committed original NEW and native acknowledgement")); + "Final issuer obligation requires matching committed original NEW and native" + + " acknowledgement")); assertThat(sqlImage()).isEqualTo(beforeCommitRows); // SQL cannot terminalize the genuine provisional source without its complete receipt. assertThatThrownBy( @@ -327,9 +352,9 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .execute( - "UPDATE game_session_canonical_binding_transition" - + " SET status = 'COMMITTED', inventory_revision = inventory_revision + 1" - + " WHERE transition_id = ?", + "UPDATE game_session_canonical_binding_transition SET status =" + + " 'COMMITTED', inventory_revision = inventory_revision + 1 WHERE" + + " transition_id = ?", fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .satisfies( @@ -338,7 +363,8 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { failure, "23514", "gs_binding_runtime_fence_terminal_owner_required", - "A lease-bound runtime fence cannot be released without definitive first-NEW Account abort evidence")); + "A lease-bound runtime fence cannot be released without definitive first-NEW" + + " Account abort evidence")); assertThat(sqlImage()).isEqualTo(beforeCommitRows); // Even genuine final readback values cannot authorize changing the original source. assertThatThrownBy( @@ -346,10 +372,12 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .execute( - "UPDATE game_session_canonical_binding_transition SET status = 'COMMITTED'," - + " inventory_revision = inventory_revision + 1," - + " original_new_final_session_sha256 = ?, original_new_admission_at_ms = ?," - + " original_new_continuity_expires_at_ms = ?, original_new_session_duration_ms = ?," + "UPDATE game_session_canonical_binding_transition SET status =" + + " 'COMMITTED', inventory_revision = inventory_revision + 1," + + " original_new_final_session_sha256 = ?," + + " original_new_admission_at_ms = ?," + + " original_new_continuity_expires_at_ms = ?," + + " original_new_session_duration_ms = ?," + " candidate_account_index_fence = ? WHERE transition_id = ?", actual.finalSessionSha256(), actual.admissionAtMillis(), @@ -372,7 +400,8 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .fetchSingle( - "SELECT to_jsonb(runtime)::text FROM game_instances runtime WHERE game_instance_uuid = ?", + "SELECT to_jsonb(runtime)::text FROM game_instances runtime WHERE" + + " game_instance_uuid = ?", decision.candidate().gameInstanceId()) .get(0, String.class); assertThatThrownBy(fixture::stopRuntime) @@ -383,12 +412,14 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { failure, "23514", "gs_binding_runtime_row_mutation_fenced", - "Game Instance runtime row is fenced by an unresolved lease-bound binding decision")); + "Game Instance runtime row is fenced by an unresolved lease-bound binding" + + " decision")); assertThat( fixture .dsl() .fetchSingle( - "SELECT to_jsonb(runtime)::text FROM game_instances runtime WHERE game_instance_uuid = ?", + "SELECT to_jsonb(runtime)::text FROM game_instances runtime WHERE" + + " game_instance_uuid = ?", decision.candidate().gameInstanceId()) .get(0, String.class)) .isEqualTo(runningRuntime); @@ -554,8 +585,8 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .execute( - "UPDATE game_session_canonical_binding_issuer_index_obligation SET status = 'REQUIRED'" - + " WHERE transition_id = ?", + "UPDATE game_session_canonical_binding_issuer_index_obligation SET status" + + " = 'REQUIRED' WHERE transition_id = ?", fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .satisfies( @@ -589,8 +620,8 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .execute( - "UPDATE game_session_canonical_binding_transition SET candidate_account_index_fence = ?" - + " WHERE transition_id = ?", + "UPDATE game_session_canonical_binding_transition SET" + + " candidate_account_index_fence = ? WHERE transition_id = ?", UUID.randomUUID(), fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) @@ -606,8 +637,10 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .execute( - "UPDATE game_session_canonical_binding_transition SET original_new_final_session_sha256 = NULL," - + " original_new_admission_at_ms = NULL, original_new_continuity_expires_at_ms = NULL," + "UPDATE game_session_canonical_binding_transition SET" + + " original_new_final_session_sha256 = NULL," + + " original_new_admission_at_ms = NULL," + + " original_new_continuity_expires_at_ms = NULL," + " original_new_session_duration_ms = NULL WHERE transition_id = ?", fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) @@ -623,8 +656,8 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { fixture .dsl() .execute( - "UPDATE game_session_canonical_binding_transition SET inventory_revision = inventory_revision - 1" - + " WHERE transition_id = ?", + "UPDATE game_session_canonical_binding_transition SET inventory_revision" + + " = inventory_revision - 1 WHERE transition_id = ?", fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .satisfies( @@ -676,6 +709,15 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { void genuineAccountAndIssuerAcknowledgementsCannotSubstituteForMissingRegionAcknowledgement() throws Exception { repairAccountMember(); + // Advance the inventory watermark beyond the completed Account repair without installing a + // region acknowledgement, so the test reaches the specific missing-region guard. + assertThat( + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_binding_inventory_clock SET inventory_revision =" + + " inventory_revision + 1 WHERE singleton_id = 1")) + .isOne(); String rows = sqlImage(); Map physical = physicalImage(); assertThatThrownBy(() -> inventory.readOriginalNewFinalAdmissionSource(decision)) @@ -991,19 +1033,4 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { .containsExactly(actual.exactCanonicalBytes()); } } - - private static void assertGuardRefusal( - Throwable failure, String sqlState, String constraint, String message) { - assertThat(failure) - .rootCause() - .isInstanceOfSatisfying( - org.postgresql.util.PSQLException.class, - postgresFailure -> { - assertThat(postgresFailure.getSQLState()).isEqualTo(sqlState); - assertThat(postgresFailure.getServerErrorMessage()).isNotNull(); - assertThat(postgresFailure.getServerErrorMessage().getConstraint()) - .isEqualTo(constraint); - assertThat(postgresFailure.getServerErrorMessage().getMessage()).isEqualTo(message); - }); - } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java similarity index 81% rename from services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport.java rename to services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java index 19f3b9d77b..bda0171380 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java @@ -24,54 +24,42 @@ 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.test.TestContainerImages; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -/** - * Shared physical fixtures and collaborators for original NEW final-admission integration proofs. - */ @SuppressWarnings("resource") -abstract class CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport { +abstract class CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport { + abstract PostgreSQLContainer postgresContainer(); - protected static final Clock CLOCK = Clock.systemUTC(); - protected static final String PRINCIPAL = "gamesession_coord_app"; - protected static final int TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS = 128; - protected static final long TEST_CAPACITY_EVIDENCE_MAXIMUM_BINDING_BYTES = 128L * 1_048_576L; - - @Container - protected static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Container - protected static final GenericContainer REDIS = - new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + abstract GenericContainer redisContainer(); + static final Clock CLOCK = Clock.systemUTC(); + static final String PRINCIPAL = "gamesession_coord_app"; + static final int TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS = 128; + static final long TEST_CAPACITY_EVIDENCE_MAXIMUM_BINDING_BYTES = 128L * 1_048_576L; @TempDir Path directory; - protected RedisClient administrator; - protected RedisClient ownerClient; - protected RedisURI ownerUri; - protected StatefulRedisConnection adminConnection; - protected RedisCommands admin; - protected CanonicalGameplayAdmissionAbortCompositionFixture fixture; - protected CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources sources; - protected CanonicalGameplayBindingInventoryRepository inventory; - protected CanonicalGameplayTenantGameplayTagRepository tags; - protected CanonicalGameplayAdmissionDecision decision; - protected CanonicalGameplayOriginalNewCandidateRedisOwner.Installation installation; - protected RedisScriptCatalog catalog; - protected net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution - controlledCapacity; - protected CanonicalGameplayRegionOwnerCompositionFixture.ExistingBinding regionBinding; + RedisClient administrator; + RedisClient ownerClient; + RedisURI ownerUri; + StatefulRedisConnection adminConnection; + RedisCommands admin; + CanonicalGameplayAdmissionAbortCompositionFixture fixture; + CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources sources; + CanonicalGameplayBindingInventoryRepository inventory; + CanonicalGameplayTenantGameplayTagRepository tags; + CanonicalGameplayAdmissionDecision decision; + CanonicalGameplayOriginalNewCandidateRedisOwner.Installation installation; + RedisScriptCatalog catalog; + net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution controlledCapacity; + CanonicalGameplayRegionOwnerCompositionFixture.ExistingBinding regionBinding; @BeforeEach - protected void setUp() throws Exception { + void setUp() throws Exception { administrator = client(null, null); adminConnection = administrator.connect(ByteArrayCodec.INSTANCE); admin = adminConnection.sync(); @@ -109,10 +97,10 @@ protected void setUp() throws Exception { ownerClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); - String jdbcUrl = POSTGRES.getJdbcUrl(); + String jdbcUrl = postgresContainer().getJdbcUrl(); dataSource.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=public"); - dataSource.setUsername(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setUsername(postgresContainer().getUsername()); + dataSource.setPassword(postgresContainer().getPassword()); fixture = new CanonicalGameplayAdmissionAbortCompositionFixture(dataSource, candidate(), ownerClient); inventory = new CanonicalGameplayBindingInventoryRepository(fixture.dsl()); @@ -140,7 +128,7 @@ protected void setUp() throws Exception { } @AfterEach - protected void tearDown() throws Exception { + void tearDown() throws Exception { try { if (sources != null) sources.close(); } finally { @@ -154,23 +142,38 @@ protected void tearDown() throws Exception { } } - protected void repairAccountMember() { + static void assertGuardRefusal( + Throwable failure, String sqlState, String constraint, String message) { + assertThat(failure) + .rootCause() + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + postgresFailure -> { + assertThat(postgresFailure.getSQLState()).isEqualTo(sqlState); + assertThat(postgresFailure.getServerErrorMessage()).isNotNull(); + assertThat(postgresFailure.getServerErrorMessage().getConstraint()) + .isEqualTo(constraint); + assertThat(postgresFailure.getServerErrorMessage().getMessage()).isEqualTo(message); + }); + } + + void repairAccountMember() { new CanonicalGameplayAccountMemberRepairOwner(fixture.dsl(), ownerClient, catalog) .repair(fixture.transitionId()); } - protected void bridge() { + void bridge() { bridge(true); } - protected void bridge(boolean authorizeCapacity) { + void bridge(boolean authorizeCapacity) { bridge( authorizeCapacity, TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS, TEST_CAPACITY_EVIDENCE_MAXIMUM_BINDING_BYTES); } - protected void bridge(boolean authorizeCapacity, int maximumRecords, long maximumBindingBytes) { + void bridge(boolean authorizeCapacity, int maximumRecords, long maximumBindingBytes) { regionBinding = CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( fixture.dsl(), @@ -234,7 +237,7 @@ protected void bridge(boolean authorizeCapacity, int maximumRecords, long maximu } } - protected void initializeCapacityEvidenceBudget( + void initializeCapacityEvidenceBudget( UUID tenantId, int maximumRecords, long maximumBindingBytes) { fixture .dsl() @@ -254,9 +257,8 @@ protected void initializeCapacityEvidenceBudget( tenantId); } - protected net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request - anotherAttempt( - net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request) { + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request anotherAttempt( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request) { return new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( request.identity(), UUID.randomUUID(), @@ -272,7 +274,7 @@ protected void initializeCapacityEvidenceBudget( .withDigest(); } - protected CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback issuerOpen() { + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback issuerOpen() { var repository = new CanonicalGameplayIssuerAdmissionBarrierRepository( fixture.dsl(), tags, fixture.currentIssuerSource()); @@ -284,7 +286,7 @@ protected CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback issuerOpen( /** * Controlled upstream OPEN record and physical hash, without INITIAL owner/currentness claims. */ - protected CanonicalGameplayAccountInitialOpenProof.CurrentOpen controlledAccountOpen() { + CanonicalGameplayAccountInitialOpenProof.CurrentOpen controlledAccountOpen() { var binding = decision.candidate(); var assignment = tags.assignmentForTransition(fixture.transitionId()); UUID initializer = UUID.randomUUID(); @@ -337,7 +339,7 @@ protected CanonicalGameplayAccountInitialOpenProof.CurrentOpen controlledAccount fields); } - protected String issuerKey(CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + String issuerKey(CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { var value = readback.value(); return CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( value.issuerId(), @@ -346,14 +348,14 @@ protected String issuerKey(CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Rea value.tenantGameplayTag()); } - protected CanonicalGameplayOriginalNewCandidateRedisOwner candidateOwner( + CanonicalGameplayOriginalNewCandidateRedisOwner candidateOwner( CanonicalGameplayBindingInventoryRepository repository) { return CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create( ownerClient, catalog, repository, tags); } - protected net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus - replaceRegionOwner(String successor) { + net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus replaceRegionOwner( + String successor) { var original = regionBinding.installation(); var repository = new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()); var current = repository.find(original.source).orElseThrow(); @@ -369,19 +371,38 @@ protected CanonicalGameplayOriginalNewCandidateRedisOwner candidateOwner( CLOCK.instant()); } - protected CanonicalGameplayOriginalNewCapacityExecutionOwner capacityOwner() { + CanonicalGameplayOriginalNewCapacityExecutionOwner capacityOwner() { return new CanonicalGameplayOriginalNewCapacityExecutionOwner( fixture.dsl(), ownerClient, catalog, CLOCK, tags); } - protected String capacityKey(CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { + CanonicalGameplayRegionLeaseOwner.Installation actualTransferHandoff() throws Exception { + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + return CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + regionBinding.installation(), + sources.resolver, + transfer, + deadline()); + } + + String capacityKey(CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { return "session:game:capacity-execution:{" + assignment.tenantGameplayTag() + "}:" + controlledCapacity.request().admissionAttemptId(); } - protected void commitHistoricalSplitReceipt( + void commitHistoricalSplitReceipt( CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback readback) { var sql = fixture.dsl(); // Model the old receipt-only writer while exercising the actual guarded receipt transaction. @@ -422,7 +443,7 @@ EXECUTE FUNCTION fixture_preserve_authorized_execution() assertThat(execution.get("terminal_readback", byte[].class)).isNull(); } - protected void controlledRemoveServingKeys( + void controlledRemoveServingKeys( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { var binding = source.candidate().bindingIdentity(); @@ -438,11 +459,11 @@ protected void controlledRemoveServingKeys( ascii(binding.sessionId())); } - protected ControlledCapacityFinalOwner finalOwner() { + ControlledCapacityFinalOwner finalOwner() { return new ControlledCapacityFinalOwner(); } - protected final class ControlledCapacityFinalOwner { + final class ControlledCapacityFinalOwner { CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback finalizeOriginalNewOnce( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, CanonicalGameplayOriginalNewAuthenticatedSession.Template template, @@ -461,11 +482,11 @@ CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback finalizeOriginalNe } } - protected CanonicalGameplayOriginalNewFinalAdmissionReadRepository reader() { + CanonicalGameplayOriginalNewFinalAdmissionReadRepository reader() { return reader(CLOCK); } - protected CanonicalGameplayOriginalNewFinalAdmissionReadRepository reader(Clock readClock) { + CanonicalGameplayOriginalNewFinalAdmissionReadRepository reader(Clock readClock) { return new CanonicalGameplayOriginalNewFinalAdmissionReadRepository( fixture.dsl(), ownerClient, @@ -474,7 +495,7 @@ protected CanonicalGameplayOriginalNewFinalAdmissionReadRepository reader(Clock readClock); } - protected String sqlImage() { + String sqlImage() { Map> rows = new LinkedHashMap<>(); for (String table : List.of( @@ -517,7 +538,7 @@ protected String sqlImage() { return rows.toString(); } - protected Map physicalImage() { + Map physicalImage() { Map image = new java.util.TreeMap<>(); for (byte[] key : admin.keys("session:game:*")) { image.put( @@ -530,7 +551,7 @@ protected Map physicalImage() { return image; } - protected static Candidate candidate() { + static Candidate candidate() { return new Candidate( UUID.randomUUID(), UUID.randomUUID(), @@ -549,25 +570,25 @@ protected static Candidate candidate() { BigInteger.valueOf(64)); } - protected RedisClient client(String username, String password) { + RedisClient client(String username, String password) { var client = RedisClient.create(redisUri(username, password)); client.setOptions(ClientOptions.builder().autoReconnect(false).build()); return client; } - protected RedisURI redisUri(String username, String password) { + RedisURI redisUri(String username, String password) { var uri = - RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)) + RedisURI.Builder.redis(redisContainer().getHost(), redisContainer().getMappedPort(6379)) .withTimeout(Duration.ofSeconds(5)); if (username != null) uri.withAuthentication(username, password); return uri.build(); } - protected static long deadline() { + static long deadline() { return CLOCK.millis() + 10_000L; } - protected static byte[] ascii(String value) { + static byte[] ascii(String value) { return value.getBytes(StandardCharsets.US_ASCII); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java new file mode 100644 index 0000000000..f3bb8317c1 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java @@ -0,0 +1,1129 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Clock; +import java.time.Duration; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayOriginalNewRegionHandoffIntegrationTest + extends CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Override + PostgreSQLContainer postgresContainer() { + return POSTGRES; + } + + @Override + GenericContainer redisContainer() { + return REDIS; + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "false,false", + "false,true", + "true,false", + "true,true" + }) + void exactAbortedOriginalCompletesSameTransferBeforeAndAfterCapture( + boolean abortAfterCapture, boolean originalReservationExpired) throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + Clock transferClock = + originalReservationExpired ? Clock.offset(CLOCK, Duration.ofHours(1)) : CLOCK; + if (originalReservationExpired) + assertThat(controlledCapacity.reservation().expiresAt()).isBefore(transferClock.instant()); + var repository = + new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), transferClock, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture(transferClock) + .receiver(repository, tags); + var capacity = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + fixture.dsl(), ownerClient, catalog, transferClock, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), transferClock, repository, capacity, receiver); + UUID transferId = null; + if (abortAfterCapture) { + transferId = + repository.within( + transferClock.millis() + 5000L, + ignored -> repository.begin(original.source, original.status)); + UUID capturedId = transferId; + var captured = + repository.within( + transferClock.millis() + 5000L, ignored -> repository.capture(capturedId)); + assertThat(captured).hasSize(1); + } + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + byte[] candidate = admin.get(ascii(installation.sessionKey())); + UUID resumed = + transfer.advance(original.source, original.status, transferClock.millis() + 5000L); + if (transferId != null) assertThat(resumed).isEqualTo(transferId); + String intent = + fixture + .dsl() + .fetchSingle( + "SELECT intent_digest FROM game_session_region_owner_transfer WHERE transfer_id=?", + resumed) + .get(0, String.class); + // Real expiry of the incumbent Redis lease, followed by actual grant acquisition and protected + // installation. + admin.pexpire(ascii(original.grant.key()), 0); + var installed = + abortAfterCapture && !originalReservationExpired + ? resumeAbortedOriginalWithLeaseOwner(transfer, original) + : installAbortedTransferSuccessor(transfer, original, resumed, transferClock); + assertThat(installed.ownerInstanceId()) + .isEqualTo( + abortAfterCapture && !originalReservationExpired + ? "final-owner-handoff" + : "aborted-original-successor"); + assertThat(installed.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(installed); + var completed = + fixture + .dsl() + .fetchSingle( + "SELECT transfer_id,intent_digest,state FROM game_session_region_owner_transfer"); + assertThat(completed.get("transfer_id", UUID.class)).isEqualTo(resumed); + assertThat(completed.get("intent_digest", String.class)).isEqualTo(intent); + assertThat(completed.get("state", String.class)).isEqualTo("COMPLETED"); + assertThat( + receiver + .observeForRegionOwnerTransfer(resumed, 0, transferClock.millis() + 5000L) + .regionOwnerTransferContext() + .controlState()) + .isEqualTo("COMPLETED"); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(candidate); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition WHERE" + + " transition_id=?", + fixture.transitionId()) + .get(0, String.class)) + .isEqualTo("ABORTED"); + assertThatThrownBy(() -> tags.assignmentForTransition(fixture.transitionId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy( + () -> + capacity.readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + String terminalRows = sqlImage(); + assertThatThrownBy( + () -> + transfer.advance(original.source, original.status, transferClock.millis() + 5000L)) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(terminalRows); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(strings = {"missing", "binding", "ttl"}) + void abortedTransferCannotInstallWithMissingOrChangedRetainedFence(String fault) + throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var assignment = tags.assignmentForTransition(fixture.transitionId()); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + UUID id = transfer.advance(original.source, original.status, deadline()); + byte[] key = ascii(capacityKey(assignment)); + if (fault.equals("missing")) admin.del(java.util.List.of(key).toArray(byte[][]::new)); + else if (fault.equals("binding")) admin.hset(key, ascii("binding"), ascii("changed")); + else admin.pexpire(key, 60_000L); + byte[] altered = + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key); + String retained = sqlImage(); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy(() -> installAbortedTransferSuccessor(transfer, original, id, CLOCK)) + .isInstanceOf(IllegalStateException.class); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(original.status); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT state FROM game_session_region_owner_transfer") + .get(0, String.class)) + .isEqualTo("FROZEN"); + assertThat(sqlImage()).isEqualTo(retained); + assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) + .containsExactly(altered); + } + + @Test + void authorizedUnknownHandoffKeepsOriginalCandidateAndRefusesCompletedMutation() + throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + byte[] candidate = admin.get(ascii(installation.sessionKey())); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + UUID transferId = transfer.advance(original.source, original.status, deadline()); + assertThatThrownBy(() -> replaceRegionOwner("unproved-successor")) + .isInstanceOf(IllegalStateException.class); + admin.pexpire(ascii(original.grant.key()), 0); + var successor = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + deadline()); + var completed = receiver.observeForRegionOwnerTransfer(transferId, 0, deadline()); + assertThat(completed.regionOwnerTransferContext().controlState()).isEqualTo("COMPLETED"); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(candidate); + assertThatThrownBy( + () -> repository.within(deadline(), ignored -> repository.capture(transferId))) + .isInstanceOf(IllegalStateException.class); + assertThat(successor.status.ownerInstanceId()).isEqualTo("final-owner-handoff"); + } + + @Test + void completedTransferResumesOnlyWithTheSameLivePrivateGrant() throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var failAfterCommit = new java.util.concurrent.atomic.AtomicBoolean(true); + var observationSource = + new CanonicalGameplayRegionOwnerTransferObservationSource() { + @Override + public Context readCurrent(UUID transferId, long targetOrdinal) { + var context = repository.readCurrent(transferId, targetOrdinal); + if ("COMPLETED".equals(context.controlState()) && failAfterCommit.getAndSet(false)) { + throw new IllegalStateException("Controlled completed observation failure"); + } + return context; + } + + @Override + public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository sourceTags) { + return repository.readAssignment(transitionId, sourceTags); + } + }; + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(observationSource, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + var identity = + new net.firedevops.firemud.common.runtime.RuntimeIdentity( + "game-session-service", + "final-owner-handoff", + "localhost", + CLOCK.instant(), + "test", + "test", + "controlled-test-image"); + CanonicalGameplayRegionIncarnationSource incarnation = + scope -> { + assertThat(scope).isEqualTo(original.incarnation.scope()); + return original.incarnation; + }; + var successor = + CanonicalGameplayRegionLeaseOwnerFactory.compose( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + incarnation, + sources.resolver, + identity, + java.time.Duration.ofSeconds(30), + CLOCK); + admin.pexpire(ascii(original.grant.key()), 0); + var failure = + org.junit.jupiter.api.Assertions.assertThrows( + CanonicalGameplayRegionLeaseOwner.TransferCompletionUnconfirmed.class, + () -> + successor.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline())); + assertThat(failAfterCommit).isFalse(); + var durable = + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow(); + assertThat(durable.executorFence()).isGreaterThan(original.status.executorFence()); + var completed = + fixture + .dsl() + .fetchSingle("SELECT state, transfer_id FROM game_session_region_owner_transfer"); + assertThat(completed.get("state", String.class)).isEqualTo("COMPLETED"); + assertThatThrownBy( + () -> + successor.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline())) + .isInstanceOf(IllegalStateException.class); + var recovered = successor.resumeCompletedTransfer(failure, deadline()); + assertThat(recovered.status).isEqualTo(durable); + assertThat(recovered.grant.tokenCorrelation()).isEqualTo(durable.leaseTokenCorrelation()); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT state, transfer_id FROM game_session_region_owner_transfer")) + .isEqualTo(completed); + var completedSql = sqlImage(); + assertThat(successor.resumeCompletedTransfer(failure, deadline()).status).isEqualTo(durable); + assertThat(sqlImage()).isEqualTo(completedSql); + var restarted = + CanonicalGameplayRegionLeaseOwnerFactory.compose( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + incarnation, + sources.resolver, + new net.firedevops.firemud.common.runtime.RuntimeIdentity( + "game-session-service", + identity.serviceInstanceId(), + "localhost", + CLOCK.instant(), + "test", + "test", + "controlled-test-image"), + java.time.Duration.ofSeconds(30), + CLOCK); + assertThatThrownBy(() -> restarted.resumeCompletedTransfer(failure, deadline())) + .isInstanceOf(IllegalStateException.class); + byte[] leaseKey = ascii(recovered.grant.key()); + assertThatThrownBy( + () -> + restarted.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(completedSql); + admin.pexpire(leaseKey, 0); + assertThatThrownBy(() -> successor.resumeCompletedTransfer(failure, deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(durable); + + assertThat( + admin.set( + leaseKey, + ascii(UUID.randomUUID().toString()), + io.lettuce.core.SetArgs.Builder.nx().px(30_000))) + .isEqualTo("OK"); + assertThatThrownBy( + () -> + restarted.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(completedSql); + + admin.pexpire(leaseKey, 0); + var fresh = + restarted.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline()); + assertThat(fresh.status.ownerInstanceId()).isEqualTo(durable.ownerInstanceId()); + assertThat(fresh.status.executorFence()).isGreaterThan(durable.executorFence()); + assertThat(fresh.grant.tokenCorrelation()).isNotEqualTo(recovered.grant.tokenCorrelation()); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT state, transfer_id FROM game_session_region_owner_transfer WHERE" + + " transfer_id = ?", + completed.get("transfer_id", UUID.class))) + .isEqualTo(completed); + assertThat( + fixture.dsl().fetchCount(org.jooq.impl.DSL.table("game_session_region_owner_transfer"))) + .isEqualTo(2); + } + + @Test + void completedTransferRecoversExactAbortRetainedBeforeIndependentVerification() throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var pinnedEvidence = inventory.readProvisionalCasEvidence(original.transitionId); + var pinnedCandidate = + inventory.readRegionTransferOriginalCandidate(original.transitionId, pinnedEvidence); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var accountAbortedAfterInstall = new java.util.concurrent.atomic.AtomicBoolean(); + var observationSource = + new CanonicalGameplayRegionOwnerTransferObservationSource() { + @Override + public Context readCurrent(UUID transferId, long targetOrdinal) { + var context = repository.readCurrent(transferId, targetOrdinal); + if ("COMPLETED".equals(context.controlState()) + && accountAbortedAfterInstall.compareAndSet(false, true)) { + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + } + return context; + } + + @Override + public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository sourceTags) { + return repository.readAssignment(transitionId, sourceTags); + } + }; + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(observationSource, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + var identity = + new net.firedevops.firemud.common.runtime.RuntimeIdentity( + "game-session-service", + "final-owner-handoff", + "localhost", + CLOCK.instant(), + "test", + "test", + "controlled-test-image"); + CanonicalGameplayRegionIncarnationSource incarnation = + scope -> { + assertThat(scope).isEqualTo(original.incarnation.scope()); + return original.incarnation; + }; + var successor = + CanonicalGameplayRegionLeaseOwnerFactory.compose( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + incarnation, + sources.resolver, + identity, + java.time.Duration.ofSeconds(30), + CLOCK); + admin.pexpire(ascii(original.grant.key()), 0); + var interrupted = + org.junit.jupiter.api.Assertions.assertThrows( + CanonicalGameplayRegionLeaseOwner.TransferCompletionUnconfirmed.class, + () -> + successor.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline())); + + assertThat(accountAbortedAfterInstall).isTrue(); + var durable = + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow(); + assertThat(durable.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT state FROM game_session_region_owner_transfer") + .get(0, String.class)) + .isEqualTo("COMPLETED"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition WHERE" + + " transition_id=?", + original.transitionId) + .get(0, String.class)) + .isEqualTo("ABORTED"); + + var recovered = successor.resumeCompletedTransfer(interrupted, deadline()); + assertThat(recovered.status).isEqualTo(durable); + assertThat(recovered.grant.tokenCorrelation()).isEqualTo(durable.leaseTokenCorrelation()); + assertThat(inventory.readRegionTransferAbortedCandidate(original.transitionId, pinnedCandidate)) + .contains(pinnedCandidate); + assertThatThrownBy(() -> inventory.readProvisionalCasEvidence(original.transitionId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not a retryable provisional operation"); + assertThatThrownBy(() -> successor.revalidateBeforeBridge(recovered)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void committedOriginalStartsHandoffWithoutAnExistingTransfer() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var original = regionBinding.installation(); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var readback = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + inventory.commitOriginalNewFinalAdmission(readback); + } + var retained = inventory.readRegionTransferOriginalSource(fixture.transitionId(), source); + var terminal = + capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); + assertThat(terminal.disposition()).isEqualTo("COMMITTED"); + assertThat( + fixture.dsl().fetchCount(org.jooq.impl.DSL.table("game_session_region_owner_transfer"))) + .isZero(); + byte[] session = admin.get(ascii(installation.sessionKey())); + + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); + + assertThat(successor.evidence).isNull(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(session); + var current = inventory.readRegionTransferOriginalSource(fixture.transitionId(), retained); + assertThat(current.finalReceipt()).isEqualTo(retained.finalReceipt()); + assertThat( + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation()) + .canonicalReadback()) + .containsExactly(terminal.canonicalReadback()); + } + + @Test + void committedOriginalCanStartTopologyHandoffUnderRetainedAccountFenceIntent() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var original = regionBinding.installation(); + var accountOpen = controlledAccountOpen(); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var readback = + finalOwner() + .finalizeOriginalNewOnce( + source, template, accountOpen, issuerOpen(), controlledCapacity, deadline())) { + inventory.commitOriginalNewFinalAdmission(readback); + } + + var retained = inventory.readRegionTransferOriginalSource(fixture.transitionId(), source); + assertThat(retained.transitionStatus()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED); + var terminal = + capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); + byte[] session = admin.get(ascii(installation.sessionKey())); + byte[] accountBarrier = + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( + admin, ascii(accountOpen.key())); + String originalRepair = + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(repair)::text FROM" + + " game_session_canonical_account_member_repair_operation repair WHERE" + + " transition_id=?", + fixture.transitionId()) + .get(0, String.class); + + var fenceIntent = + new CanonicalGameplayAccountAdmissionBarrierRepository(fixture.dsl()) + .beginFenceIntent(source.candidate().bindingIdentity().accountId(), UUID.randomUUID()); + assertThat(fenceIntent.state().name()).isEqualTo("ACQUISITION_INTENT"); + assertThat(fenceIntent.cohortRows()) + .filteredOn( + row -> + row.kind() == CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.TRANSITION + && row.sourceKey().equals(fixture.transitionId().toString())) + .hasSize(1); + String fencedControl = + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(control)::text FROM" + + " game_session_canonical_account_coverage_control control WHERE account_id=?", + source.candidate().bindingIdentity().accountId()) + .get(0, String.class); + + assertThatThrownBy(() -> inventory.readOriginalNewFinalAdmissionSource(decision)) + .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + var underFence = inventory.readRegionTransferOriginalSource(fixture.transitionId(), source); + assertThat(underFence.finalReceipt()).isEqualTo(retained.finalReceipt()); + + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); + + assertThat(successor.evidence).isNull(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(session); + assertThat( + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( + admin, ascii(accountOpen.key()))) + .containsExactly(accountBarrier); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(control)::text FROM" + + " game_session_canonical_account_coverage_control control WHERE" + + " account_id=?", + source.candidate().bindingIdentity().accountId()) + .get(0, String.class)) + .isEqualTo(fencedControl); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(repair)::text FROM" + + " game_session_canonical_account_member_repair_operation repair WHERE" + + " transition_id=?", + fixture.transitionId()) + .get(0, String.class)) + .isEqualTo(originalRepair); + assertThat( + inventory + .readRegionTransferOriginalSource(fixture.transitionId(), underFence) + .finalReceipt()) + .isEqualTo(retained.finalReceipt()); + assertThat( + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation()) + .canonicalReadback()) + .containsExactly(terminal.canonicalReadback()); + } + + @Test + void frozenTransferResumesExactTerminalOriginalThatCommittedBeforeCapture() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + UUID transferId; + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var readback = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + transferId = + repository.within( + deadline(), ignored -> repository.begin(original.source, original.status)); + assertThat(transferId).isNotNull(); + inventory.commitOriginalNewFinalAdmission(readback); + } + var captured = repository.within(deadline(), ignored -> repository.capture(transferId)); + assertThat(captured).isEmpty(); + var retained = inventory.readRegionTransferOriginalSource(fixture.transitionId(), source); + byte[] committed = admin.get(ascii(installation.sessionKey())); + assertThat(retained.finalReceipt()).isPresent(); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(original.status); + admin.pexpire(ascii(original.grant.key()), 0); + var successor = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + deadline()); + assertThat(successor.evidence).isNull(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + var completed = fixture.dsl().fetchSingle("SELECT * FROM game_session_region_owner_transfer"); + assertThat(completed.get("transfer_id", UUID.class)).isEqualTo(transferId); + assertThat(completed.get("state", String.class)).isEqualTo("COMPLETED"); + assertThat( + fixture + .dsl() + .fetchCount(org.jooq.impl.DSL.table("game_session_region_owner_transfer_item"))) + .isZero(); + assertThat( + inventory + .readRegionTransferOriginalSource(fixture.transitionId(), retained) + .finalReceipt()) + .isEqualTo(retained.finalReceipt()); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); + } + + @Test + void secondFrozenHandoffResumesOlderOriginalAbortedBeforeCapture() throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var originalCandidate = inventory.readOriginalNewFinalAdmissionSource(decision).candidate(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + + UUID firstTransferId = transfer.advance(original.source, original.status, deadline()); + assertThat(firstTransferId).isNotNull(); + admin.pexpire(ascii(original.grant.key()), 0); + var firstSuccessor = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + deadline()); + assertThat(firstSuccessor.status.executorFence()) + .isGreaterThan(original.status.executorFence()); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT state FROM game_session_region_owner_transfer WHERE transfer_id=?", + firstTransferId) + .get(0, String.class)) + .isEqualTo("COMPLETED"); + + UUID secondTransferId = + repository.within( + deadline(), ignored -> repository.begin(firstSuccessor.source, firstSuccessor.status)); + // Leave the committed second freeze without capture, as after an interrupted process. + assertThat(secondTransferId).isNotNull().isNotEqualTo(firstTransferId); + var secondFrozen = + fixture + .dsl() + .fetchSingle( + "SELECT old_owner_id,old_owner_fence,state FROM game_session_region_owner_transfer" + + " WHERE transfer_id=?", + secondTransferId); + assertThat(secondFrozen.get("old_owner_id", String.class)) + .isEqualTo(firstSuccessor.status.ownerInstanceId()) + .isNotEqualTo(controlledCapacity.selectedOwnerId()); + assertThat(secondFrozen.get("old_owner_fence", Long.class)) + .isGreaterThan(controlledCapacity.selectedOwnerFence()); + assertThat(secondFrozen.get("state", String.class)).isEqualTo("FROZEN"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_region_owner_transfer_item WHERE" + + " transfer_id=?", + secondTransferId) + .get(0, Long.class)) + .isZero(); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + + var frozenOriginal = + repository.within(deadline(), ignored -> repository.frozenOriginal(fixture.transitionId())); + assertThat(frozenOriginal).isNotNull(); + assertThat(frozenOriginal.transferId()).isEqualTo(secondTransferId); + assertThat(frozenOriginal.executionDigest()).isEqualTo(controlledCapacity.digest()); + assertThat(frozenOriginal.candidate().canonicalBytes()) + .containsExactly(originalCandidate.canonicalBytes()); + + byte[] candidateBytes = admin.get(ascii(installation.sessionKey())); + var thirdIdentity = + new net.firedevops.firemud.common.runtime.RuntimeIdentity( + "game-session-service", + "third-owner-handoff", + "localhost", + CLOCK.instant(), + "test", + "test", + "controlled-test-image"); + CanonicalGameplayRegionIncarnationSource thirdIncarnation = + scope -> { + assertThat(scope).isEqualTo(firstSuccessor.incarnation.scope()); + return firstSuccessor.incarnation; + }; + var thirdOwner = + CanonicalGameplayRegionLeaseOwnerFactory.compose( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + thirdIncarnation, + sources.resolver, + thirdIdentity, + Duration.ofSeconds(30), + CLOCK); + admin.pexpire(ascii(firstSuccessor.grant.key()), 0); + var secondSuccessor = + thirdOwner.installForTransition( + null, firstSuccessor.transitionId, firstSuccessor.worldRequest, transfer, deadline()); + assertThat(secondSuccessor.status.ownerInstanceId()).isEqualTo("third-owner-handoff"); + assertThat(secondSuccessor.status.executorFence()) + .isGreaterThan(firstSuccessor.status.executorFence()); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(candidateBytes); + var retainedExecution = + fixture + .dsl() + .fetchSingle( + "SELECT selected_owner_id,selected_owner_fence,status FROM" + + " game_session_original_new_capacity_execution WHERE execution_digest=?", + controlledCapacity.digest()); + assertThat(retainedExecution.get("selected_owner_id", String.class)) + .isEqualTo(controlledCapacity.selectedOwnerId()); + assertThat(retainedExecution.get("selected_owner_fence", Long.class)) + .isEqualTo(controlledCapacity.selectedOwnerFence()); + assertThat(retainedExecution.get("status", String.class)).isEqualTo("AUTHORIZED"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT old_owner_id,old_owner_fence,new_owner_id,new_owner_fence,state FROM" + + " game_session_region_owner_transfer WHERE transfer_id=?", + secondTransferId) + .get("state", String.class)) + .isEqualTo("COMPLETED"); + var completedSecondTransfer = + fixture + .dsl() + .fetchSingle( + "SELECT old_owner_id,old_owner_fence,new_owner_id,new_owner_fence FROM" + + " game_session_region_owner_transfer WHERE transfer_id=?", + secondTransferId); + assertThat(completedSecondTransfer.get("old_owner_id", String.class)) + .isEqualTo(firstSuccessor.status.ownerInstanceId()); + assertThat(completedSecondTransfer.get("new_owner_id", String.class)) + .isEqualTo("third-owner-handoff"); + assertThat(completedSecondTransfer.get("new_owner_fence", Long.class)) + .isGreaterThan(completedSecondTransfer.get("old_owner_fence", Long.class)); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition WHERE" + + " transition_id=?", + fixture.transitionId()) + .get(0, String.class)) + .isEqualTo("ABORTED"); + } + + @Test + void frozenTransferResumesSameCommittedOriginalAfterFenceRetentionFailure() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + byte[] committed; + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var ignored = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + committed = admin.get(ascii(installation.sessionKey())); + } + var original = regionBinding.installation(); + var failRetention = new java.util.concurrent.atomic.AtomicBoolean(true); + var failed = new java.util.concurrent.atomic.AtomicBoolean(); + var observer = + new org.jooq.impl.DefaultExecuteListener() { + @Override + public void executeStart(org.jooq.ExecuteContext context) { + String query = context.sql(); + if (query == null || !query.contains(" SET fence_readback=")) return; + if (!failRetention.get()) return; + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("COMMITTED"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT original_new_final_session_sha256 FROM" + + " game_session_canonical_binding_transition WHERE" + + " transition_id=?", + fixture.transitionId()) + .get(0, String.class)) + .isNotBlank(); + failed.set(true); + throw new IllegalStateException("Controlled failure after positive SQL retention"); + } + }; + var observedSql = + org.jooq.impl.DSL.using(fixture.dsl().configuration().deriveAppending(observer)); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(observedSql, CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + observedSql, CLOCK, repository, capacityOwner(), receiver); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + deadline())) + .isInstanceOf(RuntimeException.class); + assertThat(failed).isTrue(); + var frozen = fixture.dsl().fetchSingle("SELECT * FROM game_session_region_owner_transfer"); + UUID transferId = frozen.get("transfer_id", UUID.class); + String intent = frozen.get("intent_digest", String.class); + assertThat(frozen.get("state", String.class)).isEqualTo("FROZEN"); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(original.status); + var retained = inventory.readRegionTransferOriginalSource(fixture.transitionId(), source); + assertThat(retained.transitionStatus()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED); + assertThat(retained.finalReceipt()).isPresent(); + String executionImage = + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(e)::text FROM game_session_original_new_capacity_execution e WHERE" + + " execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class); + long sequence = + fixture + .dsl() + .fetchSingle("SELECT last_value FROM game_session_region_executor_fence_seq") + .get(0, Long.class); + failRetention.set(false); + // Controlled expiry of the failed contender's grant, not a bypass of a live incumbent. + admin.pexpire(ascii(original.grant.key()), 0); + var successor = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + deadline()); + assertThat(successor.status.ownerInstanceId()).isEqualTo("final-owner-handoff"); + var completed = fixture.dsl().fetchSingle("SELECT * FROM game_session_region_owner_transfer"); + assertThat(completed.get("transfer_id", UUID.class)).isEqualTo(transferId); + assertThat(completed.get("intent_digest", String.class)).isEqualTo(intent); + assertThat(completed.get("state", String.class)).isEqualTo("COMPLETED"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT last_value FROM game_session_region_executor_fence_seq") + .get(0, Long.class)) + .isEqualTo(sequence + 1); + assertThat( + inventory + .readRegionTransferOriginalSource(fixture.transitionId(), retained) + .finalReceipt()) + .isEqualTo(retained.finalReceipt()); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(e)::text FROM game_session_original_new_capacity_execution e" + + " WHERE execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo(executionImage); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); + assertThat(successor.evidence) + .as("committed continuation grants no provisional bridge authority") + .isNull(); + // The old epoch cannot reacquire the lease after the successor advances the timeline. + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + deadline())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Game Session region lease is unavailable"); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(successor.status); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT last_value FROM game_session_region_executor_fence_seq") + .get(0, Long.class)) + .isEqualTo(sequence + 1); + } + + private net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus + resumeAbortedOriginalWithLeaseOwner( + CanonicalGameplayRegionOwnerTransferCoordinator transfer, + CanonicalGameplayRegionLeaseOwner.Installation original) { + var resumed = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + deadline()); + assertThat(resumed.evidence).isNull(); + return resumed.status; + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void abortedCapturedOriginalRetainsPhysicalClosureBeforeSuccessorInstallation( + boolean closeBeforeAbort) throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + UUID id = + repository.within( + deadline(), ignored -> repository.begin(original.source, original.status)); + var captured = repository.within(deadline(), ignored -> repository.capture(id)); + assertThat(captured).hasSize(1); + if (closeBeforeAbort) + capacityOwner() + .closeOriginalAttempt(controlledCapacity.request(), controlledCapacity.reservation()); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + if (!closeBeforeAbort) + capacityOwner() + .closeOriginalAttempt(controlledCapacity.request(), controlledCapacity.reservation()); + var proof = + capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); + assertThat(proof.disposition()).isEqualTo("NOT_EXECUTED_AFTER_AUTHORIZATION"); + byte[] tombstone = + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( + admin, + ascii( + capacityKey(tags.assignmentForRetainedCapacityExecution(fixture.transitionId())))); + assertThat(transfer.advance(original.source, original.status, deadline())).isEqualTo(id); + admin.pexpire(ascii(original.grant.key()), 0); + var installed = installAbortedTransferSuccessor(transfer, original, id, CLOCK); + assertThat(installed.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat( + receiver + .observeForRegionOwnerTransfer(id, 0, deadline()) + .regionOwnerTransferContext() + .controlState()) + .isEqualTo("COMPLETED"); + assertThat( + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation()) + .canonicalReadback()) + .containsExactly(proof.canonicalReadback()); + assertThat( + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( + admin, + ascii( + capacityKey( + tags.assignmentForRetainedCapacityExecution(fixture.transitionId()))))) + .containsExactly(tombstone); + } + + private net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus + installAbortedTransferSuccessor( + CanonicalGameplayRegionOwnerTransferCoordinator transfer, + CanonicalGameplayRegionLeaseOwner.Installation original, + UUID transferId, + Clock transferClock) { + var identity = + new net.firedevops.firemud.common.runtime.RuntimeIdentity( + "game-session-service", + "aborted-original-successor", + "localhost", + transferClock.instant(), + "test", + "test", + "controlled-test-image"); + var leases = new CanonicalGameplayRegionLeaseRedisOwner(ownerClient, ownerUri, catalog); + var grant = + leases.acquire( + original.source, original.status.regionEpoch(), Duration.ofSeconds(30), identity); + leases.requireGrantScope(grant, original.source, original.status.regionEpoch(), identity); + var preparation = + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .findTimelinePreparation(original.source) + .orElseThrow(); + leases.verifyInitializedTimeline(grant, preparation); + leases.requireCurrent(grant); + var installed = + transfer.install( + transferId, + original.source, + original.status, + grant.tokenCorrelation(), + identity.service(), + identity.serviceInstanceId(), + transferClock.millis() + 5000L); + leases.requireCurrent(grant); + return installed; + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java new file mode 100644 index 0000000000..dffd890d2b --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java @@ -0,0 +1,1097 @@ +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.when; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RestoreArgs; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; +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; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest + extends CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Override + PostgreSQLContainer postgresContainer() { + return POSTGRES; + } + + @Override + GenericContainer redisContainer() { + return REDIS; + } + + @Test + void lostDispatchCommitReplyBeforeRedisSendFencesUnknownAndActuallyHandsOff() throws Exception { + repairAccountMember(); + bridge(false); + String schema = fixture.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); + DriverManagerDataSource raw = new DriverManagerDataSource(); + raw.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + raw.setUrl(jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema); + raw.setUsername(POSTGRES.getUsername()); + raw.setPassword(POSTGRES.getPassword()); + var stoppedAfterCommit = new java.util.concurrent.atomic.AtomicBoolean(); + var stoppingDataSource = + new org.springframework.jdbc.datasource.DelegatingDataSource(raw) { + @Override + public java.sql.Connection getConnection() throws java.sql.SQLException { + return failDispatchCommitReplyAfterMarker( + super.getConnection(), raw, controlledCapacity.digest(), stoppedAfterCommit); + } + }; + var stoppingDsl = org.jooq.impl.DSL.using(stoppingDataSource, org.jooq.SQLDialect.POSTGRES); + var stoppingOwner = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + stoppingDsl, ownerClient, catalog, CLOCK, tags); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var accountOpen = controlledAccountOpen(); + var issuerOpen = issuerOpen(); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var rawTemplate = credential.template(); + var template = rawTemplate.bindCapacityExecution(controlledCapacity)) { + assertThatThrownBy( + () -> + stoppingOwner.authorize( + source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) + .isInstanceOf(RuntimeException.class); + } + assertThat(stoppedAfterCommit).isTrue(); + String originalKey = capacityKey(tags.assignmentForTransition(fixture.transitionId())); + assertThat(admin.type(ascii(originalKey))).isEqualTo("none"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("INSTALL_DISPATCHED"); + var original = regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat( + admin.hget( + ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))), + ascii("state"))) + .containsExactly(ascii("FENCED_INDETERMINATE")); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("INSTALL_DISPATCHED"); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .closeOriginalAttempt( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void retainedTransferObservationDoesNotWaitOnInventoryClock() throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + UUID transferId = transfer.advance(original.source, original.status, deadline()); + String schema = fixture.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); + try (var blocker = + java.sql.DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + blocker.setSchema(schema); + blocker.setAutoCommit(false); + try (var statement = blocker.createStatement()) { + statement + .executeQuery( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id=1 FOR UPDATE") + .close(); + } + try { + var observation = receiver.observeForRegionOwnerTransfer(transferId, 0, deadline()); + assertThat(observation.regionOwnerTransferContext().controlState()).isEqualTo("FROZEN"); + } finally { + blocker.rollback(); + } + } + } + + @Test + void contenderAcquireUsesBoundedInitialTtlWhileOrdinaryRenewKeepsConfiguredTtl() + throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var leases = new CanonicalGameplayRegionLeaseRedisOwner(ownerClient, ownerUri, catalog); + var identity = + new net.firedevops.firemud.common.runtime.RuntimeIdentity( + "game-session-service", + "bounded-contender", + "localhost", + CLOCK.instant(), + "test", + "test", + "controlled-test-image"); + byte[] key = ascii(original.grant.key()); + assertThat(admin.pexpire(key, 0)).isTrue(); + byte[] acquireScript; + try (InputStream input = + getClass() + .getClassLoader() + .getResourceAsStream( + CanonicalGameplayRegionLeaseRedisScriptContribution.ACQUIRE_PATH)) { + assertThat(input).isNotNull(); + acquireScript = input.readAllBytes(); + } + byte[][] keys = { + key, + ascii( + CanonicalGameplayRegionRedisKeys.meta( + original.source.tenantId(), + original.source.gameInstanceId(), + original.source.regionId())) + }; + byte[] token = ascii(UUID.randomUUID().toString()); + byte[][] arguments = { + ascii("gs_region_lease/v2"), + token, + ascii(Long.toString(original.status.regionEpoch())), + ascii("30000"), + ascii("1") + }; + Long refused = admin.eval(acquireScript, ScriptOutputType.INTEGER, keys, arguments); + assertThat(refused).isZero(); + assertThat(admin.type(key)).isEqualTo("none"); + + // Bypass the Java client's own TTL cap to exercise the Redis deadline independently. + long redisNow = + admin.eval( + "local now = redis.call('TIME'); return now[1] * 1000 + math.floor(now[2] / 1000)", + ScriptOutputType.INTEGER); + long deadline = redisNow + 5_000L; + arguments[4] = ascii(Long.toString(deadline)); + Long acquired = admin.eval(acquireScript, ScriptOutputType.INTEGER, keys, arguments); + assertThat(acquired).isEqualTo(1L); + long expiry = admin.pexpiretime(key); + assertThat(expiry).isGreaterThan(redisNow).isLessThanOrEqualTo(deadline); + + arguments[4] = ascii("1"); + Long replayed = admin.eval(acquireScript, ScriptOutputType.INTEGER, keys, arguments); + assertThat(replayed).isEqualTo(2L); + assertThat(admin.get(key)).containsExactly(token); + assertThat(admin.pexpiretime(key)).isEqualTo(expiry); + assertThat(admin.pexpire(key, 0)).isTrue(); + + var grant = + leases + .forHandoffDeadline(CLOCK, CLOCK.millis() + 5_000L) + .acquire( + original.source, original.status.regionEpoch(), Duration.ofSeconds(30), identity); + assertThat(admin.pttl(key)).isPositive().isLessThanOrEqualTo(5_000L); + leases.renew(grant, Duration.ofSeconds(30)); + assertThat(admin.pttl(key)).isGreaterThan(5_000L).isLessThanOrEqualTo(30_000L); + } + + @Test + void contenderCannotFreezeRenewingOwnerAndExpiredLeaseStillTransfers() throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var leases = new CanonicalGameplayRegionLeaseRedisOwner(ownerClient, ownerUri, catalog); + String rows = sqlImage(); + Map physical = physicalImage(); + String key = capacityKey(tags.assignmentForTransition(fixture.transitionId())); + for (int attempt = 0; attempt < 2; attempt++) { + leases.renew(original.grant, Duration.ofSeconds(30)); + assertThatThrownBy(this::actualTransferHandoff).isInstanceOf(IllegalStateException.class); + leases.requireCurrent(original.grant); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + assertThat(admin.hget(ascii(key), ascii("state"))).containsExactly(ascii("AUTHORIZED")); + assertThat( + fixture + .dsl() + .fetchCount(org.jooq.impl.DSL.table("game_session_region_owner_transfer"))) + .isZero(); + } + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(admin.hget(ascii(key), ascii("state"))) + .containsExactly(ascii("FENCED_INDETERMINATE")); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT state FROM game_session_region_owner_transfer") + .get(0, String.class)) + .isEqualTo("COMPLETED"); + } + + @Test + void blockedTransferPreinstallRegionStatusReadKeepsCurrentOwner() throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + String schema = fixture.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); + java.util.concurrent.CompletableFuture handoff = null; + try (var lock = + java.sql.DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + lock.setSchema(schema); + lock.setAutoCommit(false); + int blockerPid; + try (var statement = lock.createStatement()) { + statement.execute("LOCK TABLE game_session_region_runtime_status IN ACCESS EXCLUSIVE MODE"); + try (var rows = statement.executeQuery("SELECT pg_backend_pid()")) { + rows.next(); + blockerPid = rows.getInt(1); + } + } + + handoff = + java.util.concurrent.CompletableFuture.supplyAsync( + () -> { + try { + actualTransferHandoff(); + return false; + } catch (IllegalStateException unavailable) { + return true; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + long blockedDeadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(2); + boolean statusReadBlocked = false; + while (System.nanoTime() < blockedDeadline && !statusReadBlocked && !handoff.isDone()) { + statusReadBlocked = + fixture + .dsl() + .fetchOne( + "SELECT pid FROM pg_stat_activity WHERE pid <> pg_backend_pid()" + + " AND ? = ANY(pg_blocking_pids(pid))" + + " AND query LIKE '%game_session_region_runtime_status%' LIMIT 1", + blockerPid) + != null; + if (!statusReadBlocked) Thread.sleep(20L); + } + boolean failedClosed = handoff.get(7, java.util.concurrent.TimeUnit.SECONDS); + assertThat(statusReadBlocked).as("handoff reached the blocked region status read").isTrue(); + assertThat(failedClosed).as("bounded status read fails closed").isTrue(); + } finally { + if (handoff != null && !handoff.isDone()) { + assertThat(handoff.get(7, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + + var current = + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow(); + assertThat(current.executorFence()).isEqualTo(original.status.executorFence()); + assertThat(current.ownerInstanceId()).isEqualTo(original.status.ownerInstanceId()); + assertThat( + fixture.dsl().fetchCount(org.jooq.impl.DSL.table("game_session_region_owner_transfer"))) + .isZero(); + } + + @Test + void retainedTransferFenceLossCannotBeReinstalledOrQualifyHandoff() throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + transfer.advance(original.source, original.status, deadline()); + String key = capacityKey(tags.assignmentForTransition(fixture.transitionId())); + admin.del(ascii(key)); + String retained = sqlImage(); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(admin.type(ascii(key))).isEqualTo("none"); + assertThat(sqlImage()).isEqualTo(retained); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow() + .executorFence()) + .isEqualTo(original.status.executorFence()); + } + + @Test + void retainedTransferFenceWithTtlCannotQualifyNativeHandoff() throws Exception { + retainedTransferTamperBlocks("ttl"); + } + + @Test + void retainedTransferFenceWrongTypeCannotQualifyNativeHandoff() throws Exception { + retainedTransferTamperBlocks("type"); + } + + @Test + void retainedTransferFenceChangedEnvelopeCannotQualifyNativeHandoff() throws Exception { + retainedTransferTamperBlocks("binding"); + } + + @Test + void chargedTransferRefusesAnOlderRestoredRedisExecutionAtCapacity() throws Exception { + retainedTransferTamperBlocks("restored-authorization"); + } + + @Test + void correctlySignedDifferentStorageGenerationCannotAdoptRetainedTransferReceipts() + throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var attestor = new CanonicalGameplayControlledRegionTransferObservationFixture(); + var originalTransfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), attestor.receiver(repository, tags)); + originalTransfer.advance(original.source, original.status, deadline()); + String retained = sqlImage(); + var changed = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), + CLOCK, + repository, + capacityOwner(), + attestor.receiver(repository, tags, "storage-2")); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + changed, + deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(retained); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow() + .executorFence()) + .isEqualTo(original.status.executorFence()); + } + + @Test + void ordinaryProvisionalHandoffWithoutCapacityExecutionNeedsNoFinalAcknowledgements() + throws Exception { + regionBinding = + CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( + fixture.dsl(), + ownerClient, + ownerUri, + fixture.transitionId(), + sources.request, + sources.resolver, + sources.entity); + var original = regionBinding.installation(); + var before = inventory.readProvisionalCasEvidence(fixture.transitionId()); + assertThat(before.candidate().accountIndexState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry + .IndexState.REPAIR_REQUIRED); + assertThatThrownBy(() -> inventory.readOriginalNewFinalAdmissionSource(decision)) + .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM game_session_original_new_capacity_execution") + .get(0, Long.class)) + .isZero(); + + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); + + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(inventory.readProvisionalCasEvidence(fixture.transitionId())).isEqualTo(before); + assertThatThrownBy(() -> inventory.readOriginalNewFinalAdmissionSource(decision)) + .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM game_session_region_owner_transfer") + .get(0, Long.class)) + .isZero(); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.EnumSource( + CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources.WorldRead.class) + void stalledWorldReadCannotOutliveHandoffDeadline( + CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources.WorldRead + stalledRead) + throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var transferRepository = + new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(transferRepository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, transferRepository, capacityOwner(), receiver); + admin.pexpire(ascii(original.grant.key()), 0); + String beforeSql = sqlImage(); + Map beforeRedis = physicalImage(); + sources.withholdWorldRead = stalledRead; + long started = System.nanoTime(); + long handoffDeadline = CLOCK.millis() + 1500; + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + handoffDeadline)) + .isInstanceOfSatisfying( + io.grpc.StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.DEADLINE_EXCEEDED)); + assertThat(sources.withheldReadEntered.getCount()).isZero(); + assertThat(java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)) + .isLessThan(3500); + assertThat(sqlImage()).isEqualTo(beforeSql); + assertThat(physicalImage()).isEqualTo(beforeRedis); + assertThat( + fixture.dsl().fetchCount(org.jooq.impl.DSL.table("game_session_region_owner_transfer"))) + .isZero(); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(ints = {1, 2}) + void blockedCommittedSelectionOrPreInstallRevalidationCannotOutliveHandoffDeadline( + int blockedRead) throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var ignored = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + // Leave positive SQL retention to the actual transfer, as in the crash-window test. + } + var original = regionBinding.installation(); + var transferRepository = + new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(transferRepository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, transferRepository, capacityOwner(), receiver); + String schema = fixture.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); + var blocked = new java.util.concurrent.atomic.AtomicBoolean(); + var completed = new java.util.concurrent.CountDownLatch(1); + var reads = new java.util.concurrent.atomic.AtomicInteger(); + try (var lock = + java.sql.DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + lock.setSchema(schema); + lock.setAutoCommit(false); + var observer = + new org.jooq.impl.DefaultExecuteListener() { + @Override + public void executeStart(org.jooq.ExecuteContext context) { + String sql = context.sql(); + if (sql == null + || !sql.contains("game_session_canonical_binding_inventory_clock") + || !sql.contains("FOR UPDATE")) return; + // This derived observer belongs only to the successor inventory/status context. + // The independently composed transfer has already retained the positive winner. + String status = + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class); + if (!"COMMITTED".equals(status) || reads.incrementAndGet() != blockedRead) return; + try (var statement = lock.createStatement()) { + statement.setQueryTimeout(2); + statement.execute( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id=1 FOR UPDATE"); + blocked.set(true); + } catch (java.sql.SQLException failure) { + throw new IllegalStateException(failure); + } + } + + @Override + public void exception(org.jooq.ExecuteContext context) { + if (blocked.get()) completed.countDown(); + } + + @Override + public void executeEnd(org.jooq.ExecuteContext context) { + if (blocked.get()) completed.countDown(); + } + }; + var successorSql = + org.jooq.impl.DSL.using( + fixture + .dsl() + .configuration() + .derive(new org.jooq.impl.DefaultExecuteListenerProvider(observer))); + admin.pexpire(ascii(original.grant.key()), 0); + long started = System.nanoTime(); + long handoffDeadline = CLOCK.millis() + 4000; + try { + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + successorSql, + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + handoffDeadline)) + .isInstanceOf(IllegalStateException.class); + assertThat(blocked).as("exact committed inventory read reached").isTrue(); + assertThat(java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)) + .isLessThan(6500); + assertThat(completed.await(2, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } finally { + lock.rollback(); + } + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT executor_fence FROM game_session_region_runtime_status") + .get(0, BigInteger.class)) + .isEqualTo(original.status.executorFence()); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT state FROM game_session_region_owner_transfer") + .get(0, String.class)) + .isEqualTo("FROZEN"); + } + + @Test + void committedHashWithoutCompletePositiveServingProofStillBlocksActualTransfer() + throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var ignored = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + admin.del(ascii(installation.sessionKey())); + } + var original = regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy(this::actualTransferHandoff).isInstanceOf(IllegalStateException.class); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow() + .executorFence()) + .isEqualTo(original.status.executorFence()); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("AUTHORIZED"); + assertThat( + admin.hget( + ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))), + ascii("state"))) + .containsExactly(ascii("COMMITTED")); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void delayedActualPredecessorInstallRefusesAfterNativeHandoffWithinOriginalDeadline() + throws Exception { + delayedPredecessorAfterHandoff(true); + } + + @Test + void delayedActualPredecessorFinalRefusesAfterNativeHandoffWithinOriginalDeadline() + throws Exception { + delayedPredecessorAfterHandoff(false); + } + + @Test + void missingCommittedServingEvidenceCannotReleaseOriginalOwnerCustody() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var actual = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + commitHistoricalSplitReceipt(actual); + } + assertThat(admin.del(ascii(installation.sessionKey()))).isEqualTo(1L); + String rows = sqlImage(); + var physical = physicalImage(); + assertThatThrownBy( + () -> + capacityOwner() + .closeOriginalAttempt( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .retainCommittedBeforeCleanup( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> replaceRegionOwner("successor-with-missing-committed-evidence")) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + } + + @Test + void ownerMovementBeforeCapacityAuthorizationRefusesOriginalDispatchWithoutMutation() + throws Exception { + repairAccountMember(); + bridge(false); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + replaceRegionOwner("successor-before-capacity-dispatch"); + var account = controlledAccountOpen(); + var issuer = issuerOpen(); + String rows = sqlImage(); + var physical = physicalImage(); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var raw = credential.template(); + var bound = raw.bindCapacityExecution(controlledCapacity)) { + assertThatThrownBy( + () -> + capacityOwner() + .authorize(source, bound, account, issuer, controlledCapacity, deadline())) + .isInstanceOf(IllegalStateException.class); + } + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + } + + @Test + void unresolvedOriginalExecutionBlocksOwnerMovementUntilExactClosure() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + admin.pexpire(ascii(regionBinding.installation().grant.key()), 0); + String rows = sqlImage(); + var physical = physicalImage(); + assertThatThrownBy( + () -> + regionBinding + .owner() + .revalidateOriginalNewFinalBinding(regionBinding.installation(), source)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> replaceRegionOwner("successor-before-closure")) + .isInstanceOf(IllegalStateException.class); + // The positive continuation cannot turn an unexecuted/missing final result into proof. + assertThatThrownBy( + () -> + capacityOwner() + .retainCommittedBeforeCleanup( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + capacityOwner() + .closeOriginalAttempt(controlledCapacity.request(), controlledCapacity.reservation()); + var successor = replaceRegionOwner("successor-after-closure"); + assertThat(successor.executorFence().longValueExact()) + .isGreaterThan(controlledCapacity.selectedOwnerFence()); + assertThat( + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation()) + .disposition()) + .isEqualTo("NOT_EXECUTED_AFTER_AUTHORIZATION"); + } + + private void retainedTransferTamperBlocks(String fault) throws Exception { + repairAccountMember(); + bridge(true, 1, 1_048_576L); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + byte[] key = ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))); + byte[] beforeFence = admin.dump(key); + transfer.advance(original.source, original.status, deadline()); + if (fault.equals("ttl")) admin.pexpire(key, 10000); + else if (fault.equals("type")) { + byte[][] keysToDelete = {key}; + admin.del(keysToDelete); + admin.set(key, ascii("wrong-type")); + } else if (fault.equals("restored-authorization")) { + assertThat(beforeFence).isNotNull(); + assertThat(admin.hget(key, ascii("state"))).containsExactly(ascii("FENCED_INDETERMINATE")); + admin.restore(key, beforeFence, RestoreArgs.Builder.ttl(0L).replace()); + assertThat(admin.hget(key, ascii("state"))).containsExactly(ascii("AUTHORIZED")); + } else admin.hset(key, ascii("binding"), ascii("{}")); + byte[] physical = + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key); + String retained = sqlImage(); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) + .containsExactly(physical); + assertThat(sqlImage()).isEqualTo(retained); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow() + .executorFence()) + .isEqualTo(original.status.executorFence()); + } + + private static java.sql.Connection failDispatchCommitReplyAfterMarker( + java.sql.Connection actual, + javax.sql.DataSource independentDataSource, + String executionDigest, + java.util.concurrent.atomic.AtomicBoolean stopped) + throws java.sql.SQLException { + try { + return (java.sql.Connection) + java.lang.reflect.Proxy.newProxyInstance( + java.sql.Connection.class.getClassLoader(), + new Class[] {java.sql.Connection.class}, + (proxy, method, values) -> { + Object result; + try { + result = method.invoke(actual, values); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + if (method.getName().equals("commit") && !stopped.get()) { + try (var independent = independentDataSource.getConnection(); + var check = + independent.prepareStatement( + "SELECT status FROM game_session_original_new_capacity_execution" + + " WHERE execution_digest=?")) { + check.setString(1, executionDigest); + try (var rows = check.executeQuery()) { + if (rows.next() + && "INSTALL_DISPATCHED".equals(rows.getString(1)) + && stopped.compareAndSet(false, true)) { + throw new java.sql.SQLException( + "Controlled lost INSTALL_DISPATCHED commit reply"); + } + } + } + } + return result; + }); + } catch (RuntimeException | Error failure) { + try { + actual.close(); + } catch (java.sql.SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; + } + } + + private void delayedPredecessorAfterHandoff(boolean installAction) throws Exception { + repairAccountMember(); + bridge(!installAction); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + String oldSha = + admin.scriptLoad( + CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest + .predecessorLuaForOwnerProof()); + var entered = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + var calls = new java.util.concurrent.atomic.AtomicInteger(); + var redisReply = new java.util.concurrent.CompletableFuture(); + var dispatchedAt = new java.util.concurrent.atomic.AtomicLong(); + String action = installAction ? "INSTALL" : "FINAL"; + RedisClient delayed = mock(RedisClient.class); + when(delayed.connect(ByteArrayCodec.INSTANCE)) + .thenAnswer( + ignored -> + delayedConnection( + ownerClient.connect(ByteArrayCodec.INSTANCE), + oldSha, + action, + entered, + release, + calls, + redisReply, + dispatchedAt)); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var raw = credential.template(); + var template = raw.bindCapacityExecution(controlledCapacity)) { + var account = controlledAccountOpen(); + var issuer = issuerOpen(); + long frozenDeadline = CLOCK.millis() + 5000L; + var old = + java.util.concurrent.CompletableFuture.runAsync( + () -> { + if (installAction) { + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + fixture.dsl(), delayed, catalog, CLOCK, tags) + .authorize( + source, template, account, issuer, controlledCapacity, frozenDeadline); + } else { + var owner = + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + delayed, + catalog, + CLOCK, + tags, + () -> delayed.connect(ByteArrayCodec.INSTANCE), + () -> frozenDeadline - CLOCK.millis(), + java.util.concurrent.CompletableFuture::join); + try (var ignored = + owner.finalizeOriginalNewOnce( + source, template, account, issuer, controlledCapacity, frozenDeadline)) { + throw new AssertionError( + "Delayed old FINAL must not produce an admission receipt"); + } + } + }); + try { + assertThat(entered.await(3, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + var original = regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()), 0); + var successor = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + ownerUri, + catalog, + original, + sources.resolver, + transfer, + frozenDeadline); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(CLOCK.millis()).isLessThan(frozenDeadline); + var fencedPhysical = physicalImage(); + release.countDown(); + assertThat(redisReply.get(2, java.util.concurrent.TimeUnit.SECONDS)).isEqualTo(-1L); + assertThat(dispatchedAt.get()).isPositive().isLessThan(frozenDeadline); + assertThat(CLOCK.millis()).isLessThan(frozenDeadline); + assertThatThrownBy(() -> old.get(2, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class); + assertThat(calls.get()).isOne(); + assertThat(physicalImage()).isEqualTo(fencedPhysical); + assertThat(admin.get(ascii(installation.sessionKey()))) + .containsExactly(source.candidate().canonicalBytes()); + assertThat( + admin.hget( + ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))), + ascii("state"))) + .containsExactly(ascii("FENCED_INDETERMINATE")); + } finally { + release.countDown(); + try { + old.get(5, java.util.concurrent.TimeUnit.SECONDS); + } catch (java.util.concurrent.ExecutionException expected) { + /* already asserted failure */ + } + } + } + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection delayedConnection( + StatefulRedisConnection actual, + String predecessorSha, + String action, + java.util.concurrent.CountDownLatch entered, + java.util.concurrent.CountDownLatch release, + java.util.concurrent.atomic.AtomicInteger calls, + java.util.concurrent.CompletableFuture redisReply, + java.util.concurrent.atomic.AtomicLong dispatchedAt) { + var commands = actual.async(); + Object delayedCommands = + java.lang.reflect.Proxy.newProxyInstance( + io.lettuce.core.api.async.RedisAsyncCommands.class.getClassLoader(), + new Class[] {io.lettuce.core.api.async.RedisAsyncCommands.class}, + (proxy, method, args) -> { + if (method.getName().equals("evalsha") + && args.length == 4 + && args[3] instanceof byte[][] values + && values.length == 19 + && action.equals(new String(values[17], StandardCharsets.US_ASCII))) { + entered.countDown(); + if (!release.await(10, java.util.concurrent.TimeUnit.SECONDS)) + throw new AssertionError("Delayed old invocation not released to Redis"); + Object[] original = args.clone(); + original[0] = predecessorSha; + try { + dispatchedAt.set(CLOCK.millis()); + var reply = (io.lettuce.core.RedisFuture) method.invoke(commands, original); + calls.incrementAndGet(); + reply.whenComplete( + (value, failure) -> { + if (failure == null) redisReply.complete(value); + else redisReply.completeExceptionally(failure); + }); + return reply; + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + } + try { + return method.invoke(commands, args); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + return (StatefulRedisConnection) + java.lang.reflect.Proxy.newProxyInstance( + StatefulRedisConnection.class.getClassLoader(), + new Class[] {StatefulRedisConnection.class}, + (proxy, method, args) -> { + if (method.getName().equals("async")) return delayedCommands; + try { + return method.invoke(actual, args); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 2333147f15..4b453a1cfd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -36,6 +36,7 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -142,7 +143,50 @@ static void certificates() throws Exception { } @Test - void composesInitialLeaseAndHoldsReplacementAcrossSourceChanges() throws Exception { + void transferInstallationIncarnationReadReturnsByFrozenDeadlineWhenSourceStalls() + throws Exception { + WorldFixture world = WorldFixture.open(); + var blockedSource = new BlockingStableIncarnationSource(); + var owner = + new CanonicalGameplayRegionLeaseOwner( + mock(CanonicalGameplayBindingInventoryRepository.class), + mock(CanonicalGameplayRegionRuntimeStatusRepository.class), + mock(CanonicalGameplayRegionLeaseRedisOwner.class), + blockedSource, + world.resolver(), + new RuntimeIdentity( + "game-session-service", + "stalled-incarnation", + "localhost", + Instant.now(), + "controlled-test", + "controlled-sha", + "controlled-image"), + Duration.ofSeconds(30), + Clock.systemUTC()); + var source = source(world.originalEvidence()); + long deadline = System.currentTimeMillis() + 300L; + var transferOwner = mock(CanonicalGameplayRegionOwnerTransferCoordinator.class); + long startedAt = System.nanoTime(); + CompletableFuture read = + CompletableFuture.supplyAsync( + () -> owner.readInstallationIncarnation(transferOwner, deadline, source)); + + try { + assertThat(blockedSource.entered.await(2, TimeUnit.SECONDS)).isTrue(); + Throwable failure = catchThrowable(() -> read.get(2, TimeUnit.SECONDS)); + long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt); + assertThat(failure).isInstanceOf(java.util.concurrent.ExecutionException.class); + assertThat(failure.getCause()) + .hasMessage("Original NEW capacity execution budget is unavailable"); + assertThat(elapsedMillis).isLessThan(2_000L); + } finally { + blockedSource.release.countDown(); + } + } + + @Test + void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); ControlledConnectionFailureDataSource dataSource = dataSource(); CanonicalGameplayIssuerTestFixtures.migrationConfiguration( @@ -379,48 +423,31 @@ void composesInitialLeaseAndHoldsReplacementAcrossSourceChanges() throws Excepti assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); assertThat(redis.admin().persist(ascii(initialMetaKey))).isTrue(); - var reused = - firstOwner.installForTransition(firstInstallation, TRANSITION_ID, world.request()); - assertThat(reused.status).isEqualTo(firstStatus); - assertThat(reused.grant).isSameAs(firstInstallation.grant); - assertThat(fenceSequenceValue(dsl)).isEqualTo(sequenceAfterInstall); - - incarnationSource.changeStorageGeneration("storage-generation-2"); - assertThatThrownBy( - () -> firstOwner.installForTransition(reused, TRANSITION_ID, world.request())) + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(firstInstallation)) .isInstanceOf(IllegalStateException.class); - incarnationSource.restoreStorageGeneration(); - - WorldCanonicalInstanceLifecycleEvidence changed = changedEvidence(world.originalEvidence()); - for (int read : new int[] {2, 3}) { - world.replaceOnRead(read, changed); - assertThatThrownBy( - () -> firstOwner.installForTransition(reused, TRANSITION_ID, world.request())) - .isInstanceOf(IllegalStateException.class); - assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); - assertThat(fenceSequenceValue(dsl)).isEqualTo(sequenceAfterInstall); - assertThat(redis.admin().get(redisKey)).containsExactly(initialLeaseValue); - } - - world.setAfterRead(2, dataSource::failConnections); - Throwable sqlOutageFailure; - try { - sqlOutageFailure = - catchThrowable( - () -> firstOwner.installForTransition(reused, TRANSITION_ID, world.request())); - } finally { - dataSource.restoreConnections(); - world.resetReads(); - } - assertThat(sqlOutageFailure) - .isInstanceOf(RuntimeException.class) - .hasRootCauseInstanceOf(SQLException.class); assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); - assertThat(fenceSequenceValue(dsl)).isEqualTo(sequenceAfterInstall); - assertThat(redis.admin().get(redisKey)).containsExactly(initialLeaseValue); - assertThat(redis.admin().pttl(redisKey)).isPositive(); - var contender = + dsl.execute( + "UPDATE game_session_region_runtime_status" + + " SET last_committed_tick_batch_id = 'batch-0', last_committed_tick_id = 0" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId()); + redis + .admin() + .hset( + ascii( + CanonicalGameplayRegionRedisKeys.meta( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId())), + java.util.Map.of( + ascii("current_tick_id"), ascii("0"), + ascii("current_tick_state"), ascii("APPLIED"), + ascii("current_tick_terminal_at_ms"), ascii("1792972800000"))); + var secondOwner = owner( bindingInventory, statusRepository, @@ -428,14 +455,16 @@ void composesInitialLeaseAndHoldsReplacementAcrossSourceChanges() throws Excepti world, "instance-b", incarnationSource); - assertThatThrownBy(() -> contender.installForTransition(TRANSITION_ID, world.request())) - .isInstanceOf(IllegalStateException.class); - assertThat(redis.admin().get(redisKey)).containsExactly(initialLeaseValue); - assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); - - assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); - assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(reused)) + secondOwner.installForTransition(TRANSITION_ID, world.request()); + var secondStatus = statusRepository.find(qualifiedSource).orElseThrow(); + assertThat(secondStatus.executorFence()).isGreaterThan(firstStatus.executorFence()); + assertThat(secondStatus.regionEpoch()).isEqualTo(firstStatus.regionEpoch()); + assertThat(secondStatus.lastCommittedTickId()).isZero(); + assertThat(secondStatus.lastCommittedTickBatchId()).isEqualTo("batch-0"); + assertThat(secondStatus.ownerInstanceId()).isEqualTo("instance-b"); + assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(firstInstallation)) .isInstanceOf(IllegalStateException.class); + assertThat(statusRepository.find(qualifiedSource)).contains(secondStatus); dsl.execute( "UPDATE game_session_region_runtime_status" @@ -447,24 +476,109 @@ void composesInitialLeaseAndHoldsReplacementAcrossSourceChanges() throws Excepti redis .admin() .hset( - ascii(initialMetaKey), + ascii( + CanonicalGameplayRegionRedisKeys.meta( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId())), java.util.Map.of( ascii("current_tick_id"), ascii("8"), ascii("current_tick_state"), ascii("APPLIED"), ascii("current_tick_terminal_at_ms"), ascii("1792972800000"))); var progressed = statusRepository.find(qualifiedSource).orElseThrow(); - var timelineBeforeReplacement = redis.admin().dump(ascii(initialMetaKey)); - assertThat(progressed.executorFence()).isEqualTo(firstStatus.executorFence()); - assertThat(progressed.lastCommittedTickId()).isEqualTo(8L); - assertThat(progressed.lastCommittedTickBatchId()).isEqualTo("batch-8"); - assertThatThrownBy(() -> contender.installForTransition(TRANSITION_ID, world.request())) + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + + var thirdOwner = + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-c", + incarnationSource); + var thirdInstallation = thirdOwner.installForTransition(TRANSITION_ID, world.request()); + var thirdStatus = statusRepository.find(qualifiedSource).orElseThrow(); + assertThat(thirdStatus.executorFence()).isGreaterThan(progressed.executorFence()); + assertThat(thirdStatus.regionEpoch()).isEqualTo(1L); + assertThat(thirdStatus.lastCommittedTickId()).isEqualTo(8L); + assertThat(thirdStatus.lastCommittedTickBatchId()).isEqualTo("batch-8"); + assertThat(thirdStatus.ownerInstanceId()).isEqualTo("instance-c"); + assertThat(thirdInstallation).isNotNull(); + + byte[] liveLeaseBeforeIncarnationChange = redis.admin().get(redisKey); + Long fenceBeforeIncarnationChange = fenceSequenceValue(dsl); + incarnationSource.changeStorageGeneration("storage-generation-2"); + var changedIncarnationOwner = + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "changed-incarnation", + incarnationSource); + assertThatThrownBy( + () -> changedIncarnationOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); - assertThat(statusRepository.find(qualifiedSource)).contains(progressed); - assertThat(fenceSequenceValue(dsl)).isEqualTo(sequenceAfterInstall); - assertThat(redis.admin().type(redisKey)).isEqualTo("none"); - assertThat(redis.admin().dump(ascii(initialMetaKey))) - .containsExactly(timelineBeforeReplacement); - assertThat(redis.admin().pttl(ascii(initialMetaKey))).isEqualTo(-1L); + assertThat(redis.admin().get(redisKey)).containsExactly(liveLeaseBeforeIncarnationChange); + assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); + assertThat(fenceSequenceValue(dsl)).isEqualTo(fenceBeforeIncarnationChange); + incarnationSource.restoreStorageGeneration(); + + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + WorldCanonicalInstanceLifecycleEvidence changed = changedEvidence(world.originalEvidence()); + world.replaceOnRead(2, changed); + var fourthOwner = + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-d", + incarnationSource); + assertThatThrownBy(() -> fourthOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); + + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + world.resetReads(); + world.replaceOnRead(3, changed); + var fifthOwner = + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-e", + incarnationSource); + assertThatThrownBy(() -> fifthOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + var installedBeforeChangedSourceGate = statusRepository.find(qualifiedSource).orElseThrow(); + assertThat(installedBeforeChangedSourceGate.executorFence()) + .isGreaterThan(thirdStatus.executorFence()); + assertThat(installedBeforeChangedSourceGate.lastCommittedTickId()).isEqualTo(8L); + assertThat(installedBeforeChangedSourceGate.ownerInstanceId()).isEqualTo("instance-e"); + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + + world.resetReads(); + var ownerStatusBeforeSqlOutage = statusRepository.find(qualifiedSource).orElseThrow(); + world.setAfterRead(2, dataSource::failConnections); + var sixthOwner = + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-f", + incarnationSource); + Throwable sqlOutageFailure = + catchThrowable(() -> sixthOwner.installForTransition(TRANSITION_ID, world.request())); + dataSource.restoreConnections(); + assertThat(sqlOutageFailure) + .isInstanceOf(RuntimeException.class) + .hasRootCauseInstanceOf(SQLException.class); + assertThat(statusRepository.find(qualifiedSource)).contains(ownerStatusBeforeSqlOutage); + assertThat(redis.admin().type(redisKey)).isEqualTo("string"); + assertThat(redis.admin().pttl(redisKey)).isPositive(); } } @@ -511,6 +625,85 @@ void boundedTimelineCreationRejectsExpiryAndCapsNewLease() throws Exception { } } + @Test + void preparedTimelineIncarnationReadReusesPermitWhenBothBackgroundSlotsAreHeld() + throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try { + try (RedisFixture redis = RedisFixture.open()) { + var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var redisOwner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.clientUri(PRINCIPAL, PASSWORD), redis.catalog()); + WorldFixture world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var bindingEvidence = provisionalEvidence(world.request()); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + statusRepository.prepareInitialTimeline( + bindingEvidence, + world.request(), + world.resolver().resolve(world.request()), + source, + incarnation, + redisOwner.requireTimelineAbsent(source, incarnation), + NOW); + long deadline = System.currentTimeMillis() + 10_000L; + var deadlineBoundRedisOwner = redisOwner.forHandoffDeadline(Clock.systemUTC(), deadline); + RuntimeIdentity identity = + new RuntimeIdentity( + "game-session-service", + "overlapping-timeline-preparation", + "localhost", + NOW, + "controlled-test", + "controlled-sha", + "controlled-image"); + var bindingInventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + + try (CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization first = + deadlineBoundRedisOwner.prepareTimelineInitialization( + preparation, Duration.ofSeconds(30), identity); + CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization second = + deadlineBoundRedisOwner.prepareTimelineInitialization( + preparation, Duration.ofSeconds(30), identity)) { + var claim = + first.runWithinRetainedPermit( + retainedBudget -> { + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + Clock.systemUTC(), deadline, ignored -> true)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> first.runWithinRetainedPermit(ignored -> null)) + .isInstanceOf(IllegalStateException.class); + assertThat( + bindingInventory.withinTransferRead( + retainedBudget, + CanonicalGameplayBindingInventoryRepository::readSnapshot)) + .isNotNull(); + assertThat( + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source))) + .isEqualTo(incarnation); + return new CanonicalGameplayRegionRuntimeStatusRepository( + retainedBudget.sql(testSchema.dsl())) + .beginInitialTimeline(preparation, NOW); + }); + assertThat(claim) + .hasValueSatisfying( + permit -> assertThat(permit.operationId()).isEqualTo(preparation.operationId())); + } + } + } finally { + dropSchema(testSchema.schema()); + } + } + @Test void timelinePreflightFailuresLeavePreparedPermissionAndAllowLaterFirstClaim() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); @@ -951,6 +1144,48 @@ void accountMemberAcknowledgementAfterRegionBridgePreservesOriginalBridgeEvidenc } } + @Test + void acknowledgedRegionBridgeSurvivesExpiredGrantReplacement() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try { + try (RedisFixture redis = RedisFixture.open()) { + redis.admin().flushdb(); + } + // This local candidate-launch source is created through the real Game Session owners; + // its upstream publication inputs remain controlled test evidence. + var runtimeTarget = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + testSchema.dataSource(), UUID.randomUUID(), "firemud"); + WorldFixture world = WorldFixture.open(runtimeTarget); + try (var entitySource = EntityReferenceFixture.open()) { + CanonicalGameplayRegionOwnerCompositionFixture.ChangedGrantProof proof = + CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeThenChangedGrantRefuses( + testSchema.dsl(), + REDIS.getHost(), + REDIS.getMappedPort(REDIS_PORT), + world.request(), + runtimeTarget.playableTarget(), + world.resolver(), + entitySource.client()); + + assertThat(proof.acknowledgedBridge().exactLostReplyRetry()).isTrue(); + assertThat(proof.replacementGrantInstalled()).isTrue(); + assertThat(proof.replacementExecutorFence()) + .isGreaterThan(proof.acknowledgedBridge().executorFence()); + assertThat(proof.bridgeRefused()).isTrue(); + assertThat(proof.refusalMessage()) + .isEqualTo( + "A completed region bridge acknowledgement cannot be rewritten for a new grant"); + assertThat(proof.acknowledgementRowPreserved()).isTrue(); + assertThat(proof.inventoryStatePreserved()).isTrue(); + assertThat(proof.physicalBridgeStatePreserved()).isTrue(); + } + } finally { + dropSchema(testSchema.schema()); + } + } + @Test void retainedParentRegionBridgeUpgradePreservesRowsHistoryAndMigrationRetry() throws Exception { assertRetainedParentRegionBridgeUpgrade(false); @@ -1301,7 +1536,7 @@ void createdOriginNativeBridgeRetainsOriginalPurposeAndRejectsSourceSubstitution } @Test - void laterPlacementReusesCurrentGrantWithoutChangingInitialTimeline() throws Exception { + void laterPlacementAcquiresFreshGrantWithoutChangingInitialTimeline() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); TestSchema schema = newTestSchema(); try { @@ -1348,10 +1583,7 @@ void laterPlacementReusesCurrentGrantWithoutChangingInitialTimeline() throws Exc .thenAnswer(ignored -> first.original.preparationInputDigest()); when(secondEvidence.operationalRegionAssignments()) .thenAnswer(ignored -> first.original.operationalRegionAssignments()); - var secondResponse = regionResponse(secondRequest, secondEvidence); - when(first.initialClient.readInitialPlayerLocationRegion(secondRequest)) - .thenReturn(secondResponse); - when(first.lifecycleClient.read(secondLifecycle)).thenReturn(secondEvidence); + var second = new WorldFixture(secondEvidence, secondRequest); assertThat(secondLifecycle.readRequestId()).isNotEqualTo(original.readRequestId()); try (var entity = EntityReferenceFixture.open(secondRequest.getCharacterUuid())) { var result = @@ -1364,12 +1596,16 @@ void laterPlacementReusesCurrentGrantWithoutChangingInitialTimeline() throws Exc first.resolver(), entity.client(), new CanonicalGameplayRegionOwnerCompositionFixture.SecondBinding( - secondRequest, target.playableTarget(), first.resolver(), entity.client())); + second.request(), + target.playableTarget(), + second.resolver(), + entity.client(), + true)); assertThat(result.firstTimelineUnchanged()).isTrue(); assertThat(result.initialMetaUnchanged()).isTrue(); assertThat(result.first().exactLostReplyRetry()).isTrue(); assertThat(result.second().exactLostReplyRetry()).isTrue(); - assertThat(result.second().executorFence()).isEqualTo(result.first().executorFence()); + assertThat(result.second().executorFence()).isGreaterThan(result.first().executorFence()); assertThat(result.foreignOwnerCapabilityRejectedWithoutStateChange()).isTrue(); assertThat(result.expiredGrantRejectedWithoutStateChange()).isTrue(); } @@ -1594,6 +1830,25 @@ synchronized void restoreRecoveryEvidence() { } } + private static final class BlockingStableIncarnationSource + implements CanonicalGameplayRegionIncarnationSource { + private final CountDownLatch entered = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + + @Override + public CanonicalGameplayRegionIncarnationSource.StableEvidence readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope scope) { + entered.countDown(); + try { + release.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Controlled incarnation read was interrupted", interrupted); + } + return stableIncarnation(scope, "storage-generation-1"); + } + } + private static CanonicalGameplayRegionLeaseOwner owner( CanonicalGameplayBindingInventoryRepository bindingInventory, CanonicalGameplayRegionRuntimeStatusRepository statusRepository, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index 7ca8c08861..db4e5551c5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -30,6 +30,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; @@ -51,6 +52,7 @@ import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRuntimeReferenceClient; import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; @@ -118,6 +120,65 @@ record ExistingBinding( CanonicalGameplayRegionLeaseOwner.Installation installation, CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement acknowledgement) {} + /** + * Actual acquire/install/revalidate path; only upstream placement/incarnation remain controlled. + */ + static CanonicalGameplayRegionLeaseOwner.Installation handoffExistingOriginal( + DSLContext dsl, + RedisClient coordinationRedis, + RedisURI coordinationUri, + RedisScriptCatalog catalog, + CanonicalGameplayRegionLeaseOwner.Installation original, + CanonicalInitialPlayerLocationRegionResolver resolver, + CanonicalGameplayRegionOwnerTransferCoordinator transfer, + long deadline) { + return handoffExistingOriginal( + dsl, + coordinationRedis, + coordinationUri, + catalog, + original, + resolver, + new ControlledStableIncarnationSource(), + transfer, + deadline); + } + + /** Rechecks the same explicit current incarnation source used by the original installation. */ + static CanonicalGameplayRegionLeaseOwner.Installation handoffExistingOriginal( + DSLContext dsl, + RedisClient coordinationRedis, + RedisURI coordinationUri, + RedisScriptCatalog catalog, + CanonicalGameplayRegionLeaseOwner.Installation original, + CanonicalInitialPlayerLocationRegionResolver resolver, + CanonicalGameplayRegionIncarnationSource incarnationSource, + CanonicalGameplayRegionOwnerTransferCoordinator transfer, + long deadline) { + var identity = + new RuntimeIdentity( + "game-session-service", + "final-owner-handoff", + "localhost", + Instant.now(), + "test", + "test", + "controlled-test-image"); + var successor = + CanonicalGameplayRegionLeaseOwnerFactory.compose( + dsl, + coordinationRedis, + coordinationUri, + catalog, + incarnationSource, + resolver, + identity, + Duration.ofSeconds(30), + Clock.systemUTC()); + return successor.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline); + } + /** * Creates one real first-NEW provisional candidate from the exact placement selector, installs * the first region timeline and SQL fence, then retries the same binding bridge as a lost reply. @@ -512,6 +573,7 @@ static Proof installAndBridgeWithSqlPhaseRunner( null, null, null, + null, Objects.requireNonNull(phaseRunner, "phaseRunner")) .first(); } @@ -541,6 +603,7 @@ static Proof installCreatedAndBridgeThenCheckSources( worldRegionResolver, entityReferenceClient, null, + null, createdReferenceClient, binding -> { try (var redis = RegionRedis.open(redisHost, redisPort)) { @@ -592,6 +655,30 @@ private static List createdBridgeState( physical); } + /** Reacquires a real region grant after the bridge ACK and proves that the ACK remains closed. */ + public static ChangedGrantProof installAndBridgeThenChangedGrantRefuses( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) + throws Exception { + var capture = new AtomicReference(); + installAndBridgeInternal( + dsl, + redisHost, + redisPort, + worldRequest, + currentTarget, + worldRegionResolver, + entityReferenceClient, + null, + capture); + return Objects.requireNonNull(capture.get(), "changed-grant bridge proof"); + } + /** * Runs the physical region bridge first, then the actual Account-member repair owner and retry. */ @@ -914,6 +1001,30 @@ private static TwoBindingProof installAndBridgeInternal( worldRegionResolver, entityReferenceClient, secondBinding, + null); + } + + private static TwoBindingProof installAndBridgeInternal( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + SecondBinding secondBinding, + AtomicReference changedGrantProofCapture) + throws Exception { + return installAndBridgeInternal( + dsl, + redisHost, + redisPort, + worldRequest, + currentTarget, + worldRegionResolver, + entityReferenceClient, + secondBinding, + changedGrantProofCapture, null, null, null); @@ -928,6 +1039,7 @@ private static TwoBindingProof installAndBridgeInternal( CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, SecondBinding secondBinding, + AtomicReference changedGrantProofCapture, CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient, java.util.function.Consumer afterBridge, BridgeSqlPhaseRunner phaseRunner) @@ -1070,6 +1182,20 @@ private static TwoBindingProof installAndBridgeInternal( afterBridge.accept(new ExistingBinding(bridgeOwner, installation, firstAcknowledgement)); } if (secondBinding == null) { + if (changedGrantProofCapture != null) { + changedGrantProofCapture.set( + reacquireGrantAfterAcknowledgement( + dsl, + redis, + scriptCatalog, + stableSource, + worldRegionResolver, + bridgeEntityReferenceClient, + worldRequest, + firstProof, + installation, + status)); + } return new TwoBindingProof(firstProof, null, null, true, true, true, true, true); } @@ -1145,11 +1271,33 @@ private static TwoBindingProof installAndBridgeInternal( secondPrepared.bindingGeneration(), null, secondBinding.currentTarget())); - var secondInstallation = - bridgeOwner.installForTransition( - installation, secondTransitionId, secondBinding.worldRequest()); - var secondAcknowledgement = bridgeOwner.bridge(secondInstallation).obligation(); - var secondLostReplyRetry = bridgeOwner.bridge(secondInstallation).obligation(); + CanonicalGameplayRegionLeaseOwner.Installation secondInstallation; + CanonicalGameplayRegionBindingBridgeOwner secondBridgeOwner = bridgeOwner; + if (secondBinding.freshGrant()) { + // The first private handle is deliberately not reused. Expire only this test-owned lease. + redis.admin().pexpire(redisKey, 0L); + secondBridgeOwner = + CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( + dsl, + redis.ownerClient(), + redis.ownerUri, + scriptCatalog, + stableSource, + secondBinding.worldRegionResolver(), + secondBinding.entityReferenceClient(), + runtimeIdentity, + Duration.ofSeconds(30), + Clock.systemUTC()); + secondInstallation = + secondBridgeOwner.installForTransition( + secondTransitionId, secondBinding.worldRequest()); + } else { + secondInstallation = + bridgeOwner.installForTransition( + installation, secondTransitionId, secondBinding.worldRequest()); + } + var secondAcknowledgement = secondBridgeOwner.bridge(secondInstallation).obligation(); + var secondLostReplyRetry = secondBridgeOwner.bridge(secondInstallation).obligation(); requireMaterializedBridgeCaptured(dsl, secondTransitionId); if (!secondAcknowledgement.equals(secondLostReplyRetry) || secondAcknowledgement.status() @@ -1234,8 +1382,10 @@ private static TwoBindingProof installAndBridgeInternal( && secondStatus.lastCommittedTickId() == -1L; if (!unchangedTimeline || !preparationGrantMatchesCurrent - || !status.leaseTokenCorrelation().equals(secondStatus.leaseTokenCorrelation()) - || !status.executorFence().equals(secondStatus.executorFence()) + || (secondBinding.freshGrant() + ? status.leaseTokenCorrelation().equals(secondStatus.leaseTokenCorrelation()) + || secondStatus.executorFence().compareTo(status.executorFence()) <= 0 + : !status.leaseTokenCorrelation().equals(secondStatus.leaseTokenCorrelation())) || redis.admin().pttl(redisKey) <= 0L || redis.admin().pttl(ascii(initialMetaKey)) != -1L) { throw new IllegalStateException( @@ -1294,7 +1444,7 @@ private static TwoBindingProof installAndBridgeInternal( snapshotRegionRedisState(redis, redisKey, initialMetaKey); boolean expiredGrantInstallationRejected; try { - bridgeOwner.installForTransition( + secondBridgeOwner.installForTransition( secondInstallation, secondTransitionId, secondBinding.worldRequest()); expiredGrantInstallationRejected = false; } catch (IllegalStateException expected) { @@ -1359,6 +1509,121 @@ public T run( }; } + private static ChangedGrantProof reacquireGrantAfterAcknowledgement( + DSLContext dsl, + RegionRedis redis, + RedisScriptCatalog scriptCatalog, + ControlledStableIncarnationSource stableSource, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + CanonicalInitialPlayerLocationRequest worldRequest, + Proof acknowledged, + CanonicalGameplayRegionLeaseOwner.Installation originalInstallation, + CanonicalGameplayRegionRuntimeStatus originalStatus) { + String acknowledgedRowBeforeGrant = regionBridgeRowImage(dsl, acknowledged.transitionId()); + byte[] leaseKey = + ascii( + CanonicalGameplayRegionRedisKeys.lease( + originalInstallation.source.tenantId(), + originalInstallation.source.gameInstanceId(), + originalInstallation.source.regionId())); + if (!redis.admin().pexpire(leaseKey, 0L)) { + throw new IllegalStateException("The acknowledged bridge grant could not be expired"); + } + + RuntimeIdentity replacementIdentity = + new RuntimeIdentity( + "game-session-service", + "region-owner-composition-replacement", + "localhost", + Instant.now(), + "test", + "test", + "controlled-test-image"); + var replacementOwner = + CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( + dsl, + redis.ownerClient(), + redis.ownerUri, + scriptCatalog, + stableSource, + worldRegionResolver, + entityReferenceClient, + replacementIdentity, + Duration.ofSeconds(30), + Clock.systemUTC()); + var replacementInstallation = + replacementOwner.installForTransition(acknowledged.transitionId(), worldRequest); + CanonicalGameplayRegionRuntimeStatus replacementStatus = + new CanonicalGameplayRegionRuntimeStatusRepository(dsl) + .find(originalInstallation.source) + .orElseThrow(); + + String acknowledgedRowBeforeRefusal = regionBridgeRowImage(dsl, acknowledged.transitionId()); + Record acknowledgedRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE transition_id = ?", + acknowledged.transitionId()), + "acknowledged bridge row after grant replacement"); + RegionBridgeRedisState physicalBridgeBeforeRefusal = + snapshotRegionBridgeRedisState(redis, acknowledgedRow, acknowledged.runtimeEntityId()); + var inventoryBeforeRefusal = + new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot(); + + boolean bridgeRefused; + String refusalMessage; + try { + replacementOwner.bridge(replacementInstallation); + bridgeRefused = false; + refusalMessage = null; + } catch (CanonicalGameplayBindingInventoryConflictException expected) { + bridgeRefused = true; + refusalMessage = expected.getMessage(); + } + + String acknowledgedRowAfterRefusal = regionBridgeRowImage(dsl, acknowledged.transitionId()); + var acknowledgedRowAfter = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE transition_id = ?", + acknowledged.transitionId()), + "acknowledged bridge row after changed-grant bridge refusal"); + RegionBridgeRedisState physicalBridgeAfterRefusal = + snapshotRegionBridgeRedisState(redis, acknowledgedRowAfter, acknowledged.runtimeEntityId()); + var inventoryAfterRefusal = new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot(); + boolean replacementGrantInstalled = + replacementStatus.executorFence().compareTo(acknowledged.executorFence()) > 0 + && !originalStatus + .leaseTokenCorrelation() + .equals(replacementStatus.leaseTokenCorrelation()) + && "region-owner-composition-replacement".equals(replacementStatus.ownerInstanceId()); + return new ChangedGrantProof( + acknowledged, + replacementStatus.executorFence(), + replacementGrantInstalled, + bridgeRefused, + refusalMessage, + acknowledgedRowBeforeGrant.equals(acknowledgedRowBeforeRefusal) + && acknowledgedRowBeforeRefusal.equals(acknowledgedRowAfterRefusal), + inventoryBeforeRefusal.equals(inventoryAfterRefusal), + physicalBridgeBeforeRefusal.equals(physicalBridgeAfterRefusal)); + } + + private static String regionBridgeRowImage(DSLContext dsl, UUID transitionId) { + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(obligation)::text AS image" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " WHERE transition_id = ?", + transitionId), + "persisted region bridge obligation image"); + return Objects.requireNonNull(row.get("image", String.class), "region bridge row image"); + } + private static boolean sameAbortSource( CanonicalGameplayAdmissionAbortSource expected, CanonicalGameplayAdmissionAbortSource actual) { @@ -1934,7 +2199,16 @@ public record SecondBinding( CanonicalInitialPlayerLocationRequest worldRequest, CanonicalPlayableTarget currentTarget, CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, - CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) {} + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + boolean freshGrant) { + public SecondBinding( + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) { + this(worldRequest, currentTarget, worldRegionResolver, entityReferenceClient, false); + } + } public record TwoBindingProof( Proof first, @@ -1964,6 +2238,16 @@ public record MemberRepairProof( boolean accountControlStatePreserved, boolean exactMemberRetryPreservedState) {} + public record ChangedGrantProof( + Proof acknowledgedBridge, + BigInteger replacementExecutorFence, + boolean replacementGrantInstalled, + boolean bridgeRefused, + String refusalMessage, + boolean acknowledgementRowPreserved, + boolean inventoryStatePreserved, + boolean physicalBridgeStatePreserved) {} + public record AccountAbortProof( UUID transitionId, UUID cleanupId, @@ -2035,7 +2319,8 @@ private static RegionRedis open(String host, int port, boolean allowAccountMembe .addCommand(CommandType.PTTL) .addCommand(CommandType.GET) .addCommand(CommandType.SET) - .addCommand(CommandType.PEXPIRE); + .addCommand(CommandType.PEXPIRE) + .addCommand(CommandType.TIME); if (allowAccountMemberRepair) { permissions .keyPattern("session:game:index:account:*") diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 8d829b8117..325c8681ea 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -10,9 +10,13 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @Testcontainers(disabledWithoutDocker = true) @@ -20,6 +24,24 @@ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest extends CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Override + PostgreSQLContainer postgresContainer() { + return POSTGRES; + } + + @Override + GenericContainer redisContainer() { + return REDIS; + } + @Test void initializesOnlyAnAbsentRegionAtItsFirstEpochAndFirstTick() { assertThatThrownBy( @@ -67,7 +89,7 @@ void ownerReadRejectsAnAmbientSynchronizationContext() { } @Test - void exactOwnerRetryKeepsFenceAndReplacementIsHeld() { + void exactOwnerRetryReplacesFenceWithoutResettingRegionTimeline() { var initial = repository.installOwner( source, @@ -100,19 +122,34 @@ void exactOwnerRetryKeepsFenceAndReplacementIsHeld() { OPERATIONAL_REGION_ID); var current = repository.find(source).orElseThrow(); + var retry = + repository.installOwner( + source, + 1L, + current, + SECOND_LEASE_CORRELATION, + "game-session-service", + "instance-b", + Instant.parse("2026-10-26T00:00:02Z")); + + assertThat(retry.regionEpoch()).isEqualTo(1L); + assertThat(retry.executorFence()).isGreaterThan(initial.executorFence()); + assertThat(retry.leaseTokenCorrelation()).isEqualTo(SECOND_LEASE_CORRELATION); + assertThat(retry.ownerInstanceId()).isEqualTo("instance-b"); + assertThat(retry.lastCommittedTickId()).isEqualTo(7L); + assertThat(retry.lastCommittedTickBatchId()).isEqualTo("batch-7"); assertThatThrownBy( () -> repository.installOwner( source, 1L, - current, - SECOND_LEASE_CORRELATION, + initial, + FIRST_LEASE_CORRELATION, "game-session-service", - "instance-b", - Instant.parse("2026-10-26T00:00:02Z"))) + "instance-a", + Instant.parse("2026-10-26T00:00:03Z"))) .isInstanceOf(IllegalStateException.class); - assertThat(repository.find(source)).contains(current); - assertThat(fenceSequenceValue()).isEqualTo(sequenceAfterInstall); + assertThat(repository.find(source)).contains(retry); } @Test @@ -158,12 +195,12 @@ void ownerGrantAcceptsOnlyChangedLifecycleReadCorrelationAndKeepsInitialRequestB laterSource, 1L, initial, - FIRST_LEASE_CORRELATION, + SECOND_LEASE_CORRELATION, "game-session-service", - "instance-a", + "instance-b", Instant.parse("2026-10-26T00:00:02Z")); - assertThat(later).isEqualTo(initial); + assertThat(later.executorFence()).isGreaterThan(initial.executorFence()); assertThat(later.regionEpoch()).isEqualTo(1L); assertThat(later.lastCommittedTickId()).isEqualTo(-1L); assertThat( @@ -215,7 +252,7 @@ void sameRegionInDifferentGameInstancesHasDistinctPersistedOwnerTags() { } @Test - void concurrentReplacementRequestsLeaveTheOriginalFence() throws Exception { + void concurrentNewGrantsFromOnePriorOwnerInstallOnlyOneNewFence() throws Exception { var prior = repository.installOwner( source, @@ -242,10 +279,13 @@ void concurrentReplacementRequestsLeaveTheOriginalFence() throws Exception { start.countDown(); var firstResult = first.get(10, TimeUnit.SECONDS); var secondResult = second.get(10, TimeUnit.SECONDS); - assertThat(firstResult).isNull(); - assertThat(secondResult).isNull(); - assertThat(repository.find(source)).contains(prior); - assertThat(fenceSequenceValue()).isEqualTo(sequenceBefore); + assertThat((firstResult == null) ^ (secondResult == null)).isTrue(); + + var committed = repository.find(source).orElseThrow(); + assertThat(committed.executorFence()).isGreaterThan(prior.executorFence()); + assertThat(committed.regionEpoch()).isEqualTo(prior.regionEpoch()); + assertThat(fenceSequenceValue()).isEqualTo(sequenceBefore + 1L); + assertThat(committed).isEqualTo(firstResult == null ? secondResult : firstResult); } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java index 4e04624c32..a0c26a030a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java @@ -31,7 +31,6 @@ import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; -import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; import org.jooq.ExecuteContext; import org.jooq.Record; @@ -45,10 +44,12 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; -import org.testcontainers.junit.jupiter.Container; -@SuppressWarnings("resource") abstract class CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport { + abstract PostgreSQLContainer postgresContainer(); + + abstract GenericContainer redisContainer(); + static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); static final UUID OTHER_GAME_INSTANCE_ID = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); @@ -64,14 +65,6 @@ abstract class CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupp static final int TEST_TRANSFER_HISTORY_MAXIMUM_TRANSFERS = 256; static final int TEST_TRANSFER_HISTORY_MAXIMUM_ITEMS = 1024; - @Container - static final PostgreSQLContainer POSTGRES = - new PostgreSQLContainer<>(TestContainerImages.postgres()); - - @Container - static final GenericContainer REDIS = - new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); - @TempDir Path directory; DSLContext dsl; @@ -80,13 +73,13 @@ abstract class CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupp @BeforeAll void setUpRepository() { - PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgresContainer()); DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(POSTGRES.getDriverClassName()); - dataSource.setUrl(POSTGRES.getJdbcUrl()); - dataSource.setUsername(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setDriverClassName(postgresContainer().getDriverClassName()); + dataSource.setUrl(postgresContainer().getJdbcUrl()); + dataSource.setUsername(postgresContainer().getUsername()); + dataSource.setPassword(postgresContainer().getPassword()); CanonicalGameplayIssuerTestFixtures.migrationConfiguration( dataSource, @@ -104,6 +97,18 @@ void selectFreshOwnerScopeWithoutDiscardingRetainedCustody() { source = source(UUID.randomUUID(), CAPTURE_ID); } + static UUID beginAfterBarrier( + TransferSqlProof proof, + CanonicalGameplayRegionOwnerTransferRepository transfers, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + assertThat(start.await(5, TimeUnit.SECONDS)).isTrue(); + return transfers.within( + transferDeadline(), ignored -> transfers.begin(proof.scope, proof.prior)); + } + static void assertDatabaseWaitsFor(DSLContext sql, int blockerPid) throws Exception { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); do { @@ -213,6 +218,57 @@ public void close() { } } + /** Stops a real bridge transaction only after its inventory-clock lock was granted. */ + static final class InventoryRowLockGate extends DefaultExecuteListener implements AutoCloseable { + final AtomicBoolean armed = new AtomicBoolean(); + final AtomicInteger pid = new AtomicInteger(); + final CountDownLatch locked = new CountDownLatch(1); + final CountDownLatch resume = new CountDownLatch(1); + + void arm() { + armed.set(true); + } + + @Override + public void executeEnd(ExecuteContext context) { + String statement = context.sql(); + if (statement == null + || !statement.contains("game_session_canonical_binding_inventory_clock") + || !statement.contains("FOR UPDATE") + || !armed.compareAndSet(true, false)) return; + try (var query = context.connection().createStatement(); + var result = query.executeQuery("SELECT pg_backend_pid()")) { + assertThat(result.next()).isTrue(); + pid.set(result.getInt(1)); + locked.countDown(); + if (!resume.await(4, TimeUnit.SECONDS)) + throw new AssertionError("Inventory-row test gate was not released"); + } catch (java.sql.SQLException failure) { + throw new IllegalStateException("Could not observe actual inventory lock owner", failure); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Inventory-row test gate was interrupted", interrupted); + } + } + + void awaitLock() throws InterruptedException { + assertThat(locked.await(3, TimeUnit.SECONDS)).isTrue(); + } + + int backendPid() { + return pid.get(); + } + + void release() { + resume.countDown(); + } + + @Override + public void close() { + release(); + } + } + TransferSqlProof withCapacityBudget(int maximumRecords, long maximumBindingBytes) throws Exception { return new TransferSqlProof(maximumRecords, maximumBindingBytes, maximumRecords); @@ -221,6 +277,7 @@ TransferSqlProof withCapacityBudget(int maximumRecords, long maximumBindingBytes TransferSqlProof withTransferHistoryBudget(int maximumTransfers, int maximumItems) throws Exception { return new TransferSqlProof( + new DefaultExecuteListener(), TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS, TEST_CAPACITY_EVIDENCE_MAXIMUM_BINDING_BYTES, TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS, @@ -248,17 +305,46 @@ final class TransferSqlProof implements AutoCloseable { final CanonicalGameplayRegionRuntimeStatus prior; final OriginalNewCapacityExecution execution; final CanonicalGameplayRegionOwnerCompositionFixture.ExistingBinding region; + CanonicalGameplayRegionOwnerTransferRepository transfers; + CanonicalGameplayProtectedIncarnationReceiver receiver; + CanonicalGameplayRegionOwnerTransferCoordinator coordinator; TransferSqlProof() throws Exception { this( + new DefaultExecuteListener(), TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS, - TEST_CAPACITY_EVIDENCE_MAXIMUM_BINDING_BYTES, - TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS); + TEST_CAPACITY_EVIDENCE_MAXIMUM_BINDING_BYTES); } TransferSqlProof(int maximumRecords, long maximumBindingBytes, int maximumRetainedRecords) throws Exception { this( + new DefaultExecuteListener(), + maximumRecords, + maximumBindingBytes, + maximumRetainedRecords); + } + + TransferSqlProof(DefaultExecuteListener listener) throws Exception { + this( + listener, + TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS, + TEST_CAPACITY_EVIDENCE_MAXIMUM_BINDING_BYTES); + } + + TransferSqlProof(DefaultExecuteListener listener, int maximumRecords, long maximumBindingBytes) + throws Exception { + this(listener, maximumRecords, maximumBindingBytes, maximumRecords); + } + + TransferSqlProof( + DefaultExecuteListener listener, + int maximumRecords, + long maximumBindingBytes, + int maximumRetainedRecords) + throws Exception { + this( + listener, maximumRecords, maximumBindingBytes, maximumRetainedRecords, @@ -267,6 +353,7 @@ final class TransferSqlProof implements AutoCloseable { } TransferSqlProof( + DefaultExecuteListener listener, int maximumRecords, long maximumBindingBytes, int maximumRetainedRecords, @@ -275,7 +362,9 @@ final class TransferSqlProof implements AutoCloseable { throws Exception { String password = UUID.randomUUID().toString(); try (var administrator = - RedisClient.create(RedisURI.create(REDIS.getHost(), REDIS.getMappedPort(6379))); + RedisClient.create( + RedisURI.create( + redisContainer().getHost(), redisContainer().getMappedPort(6379))); var connection = administrator.connect(ByteArrayCodec.INSTANCE)) { connection.sync().flushdb(); connection @@ -312,18 +401,18 @@ final class TransferSqlProof implements AutoCloseable { .addCommand(CommandType.TIME)); } coordinationUri = - RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)) + RedisURI.Builder.redis(redisContainer().getHost(), redisContainer().getMappedPort(6379)) .withAuthentication("gamesession_coord_app", password) .withTimeout(Duration.ofSeconds(5)) .build(); redis = RedisClient.create(coordinationUri); redis.setOptions(ClientOptions.builder().autoReconnect(false).build()); var dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(POSTGRES.getDriverClassName()); - String url = POSTGRES.getJdbcUrl(); + dataSource.setDriverClassName(postgresContainer().getDriverClassName()); + String url = postgresContainer().getJdbcUrl(); dataSource.setUrl(url + (url.contains("?") ? "&" : "?") + "currentSchema=public"); - dataSource.setUsername(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setUsername(postgresContainer().getUsername()); + dataSource.setPassword(postgresContainer().getPassword()); var candidate = new Candidate( UUID.randomUUID(), @@ -342,7 +431,28 @@ final class TransferSqlProof implements AutoCloseable { BigInteger.ONE, BigInteger.valueOf(64)); fixture = new CanonicalGameplayAdmissionAbortCompositionFixture(dataSource, candidate, redis); - sql = fixture.dsl(); + sql = + DSL.using( + fixture + .dsl() + .configuration() + .deriveAppending( + listener, + new DefaultExecuteListener() { + @Override + public void resultEnd(ExecuteContext context) { + String query = context.sql(); + var result = context.result(); + if (query != null + && query.contains("JOIN game_session_region_runtime_status r") + && result != null) { + assertThat(result.fields()) + .extracting(org.jooq.Field::getName) + .as("current transfer observation has unambiguous field names") + .doesNotHaveDuplicates(); + } + } + })); tags = new CanonicalGameplayTenantGameplayTagRepository(sql, "test", 1); scripts = RedisScriptCatalog.fromContributions( @@ -380,8 +490,8 @@ final class TransferSqlProof implements AutoCloseable { var assignment = tags.assignmentForTransition(admission.candidate().bindingDecisionId()); sql.execute( "INSERT INTO game_session_capacity_evidence_budget" - + " (tenant_id,maximum_records,maximum_binding_bytes,maximum_retained_records) VALUES (?,?,?,?)" - + " ON CONFLICT DO NOTHING", + + " (tenant_id,maximum_records,maximum_binding_bytes,maximum_retained_records) VALUES" + + " (?,?,?,?) ON CONFLICT DO NOTHING", assignment.tenantId(), maximumRecords, maximumBindingBytes, @@ -394,6 +504,7 @@ final class TransferSqlProof implements AutoCloseable { maximumItems); execution = newControlledExecution(); precharge(execution); + recreateTransferOwners(); } void replayBridge() { @@ -414,11 +525,29 @@ OriginalNewCapacityExecution newControlledExecution() { prior.executorFence().longValueExact()); } + CanonicalGameplayRegionOwnerTransferRepository transfers(DSLContext context) { + return new CanonicalGameplayRegionOwnerTransferRepository(context, clock, tags); + } + CanonicalGameplayOriginalNewCapacityExecutionOwner capacity(DSLContext context) { return new CanonicalGameplayOriginalNewCapacityExecutionOwner( context, redis, scripts, clock, tags); } + void recreateTransferOwners() throws Exception { + transfers = transfers(sql); + receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture(clock) + .receiver(transfers, tags); + coordinator = + new CanonicalGameplayRegionOwnerTransferCoordinator( + sql, clock, transfers, capacity(sql), receiver); + } + + UUID begin() { + return transfers.within(transferDeadline(), ignored -> transfers.begin(scope, prior)); + } + void seedUndeliveredDispatch(OriginalNewCapacityExecution original) { // Controlled crash-window storage seed only. No guard is disabled, no AUTHORIZED result is // invented, and this is not the real authorize path exercised by the two row-lock races. @@ -529,8 +658,8 @@ UUID insertRawFrozenTransfer( context.execute( "INSERT INTO game_session_region_owner_transfer" + " (transfer_id,tenant_id,game_instance_id,region_id,region_epoch,old_owner_id,old_owner_fence," - + " old_lease_correlation,source_digest,intent_digest,state)" - + " VALUES (?,?,?,?,?,?,?,?,?,?,'FROZEN')", + + " old_lease_correlation,source_digest,intent_digest,state) VALUES" + + " (?,?,?,?,?,?,?,?,?,?,'FROZEN')", transferId, source.tenantId(), source.gameInstanceId(), @@ -539,22 +668,18 @@ UUID insertRawFrozenTransfer( owner.ownerInstanceId(), owner.executorFence().longValueExact(), owner.leaseTokenCorrelation(), - "sha256:" + "b".repeat(64), + CanonicalGameplayRegionOwnerTransferRepository.sourceDigest(source, owner), "sha256:" + "c".repeat(64)); return transferId; } void insertRawTransferItem(DSLContext context, UUID transferId, long ordinal) { - insertRawTransferItem(context, transferId, ordinal, execution); - } - - void insertRawTransferItem( - DSLContext context, UUID transferId, long ordinal, OriginalNewCapacityExecution execution) { var assignment = tags.assignmentForTransition(execution.transitionId()); context.execute( "INSERT INTO game_session_region_owner_transfer_item" + " (transfer_id,target_ordinal,execution_digest,canonical_execution,candidate_digest," - + " tenant_gameplay_tag,workload_namespace,allocation_version) VALUES (?,?,?,?,?,?,?,?)", + + " tenant_gameplay_tag,workload_namespace,allocation_version) VALUES" + + " (?,?,?,?,?,?,?,?)", transferId, ordinal, execution.digest(), @@ -565,6 +690,59 @@ void insertRawTransferItem( assignment.allocationVersion()); } + List captureAndFence(UUID id) { + var page = transfers.within(transferDeadline(), ignored -> transfers.capture(id)); + assertThat(page.size()).isLessThanOrEqualTo(32); + for (var item : page) fence(item); + return page; + } + + void fence(CanonicalGameplayRegionOwnerTransferRepository.Item item) { + long deadline = transferDeadline(); + transfers.within( + deadline, + budget -> { + var before = + receiver.observeForRegionOwnerTransfer(item.transferId(), item.ordinal(), deadline); + var dispatch = transfers.fenceDispatch(item, before); + var actual = + capacity(sql).forTransferBudget(budget).fenceForTransfer(item, dispatch, deadline); + var after = + receiver.observeForRegionOwnerTransfer(item.transferId(), item.ordinal(), deadline); + transfers.retainFence(item, actual, before, after); + return null; + }); + } + + void verifyPage(UUID id) { + long cursor = + transfers.within(transferDeadline(), ignored -> transfers.verificationCursor(id)); + var page = transfers.within(transferDeadline(), ignored -> transfers.page(id, cursor)); + assertThat(page.size()).isLessThanOrEqualTo(32); + for (var item : page) { + var before = receiver.observeForRegionOwnerTransfer(id, item.ordinal(), transferDeadline()); + var actual = capacity(sql).readTransferFence(item, transferDeadline()); + var after = receiver.observeForRegionOwnerTransfer(id, item.ordinal(), transferDeadline()); + transfers.within( + transferDeadline(), + ignored -> { + transfers.retainVerification(item, actual, before, after); + return null; + }); + } + } + + CanonicalGameplayRegionRuntimeStatus install(UUID id) { + return coordinator.install( + id, + scope, + prior, + "e".repeat(64), + "game-session-service", + "sql-proof-successor", + transferDeadline()); + } + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback issuerOpen() { var repository = new CanonicalGameplayIssuerAdmissionBarrierRepository( @@ -637,7 +815,8 @@ CanonicalGameplayRegionRuntimeStatus currentOwner() { String executionState(OriginalNewCapacityExecution original) { Record row = sql.fetchOne( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + "SELECT status FROM game_session_original_new_capacity_execution WHERE" + + " execution_digest=?", original.digest()); return row == null ? null : row.get(0, String.class); } @@ -661,13 +840,31 @@ boolean physicalExecutionExists(OriginalNewCapacityExecution original, String ta } } + void losePhysicalExecution(OriginalNewCapacityExecution original) { + String tag = tags.assignmentForTransition(original.transitionId()).tenantGameplayTag(); + try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) { + assertThat( + connection + .sync() + .del( + ascii( + "session:game:capacity-execution:{" + + tag + + "}:" + + original.request().admissionAttemptId()))) + .isEqualTo(1L); + } + } + void rawReplaceOwner(String owner, String correlation) { rawReplaceOwner(sql, owner, correlation); } void rawReplaceOwner(DSLContext context, String owner, String correlation) { context.execute( - "UPDATE game_session_region_runtime_status SET owner_instance_id=?,executor_fence=nextval('game_session_region_executor_fence_seq'),lease_token_correlation=? WHERE tenant_id=? AND game_instance_id=? AND region_id=?", + "UPDATE game_session_region_runtime_status SET" + + " owner_instance_id=?,executor_fence=nextval('game_session_region_executor_fence_seq'),lease_token_correlation=?" + + " WHERE tenant_id=? AND game_instance_id=? AND region_id=?", owner, correlation, scope.tenantId(), @@ -675,40 +872,9 @@ void rawReplaceOwner(DSLContext context, String owner, String correlation) { scope.regionId()); } - // Seeds the fields guarded by the SQL completion boundary. It provides no physical proof. - void retainControlledTransferReceipt(UUID id) { - String digest = "sha256:" + "a".repeat(64); - UUID round = UUID.randomUUID(); - sql.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - assertThat( - transaction.execute( - "UPDATE game_session_region_owner_transfer" - + " SET incarnation_digest=?,verification_round=? WHERE transfer_id=?", - digest, - round, - id)) - .isEqualTo(1); - assertThat( - transaction.execute( - "UPDATE game_session_region_owner_transfer_item" - + " SET fence_readback=?,incarnation_digest=?,before_payload_digest=?," - + " after_payload_digest=?,verified_round=? WHERE transfer_id=?", - ascii("controlled-readback"), - digest, - digest, - digest, - round, - id)) - .isEqualTo(1); - assertThat( - transaction.execute( - "UPDATE game_session_region_owner_transfer" - + " SET verification_cursor=0,verification_complete=true WHERE transfer_id=?", - id)) - .isEqualTo(1); - }); + CanonicalGameplayRegionRuntimeStatus rawCompleteAndInstall( + UUID transferId, String owner, String correlation) { + return rawCompleteAndInstall(transferId, owner, correlation, false); } CanonicalGameplayRegionRuntimeStatus rawCompleteAndInstall( @@ -716,7 +882,9 @@ CanonicalGameplayRegionRuntimeStatus rawCompleteAndInstall( String schema = sql.fetchSingle("SELECT current_schema()").get(0, String.class); try (var connection = java.sql.DriverManager.getConnection( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + postgresContainer().getJdbcUrl(), + postgresContainer().getUsername(), + postgresContainer().getPassword())) { connection.setSchema(schema); connection.setAutoCommit(false); DSLContext transaction = DSL.using(connection, SQLDialect.POSTGRES); @@ -735,8 +903,8 @@ CanonicalGameplayRegionRuntimeStatus rawCompleteAndInstall( transferId); } if (transaction.execute( - "UPDATE game_session_region_owner_transfer" - + " SET state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=?" + "UPDATE game_session_region_owner_transfer SET" + + " state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=?" + " WHERE transfer_id=? AND state='FROZEN'", owner, fence, @@ -745,16 +913,16 @@ CanonicalGameplayRegionRuntimeStatus rawCompleteAndInstall( != 1) throw new IllegalStateException("Expected one frozen transfer"); Record installed = transaction.fetchOne( - "UPDATE game_session_region_runtime_status" - + " SET executor_fence=?,lease_token_correlation=?,owner_service=?,owner_instance_id=?," - + " updated_at=CURRENT_TIMESTAMP::timestamp" - + " WHERE tenant_id=? AND game_instance_id=? AND region_id=?" - + " AND tenant_region_tag=? AND canonical_region_id=? AND lifecycle_epoch=?" - + " AND lifecycle_row_version=? AND capture_id=? AND lifecycle_request_bytes=?" - + " AND graph_sha256=? AND preparation_input_digest=? AND region_epoch=?" - + " AND executor_fence=? AND lease_token_correlation=? AND owner_service=?" - + " AND owner_instance_id=? AND paused=? AND last_committed_tick_id=?" - + " AND last_committed_tick_batch_id IS NOT DISTINCT FROM ? RETURNING *", + "UPDATE game_session_region_runtime_status SET" + + " executor_fence=?,lease_token_correlation=?,owner_service=?,owner_instance_id=?," + + " updated_at=CURRENT_TIMESTAMP::timestamp WHERE tenant_id=? AND" + + " game_instance_id=? AND region_id=? AND tenant_region_tag=? AND" + + " canonical_region_id=? AND lifecycle_epoch=? AND lifecycle_row_version=? AND" + + " capture_id=? AND lifecycle_request_bytes=? AND graph_sha256=? AND" + + " preparation_input_digest=? AND region_epoch=? AND executor_fence=? AND" + + " lease_token_correlation=? AND owner_service=? AND owner_instance_id=? AND" + + " paused=? AND last_committed_tick_id=? AND last_committed_tick_batch_id IS" + + " NOT DISTINCT FROM ? RETURNING *", fence, correlation, "game-session-service", @@ -789,29 +957,24 @@ CanonicalGameplayRegionRuntimeStatus rawCompleteAndInstall( String originalImage() { return sql.fetch( - "SELECT to_jsonb(e)::text FROM game_session_original_new_capacity_execution e ORDER BY execution_digest") + "SELECT to_jsonb(e)::text FROM game_session_original_new_capacity_execution e ORDER" + + " BY execution_digest") .getValues(0, String.class) .toString(); } String transferImage(UUID id) { return sql.fetchSingle( - "SELECT to_jsonb(t)::text FROM game_session_region_owner_transfer t WHERE transfer_id=?", + "SELECT to_jsonb(t)::text FROM game_session_region_owner_transfer t WHERE" + + " transfer_id=?", id) .get(0, String.class); } - List transferExecutionDigests(UUID id) { - return sql.fetch( - "SELECT execution_digest FROM game_session_region_owner_transfer_item" - + " WHERE transfer_id=? ORDER BY target_ordinal", - id) - .getValues(0, String.class); - } - String itemImage(UUID id) { return sql.fetch( - "SELECT to_jsonb(i)::text FROM game_session_region_owner_transfer_item i WHERE transfer_id=? ORDER BY target_ordinal", + "SELECT to_jsonb(i)::text FROM game_session_region_owner_transfer_item i WHERE" + + " transfer_id=? ORDER BY target_ordinal", id) .getValues(0, String.class) .toString(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java new file mode 100644 index 0000000000..964b405328 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -0,0 +1,993 @@ +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.codec.ByteArrayCodec; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.ExecuteContext; +import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest + extends CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Override + PostgreSQLContainer postgresContainer() { + return POSTGRES; + } + + @Override + GenericContainer redisContainer() { + return REDIS; + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({"1,134217728", "128,1048576"}) + void chargedAbsentExecutionCanStillBeFencedWhenEitherBudgetDimensionIsFull( + int maximumRecords, long maximumBindingBytes) throws Exception { + try (var proof = withCapacityBudget(maximumRecords, maximumBindingBytes)) { + proof.seedUndeliveredDispatch(proof.execution); + assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); + assertThat( + proof + .sql + .fetchSingle( + "SELECT count(*) FROM game_session_capacity_evidence_charge WHERE" + + " tenant_id=?", + proof.admission.candidate().bindingIdentity().tenantId()) + .get(0, Long.class)) + .isEqualTo(1L); + + UUID transferId = proof.begin(); + assertThat(proof.captureAndFence(transferId)).hasSize(1); + assertThat(proof.physicalExecutionExists(proof.execution)).isTrue(); + assertThat(proof.executionState(proof.execution)).isEqualTo("INSTALL_DISPATCHED"); + assertThat( + proof + .sql + .fetchSingle( + "SELECT count(*) FROM game_session_capacity_evidence_charge WHERE" + + " tenant_id=?", + proof.admission.candidate().bindingIdentity().tenantId()) + .get(0, Long.class)) + .isEqualTo(1L); + } + } + + @Test + void retainedDenialReleasesTheLastSlotAndCannotRaceAStoredDispatch() throws Exception { + try (var proof = new TransferSqlProof(1, 1_048_576L, 3)) { + var original = proof.execution; + var later = proof.newControlledExecution(); + assertThatThrownBy(() -> proof.precharge(later)).isInstanceOf(IllegalStateException.class); + var denial = UUID.randomUUID(); + proof.settle(original, denial); + proof.settle(original, denial); + assertThatThrownBy(() -> proof.settle(original, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> proof.insertExecution(original, "INSTALL_DISPATCHED", null)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Exact retained capacity evidence charge required"); + + proof.seedUndeliveredDispatch(later); + assertThatThrownBy(() -> proof.settle(later, UUID.randomUUID())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Execution custody prevents capacity evidence settlement"); + assertThat(proof.executionState(later)).isEqualTo("INSTALL_DISPATCHED"); + assertThat(proof.executionState(original)).isNull(); + assertThat(proof.physicalExecutionExists(original)).isFalse(); + } + } + + @Test + void retainedDenialHistoryRemainsBoundedIndependentlyOfActiveSlots() throws Exception { + try (var proof = new TransferSqlProof(1, 1_048_576L, 2)) { + proof.settle(proof.execution, UUID.randomUUID()); + var next = proof.newControlledExecution(); + proof.precharge(next); + proof.settle(next, UUID.randomUUID()); + assertThatThrownBy(() -> proof.precharge(proof.newControlledExecution())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Original NEW capacity evidence budget is unavailable"); + } + } + + @Test + void postgresSerializesTheLastEvidenceChargeAcrossConcurrentAttempts() throws Exception { + try (var proof = withCapacityBudget(2, 2_097_152L); + var callers = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) { + var first = proof.newControlledExecution(); + var second = proof.newControlledExecution(); + var ready = new java.util.concurrent.CountDownLatch(2); + var start = new java.util.concurrent.CountDownLatch(1); + var assignment = + proof.tags.assignmentForTransition(proof.admission.candidate().bindingDecisionId()); + var selected = + new CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner( + proof.execution.selectedOwnerId(), proof.execution.selectedOwnerFence()); + java.util.function.Function< + OriginalNewCapacityExecution, java.util.concurrent.Future> + compete = + attempt -> + callers.submit( + () -> { + ready.countDown(); + if (!start.await(2, java.util.concurrent.TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent proof start unavailable"); + } + try { + proof.sql.transaction( + configuration -> + CanonicalGameplayCapacityEvidenceBudget.precharge( + DSL.using(configuration), + attempt.request(), + attempt.candidateDigest(), + selected, + assignment.tenantGameplayTag())); + return true; + } catch (IllegalStateException refused) { + assertThat(refused) + .hasMessage("Original NEW capacity evidence budget is unavailable"); + return false; + } + }); + var firstResult = compete.apply(first); + var secondResult = compete.apply(second); + assertThat(ready.await(2, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat( + List.of( + firstResult.get(5, java.util.concurrent.TimeUnit.SECONDS), + secondResult.get(5, java.util.concurrent.TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + assertThat( + proof + .sql + .fetchSingle( + "SELECT count(*) FROM game_session_capacity_evidence_charge WHERE" + + " tenant_id=?", + assignment.tenantId()) + .get(0, Long.class)) + .isEqualTo(2L); + } + } + + @Test + void fullTransferItemBudgetAllowsExistingIntentToCompleteButRefusesTheNextFreeze() + throws Exception { + try (var proof = withTransferHistoryBudget(2, 1)) { + proof.seedUndeliveredDispatch(proof.execution); + String originalExecution = proof.originalImage(); + UUID id = proof.begin(); + assertThat(id).isNotNull(); + assertThat( + proof + .sql + .fetchSingle( + "SELECT reserved_execution_items FROM game_session_region_owner_transfer" + + " WHERE transfer_id=?", + id) + .get(0, Integer.class)) + .isEqualTo(1); + assertThat(proof.itemImage(id)).isEqualTo("[]"); + assertTransferHistoryGuard( + () -> proof.insertRawTransferItem(proof.sql, id, 1), + "Transfer item is outside its reserved inventory"); + assertThat(proof.itemImage(id)).isEqualTo("[]"); + String frozen = proof.transferImage(id); + proof.recreateTransferOwners(); + assertThat(proof.begin()).isEqualTo(id); + assertThat(proof.transferImage(id)).isEqualTo(frozen); + assertThat(proof.captureAndFence(id)) + .extracting(item -> item.execution().digest()) + .containsExactly(proof.execution.digest()); + proof.verifyPage(id); + boolean verified = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(verified).isTrue(); + var installed = proof.install(id); + String completed = proof.transferImage(id); + String items = proof.itemImage(id); + proof.recreateTransferOwners(); + assertThat( + proof.coordinator.recoverCompleted( + id, + installed.ownerInstanceId(), + installed.leaseTokenCorrelation(), + transferDeadline())) + .isEqualTo(installed); + + assertTransferHistoryGuard( + () -> proof.coordinator.advance(proof.scope, installed, transferDeadline()), + "Transfer history cannot reserve its full execution inventory"); + assertThat( + proof + .sql + .fetch("SELECT transfer_id FROM game_session_region_owner_transfer") + .getValues(0, UUID.class)) + .containsExactly(id); + assertThat(proof.transferImage(id)).isEqualTo(completed); + assertThat(proof.itemImage(id)).isEqualTo(items); + assertThat(proof.originalImage()).isEqualTo(originalExecution); + assertThat(proof.currentOwner()).isEqualTo(installed); + } + } + + @Test + void boundedCensusAndVerificationResumeBeyondThirtyTwoWithoutLosingAnyOriginal() + throws Exception { + try (var proof = new TransferSqlProof()) { + // Controlled reservation envelopes seed SQL custody, not Account-authorized multiattempt + // behavior. Every candidate, bridge, mapping and owner source is retained by its real owner. + List originals = new ArrayList<>(); + for (int index = 0; index < 65; index++) { + var original = proof.newControlledExecution(); + originals.add(original); + proof.seedUndeliveredDispatch(original); + } + UUID id = proof.begin(); + var first = proof.captureAndFence(id); + assertThat(first).hasSize(32); + assertThat(first) + .allMatch(item -> item.execution().transitionId().equals(proof.execution.transitionId())); + assertThatThrownBy( + () -> + proof.transfers.within( + transferDeadline(), + ignored -> proof.transfers.frozenOriginal(proof.execution.transitionId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Normal region owner transfer is held"); + assertThatThrownBy( + () -> + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id))) + .isInstanceOf(IllegalStateException.class); + proof.recreateTransferOwners(); + assertThat(proof.begin()).isEqualTo(id); + assertThat(proof.captureAndFence(id)).hasSize(32); + assertThatThrownBy( + () -> + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id))) + .isInstanceOf(IllegalStateException.class); + proof.recreateTransferOwners(); + assertThat(proof.captureAndFence(id)).hasSize(1); + assertThat(proof.captureAndFence(id)).isEmpty(); + + List captured = new ArrayList<>(); + long cursor = -1; + for (int size : List.of(32, 32, 1)) { + long after = cursor; + var page = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.page(id, after)); + assertThat(page).hasSize(size); + captured.addAll(page.stream().map(item -> item.execution().digest()).toList()); + cursor = page.getLast().ordinal(); + } + assertThat(captured) + .containsExactlyInAnyOrderElementsOf( + originals.stream().map(OriginalNewCapacityExecution::digest).toList()); + assertThat(cursor).isEqualTo(64L); + long initialVerificationCursor = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id)); + assertThat(initialVerificationCursor).isEqualTo(-1L); + proof.verifyPage(id); + boolean firstPageComplete = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(firstPageComplete).isFalse(); + assertThatThrownBy(() -> proof.install(id)).isInstanceOf(IllegalStateException.class); + proof.recreateTransferOwners(); + long resumedVerificationCursor = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id)); + assertThat(resumedVerificationCursor).isEqualTo(31L); + proof.verifyPage(id); + boolean secondPageComplete = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(secondPageComplete).isFalse(); + proof.recreateTransferOwners(); + proof.verifyPage(id); + boolean allPagesComplete = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(allPagesComplete).isTrue(); + var installed = proof.install(id); + assertThat(installed.executorFence()).isGreaterThan(proof.prior.executorFence()); + assertThat(proof.currentOwner()).isEqualTo(installed); + assertThat(proof.transfers.readCurrent(id, 64).controlState()).isEqualTo("COMPLETED"); + assertThat( + proof + .sql + .fetchSingle( + "SELECT count(*) FROM game_session_region_owner_transfer_item WHERE" + + " transfer_id=? AND fence_readback IS NOT NULL AND verified_round IS" + + " NOT NULL", + id) + .get(0, Long.class)) + .isEqualTo(65L); + assertThat( + proof + .sql + .fetch("SELECT status FROM game_session_original_new_capacity_execution") + .getValues("status", String.class)) + .containsOnly("INSTALL_DISPATCHED"); + } + } + + @Test + void finalQualificationRechecksLostFenceBeyondTheFirstPageWithoutRecreatingIt() throws Exception { + try (var proof = new TransferSqlProof()) { + for (int index = 0; index < 33; index++) { + proof.seedUndeliveredDispatch(proof.newControlledExecution()); + } + UUID id = proof.begin(); + assertThat(proof.captureAndFence(id)).hasSize(32); + assertThat(proof.captureAndFence(id)).hasSize(1); + proof.verifyPage(id); + proof.recreateTransferOwners(); + proof.verifyPage(id); + boolean allPagesComplete = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(allPagesComplete).isTrue(); + var last = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.page(id, 31).getFirst()); + assertThat(last.ordinal()).isEqualTo(32L); + String receipt = proof.itemImage(id); + proof.losePhysicalExecution(last.execution()); + proof.recreateTransferOwners(); + assertThatThrownBy(() -> proof.install(id)).isInstanceOf(IllegalStateException.class); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + assertThat(proof.transfers.readCurrent(id, 32).controlState()).isEqualTo("FROZEN"); + assertThat(proof.physicalExecutionExists(last.execution())).isFalse(); + assertThat(proof.itemImage(id)).isEqualTo(receipt); + assertThat(proof.begin()).isEqualTo(id); + assertThat(proof.captureAndFence(id)).isEmpty(); + assertThat(proof.physicalExecutionExists(last.execution())).isFalse(); + } + } + + @Test + void terminalOnlyTransferRecoversExactCompletedSuccessorAfterOriginalFinalReceipt() + throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), proof.clock); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + proof + .capacity(proof.sql) + .authorize( + proof.admission, template, account, issuer, proof.execution, transferDeadline()); + try (var readback = + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + proof.redis, proof.scripts, proof.clock, proof.tags) + .finalizeOriginalNewOnce( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline())) { + UUID id = proof.begin(); + assertThatThrownBy( + () -> + proof.coordinator.recoverCompleted( + id, "sql-proof-successor", "e".repeat(64), transferDeadline())) + .isInstanceOf(IllegalStateException.class); + + new CanonicalGameplayBindingInventoryRepository(proof.sql) + .commitOriginalNewFinalAdmission(readback); + assertThat(proof.captureAndFence(id)).isEmpty(); + proof.verifyPage(id); + boolean verified = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(verified).isTrue(); + var installed = proof.install(id); + String completion = proof.transferImage(id); + String retained = proof.originalImage(); + assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED"); + assertThat( + proof.coordinator.recoverCompleted( + id, + installed.ownerInstanceId(), + installed.leaseTokenCorrelation(), + transferDeadline())) + .isEqualTo(installed); + assertThatThrownBy( + () -> + proof.coordinator.recoverCompleted( + id, installed.ownerInstanceId(), "f".repeat(64), transferDeadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(proof.currentOwner()).isEqualTo(installed); + assertThat(proof.transferImage(id)).isEqualTo(completion); + assertThat(proof.originalImage()).isEqualTo(retained); + } + } + } + + @Test + void installationResumesFrozenTransferWhenTheOriginalAbortedBeforeCapture() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + assertThat(id).isNotNull(); + assertThat(proof.itemImage(id)).isEqualTo("[]"); + assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); + String tag = + proof.tags.assignmentForTransition(proof.execution.transitionId()).tenantGameplayTag(); + assertThat(proof.fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + String originalExecution = proof.originalImage(); + var original = proof.region.installation(); + try (var connection = proof.redis.connect(ByteArrayCodec.INSTANCE)) { + assertThat(connection.sync().pexpire(ascii(original.grant.key()), 0)).isTrue(); + } + proof.recreateTransferOwners(); + + var installed = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + proof.sql, + proof.redis, + proof.coordinationUri, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayRegionLeaseRedisScriptContribution())), + original, + proof.upstream.resolver, + proof.coordinator, + transferDeadline()); + + assertThat(installed.status.executorFence()).isGreaterThan(proof.prior.executorFence()); + assertThat(installed.status).isEqualTo(proof.currentOwner()); + assertThat(installed.evidence).isNull(); + assertThat(proof.transfers.readCurrent(id, 0).controlState()).isEqualTo("COMPLETED"); + assertThat(proof.itemImage(id)).contains(proof.execution.digest()); + assertThat(proof.physicalExecutionExists(proof.execution, tag)).isTrue(); + assertThat(proof.originalImage()).isEqualTo(originalExecution); + } + } + + @Test + void installationRefusesSignedEvidenceThatExpiresWhileAcquiringTheRegionLock() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.newControlledExecution()); + var wall = new AtomicLong(proof.clock.millis()); + Clock clock = org.mockito.Mockito.mock(Clock.class); + org.mockito.Mockito.when(clock.millis()).thenAnswer(ignored -> wall.get()); + org.mockito.Mockito.when(clock.instant()) + .thenAnswer(ignored -> Instant.ofEpochMilli(wall.get())); + var expireAfterLock = new AtomicBoolean(); + var listener = + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.contains("pg_advisory_xact_lock") + && expireAfterLock.compareAndSet(true, false)) wall.addAndGet(1_100); + } + }; + DSLContext installingSql = DSL.using(proof.sql.configuration().deriveAppending(listener)); + var transfers = + new CanonicalGameplayRegionOwnerTransferRepository(installingSql, clock, proof.tags); + var observations = + new CanonicalGameplayControlledRegionTransferObservationFixture( + clock, Duration.ofSeconds(1)) + .receiver(transfers, proof.tags); + var coordinator = + new CanonicalGameplayRegionOwnerTransferCoordinator( + installingSql, clock, transfers, proof.capacity(installingSql), observations); + UUID id = coordinator.advance(proof.scope, proof.prior, wall.get() + 5_000); + assertThat(id).isNotNull(); + String before = proof.transferImage(id); + expireAfterLock.set(true); + long deadline = wall.get() + 5_000; + assertThatThrownBy( + () -> + coordinator.install( + id, + proof.scope, + proof.prior, + "e".repeat(64), + "game-session-service", + "sql-proof-successor", + deadline)) + .isInstanceOf(IllegalStateException.class); + assertThat(expireAfterLock).isFalse(); + assertThat(wall.get()).isLessThan(deadline); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + assertThat(proof.transferImage(id)).isEqualTo(before); + } + } + + @Test + void capturedOriginalThatBecomesTerminalStillRequiresQualifiedTransferCompletion() + throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), proof.clock); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + proof + .capacity(proof.sql) + .authorize( + proof.admission, template, account, issuer, proof.execution, transferDeadline()); + try (var readback = + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + proof.redis, proof.scripts, proof.clock, proof.tags) + .finalizeOriginalNewOnce( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline())) { + UUID id = proof.begin(); + var captured = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertThat(captured) + .extracting(item -> item.execution().digest()) + .containsExactly(proof.execution.digest()); + new CanonicalGameplayBindingInventoryRepository(proof.sql) + .commitOriginalNewFinalAdmission(readback); + assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED"); + String frozen = proof.transferImage(id); + String inventory = proof.itemImage(id); + assertThatThrownBy( + () -> proof.rawCompleteAndInstall(id, "sql-proof-successor", "e".repeat(64), true)) + .rootCause() + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains( + "Captured region transfer item lacks its full exact current receipt"); + }); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + assertThat(proof.transferImage(id)).isEqualTo(frozen); + assertThat(proof.itemImage(id)).isEqualTo(inventory); + var status = new CanonicalGameplayRegionRuntimeStatusRepository(proof.sql); + + assertThatThrownBy( + () -> + status.installOwner( + proof.scope, + proof.prior.regionEpoch(), + proof.prior, + "e".repeat(64), + "game-session-service", + "sql-proof-successor", + proof.clock.instant())) + .isInstanceOf(IllegalStateException.class) + .hasRootCauseMessage("Normal region owner transfer is held"); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + assertThat(proof.transferImage(id)).isEqualTo(frozen); + assertThat(proof.itemImage(id)).isEqualTo(inventory); + + proof.fence(captured.getFirst()); + proof.verifyPage(id); + boolean verified = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(verified).isTrue(); + assertThat( + proof + .rawCompleteAndInstall(id, "sql-proof-successor", "e".repeat(64)) + .ownerInstanceId()) + .isEqualTo("sql-proof-successor"); + assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED"); + assertThat(proof.transfers.readCurrent(id, captured.getFirst().ordinal()).controlState()) + .isEqualTo("COMPLETED"); + } + } + } + + @Test + void standaloneTransferObservationCancelsBlockedSqlAtItsExplicitDeadline() throws Exception { + try (var proof = new TransferSqlProof(); + var lock = + java.sql.DriverManager.getConnection( + postgresContainer().getJdbcUrl(), + postgresContainer().getUsername(), + postgresContainer().getPassword())) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var captured = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertThat(captured).hasSize(1); + lock.setSchema(proof.sql.fetchSingle("SELECT current_schema()").get(0, String.class)); + lock.setAutoCommit(false); + try (var statement = lock.createStatement()) { + statement.execute("LOCK TABLE game_session_region_owner_transfer IN ACCESS EXCLUSIVE MODE"); + } + try { + long start = System.nanoTime(); + assertThatThrownBy( + () -> + proof.receiver.observeForRegionOwnerTransfer( + id, captured.getFirst().ordinal(), proof.clock.millis() + 500L)) + .isInstanceOf(ObservationUnavailableException.class); + assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofSeconds(3)); + } finally { + lock.rollback(); + } + assertThat( + proof + .receiver + .observeForRegionOwnerTransfer( + id, captured.getFirst().ordinal(), transferDeadline()) + .regionOwnerTransferContext() + .transferId()) + .isEqualTo(id); + } + } + + @Test + void originalCapacityExecutionRefusesForgedInitialAuthorizationAndTerminalEvidence() + throws Exception { + try (var proof = new TransferSqlProof()) { + byte[] forgedReadback = {1}; + for (String status : List.of("AUTHORIZED", "COMMITTED", "CLOSED", "INSTALL_DISPATCHED")) { + byte[] readback = "AUTHORIZED".equals(status) ? null : forgedReadback; + assertThatThrownBy(() -> proof.insertExecution(proof.execution, status, readback)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining( + "Original NEW capacity execution cannot start with an authorization or terminal" + + " proof"); + } + assertThat(proof.executionState(proof.execution)).isNull(); + assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + + proof.seedUndeliveredDispatch(proof.execution); + assertThat(proof.executionState(proof.execution)).isEqualTo("INSTALL_DISPATCHED"); + assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); + } + } + + @Test + void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throws Exception { + try (var proof = new TransferSqlProof()) { + assertThatThrownBy( + () -> + proof.sql.transaction( + configuration -> + CanonicalGameplayRegionOwnerTransferRepository.completeTerminalOnly( + DSL.using(configuration), + proof.prior, + "unretained-terminal-successor", + proof.prior.executorFence().longValueExact() + 1, + "e".repeat(64)))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Normal region owner transfer is held"); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + proof.seedUndeliveredDispatch(proof.execution); + String original = proof.originalImage(); + assertSqlGuard(() -> proof.rawReplaceOwner("unretained-successor", "e".repeat(64))); + String forgedOwner = "forged-successor"; + String forgedLease = "e".repeat(64); + long forgedFence = + proof + .sql + .fetchSingle("SELECT nextval('game_session_region_executor_fence_seq')") + .get(0, Long.class); + for (String state : List.of("COMPLETED", "FROZEN")) { + boolean completed = "COMPLETED".equals(state); + assertThatThrownBy( + () -> + proof.sql.execute( + "INSERT INTO game_session_region_owner_transfer" + + " (transfer_id,tenant_id,game_instance_id,region_id,region_epoch,old_owner_id,old_owner_fence," + + " old_lease_correlation,source_digest,intent_digest,state,incarnation_digest,verification_round," + + " verification_cursor,verification_complete,new_owner_id,new_owner_fence,new_lease_correlation)" + + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,true,?,?,?)", + UUID.randomUUID(), + proof.scope.tenantId(), + proof.scope.gameInstanceId(), + proof.scope.regionId(), + proof.prior.regionEpoch(), + proof.prior.ownerInstanceId(), + proof.prior.executorFence().longValueExact(), + proof.prior.leaseTokenCorrelation(), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64), + state, + "sha256:" + "a".repeat(64), + UUID.randomUUID(), + 0L, + completed ? forgedOwner : null, + completed ? forgedFence : null, + completed ? forgedLease : null)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Region transfer must start as a clean frozen intent"); + } + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_runtime_status SET" + + " owner_instance_id=?,executor_fence=?,lease_token_correlation=? WHERE" + + " tenant_id=? AND game_instance_id=? AND region_id=?", + forgedOwner, + forgedFence, + forgedLease, + proof.scope.tenantId(), + proof.scope.gameInstanceId(), + proof.scope.regionId())); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + UUID id = proof.begin(); + assertSqlGuard(() -> proof.rawReplaceOwner("frozen-successor", "e".repeat(64))); + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer SET state='COMPLETED'," + + " new_owner_id='forged-successor',new_owner_fence=?,new_lease_correlation=?," + + " incarnation_digest=?,verification_round=?,verification_complete=true" + + " WHERE transfer_id=?", + proof.prior.executorFence().longValueExact() + 1, + "e".repeat(64), + "sha256:" + "a".repeat(64), + UUID.randomUUID(), + id)); + assertThat(proof.originalImage()).isEqualTo(original); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + proof.captureAndFence(id); + proof.verifyPage(id); + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + var installed = proof.install(id); + String completed = proof.transferImage(id); + assertSqlGuard(() -> proof.rawReplaceOwner("different-successor", "f".repeat(64))); + var lateExecution = proof.newControlledExecution(); + proof.retainExactChargeForControlledSeed(lateExecution); + assertThatThrownBy(() -> proof.seedUndeliveredDispatch(lateExecution)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Region dispatch requires the exact current selected owner"); + assertThat(proof.currentOwner()).isEqualTo(installed); + assertThat(proof.transferImage(id)).isEqualTo(completed); + } + } + + @Test + void lostFenceDispatchReplyRecoversOnlyItsPhysicalWitnessAndCannotRecreateIt() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + long deadline = transferDeadline(); + proof.transfers.within( + deadline, + budget -> { + var before = proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), deadline); + var dispatch = proof.transfers.fenceDispatch(item, before); + var competing = proof.transfers.fenceDispatch(item, before); + assertThat(competing.takeSubmission(item)).isNull(); + var owner = proof.capacity(proof.sql).forTransferBudget(budget); + owner.fenceForTransfer(item, dispatch, deadline); + return null; + }); + assertThat(proof.itemImage(id)).contains("\"fence_readback\": null"); + proof.recreateTransferOwners(); + proof.fence(item); + proof.verifyPage(id); + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + var installed = proof.install(id); + String receipt = proof.itemImage(id); + String completion = proof.transferImage(id); + proof.losePhysicalExecution(item.execution()); + assertThatThrownBy(() -> proof.fence(item)).isInstanceOf(IllegalStateException.class); + assertThat(proof.physicalExecutionExists(item.execution())).isFalse(); + assertThat(proof.currentOwner()).isEqualTo(installed); + assertThat(proof.transferImage(id)).isEqualTo(completion); + assertThat(proof.itemImage(id)).isEqualTo(receipt); + } + } + + @Test + void interruptedFenceRetentionRecoversExactTerminalProofWithoutDispatchingAgain() + throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), proof.clock); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + proof + .capacity(proof.sql) + .authorize( + proof.admission, template, account, issuer, proof.execution, transferDeadline()); + try (var physicalCommit = + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + proof.redis, proof.scripts, proof.clock, proof.tags) + .finalizeOriginalNewOnce( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline())) { + UUID id = proof.begin(); + long deadline = transferDeadline(); + var item = + proof.transfers.within(deadline, ignored -> proof.transfers.capture(id).getFirst()); + proof.transfers.within( + deadline, + budget -> { + var before = + proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), deadline); + var dispatch = proof.transfers.fenceDispatch(item, before); + proof + .capacity(proof.sql) + .forTransferBudget(budget) + .fenceForTransfer(item, dispatch, deadline); + return null; + }); + assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED"); + assertThat(proof.itemImage(id)).contains("\"fence_readback\": null"); + UUID retainedDispatch = + proof + .sql + .fetchSingle( + "SELECT fence_dispatch_id FROM game_session_region_owner_transfer_item WHERE" + + " transfer_id=?", + id) + .get("fence_dispatch_id", UUID.class); + assertThat(retainedDispatch).isNotNull(); + String original = proof.originalImage(); + proof.recreateTransferOwners(); + proof.fence(item); + assertThat(proof.itemImage(id)) + .contains(retainedDispatch.toString()) + .doesNotContain("\"fence_readback\": null"); + assertThat(proof.originalImage()).isEqualTo(original); + proof.verifyPage(id); + boolean verified = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(verified).isTrue(); + assertThat(proof.install(id).executorFence()).isGreaterThan(proof.prior.executorFence()); + } + } + } + + @Test + void recreatedRepositoryRetainsLostFenceReplyAndImmutableOriginalReceiptsAndCompletion() + throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + String original = proof.originalImage(); + assertThatThrownBy( + () -> { + proof.fence(item); + // The SQL receipt has committed, but the caller did not receive its result. + throw new IllegalStateException("Controlled lost retained fence reply"); + }) + .hasMessage("Controlled lost retained fence reply"); + String receipt = proof.itemImage(id); + proof.recreateTransferOwners(); + assertThat(proof.begin()).isEqualTo(id); + var replay = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.page(id, -1).getFirst()); + assertThat(replay.execution().canonicalBytes()) + .containsExactly(item.execution().canonicalBytes()); + proof.fence(replay); + assertThat(proof.itemImage(id)).isEqualTo(receipt); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_original_new_capacity_execution SET" + + " selected_owner_id='changed' WHERE execution_digest=?", + proof.execution.digest())); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer SET intent_digest=? WHERE" + + " transfer_id=?", + "sha256:" + "f".repeat(64), + id)); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer_item SET canonical_execution=? WHERE" + + " transfer_id=?", + "changed-original".getBytes(StandardCharsets.UTF_8), + id)); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer_item SET fence_readback=? WHERE" + + " transfer_id=?", + "changed-readback".getBytes(StandardCharsets.UTF_8), + id)); + for (String table : + List.of( + "game_session_original_new_capacity_execution", + "game_session_region_owner_transfer", + "game_session_region_owner_transfer_item")) { + assertSqlGuard(() -> proof.sql.execute("DELETE FROM " + table)); + assertSqlGuard(() -> proof.sql.execute("TRUNCATE TABLE " + table + " CASCADE")); + } + assertThat(proof.originalImage()).isEqualTo(original); + assertThat(proof.itemImage(id)).isEqualTo(receipt); + proof.verifyPage(id); + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + var installed = proof.install(id); + String completion = proof.transferImage(id); + proof.recreateTransferOwners(); + assertThat(proof.transfers.readCurrent(id, 0).controlState()).isEqualTo("COMPLETED"); + assertThat(proof.transfers.readCurrent(id, 0).completionDigest()).isNotBlank(); + assertThatThrownBy( + () -> + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id))) + .isInstanceOf(IllegalStateException.class); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer SET new_owner_id='changed-successor'" + + " WHERE transfer_id=?", + id)); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer_item SET verified_round=? WHERE" + + " transfer_id=?", + UUID.randomUUID(), + id)); + assertThat(proof.transferImage(id)).isEqualTo(completion); + assertThat(proof.originalImage()).isEqualTo(original); + assertThat(proof.currentOwner()).isEqualTo(installed); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityTransferCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java similarity index 58% rename from services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityTransferCustodyIntegrationTest.java rename to services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java index e574e799f5..5ee11e2538 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityTransferCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java @@ -13,27 +13,50 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; +import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; 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; @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @TestInstance(TestInstance.Lifecycle.PER_CLASS) -class CanonicalGameplayOriginalNewCapacityTransferCustodyIntegrationTest +class CanonicalGameplayRegionTransferSerializationIntegrationTest extends CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Override + PostgreSQLContainer postgresContainer() { + return POSTGRES; + } + + @Override + GenericContainer redisContainer() { + return REDIS; + } + @Test void ownerInstallUsesFreshReadCommittedSnapshotAfterWaitingForAdvisoryLock() throws Exception { try (var proof = new TransferSqlProof(); ExecutorService executor = Executors.newSingleThreadExecutor(); var blocker = java.sql.DriverManager.getConnection( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + postgresContainer().getJdbcUrl(), + postgresContainer().getUsername(), + postgresContainer().getPassword())) { var dispatched = proof.newControlledExecution(); String tag = CanonicalGameplayRegionRedisKeys.tenantRegionTag( @@ -60,13 +83,13 @@ public java.sql.Connection getConnection() throws java.sql.SQLException { return connection; } }; - repeatableReadSource.setDriverClassName(POSTGRES.getDriverClassName()); - String url = POSTGRES.getJdbcUrl(); + repeatableReadSource.setDriverClassName(postgresContainer().getDriverClassName()); + String url = postgresContainer().getJdbcUrl(); String schema = proof.sql.fetchSingle("SELECT current_schema()").get(0, String.class); repeatableReadSource.setUrl( url + (url.contains("?") ? "&" : "?") + "currentSchema=" + schema); - repeatableReadSource.setUsername(POSTGRES.getUsername()); - repeatableReadSource.setPassword(POSTGRES.getPassword()); + repeatableReadSource.setUsername(postgresContainer().getUsername()); + repeatableReadSource.setPassword(postgresContainer().getPassword()); var repeatableReadRepository = new CanonicalGameplayRegionRuntimeStatusRepository( DSL.using(repeatableReadSource, SQLDialect.POSTGRES)); @@ -103,99 +126,133 @@ public java.sql.Connection getConnection() throws java.sql.SQLException { } @Test - void retainedDenialReleasesTheLastSlotAndCannotRaceAStoredDispatch() throws Exception { - try (var proof = new TransferSqlProof(1, 1_048_576L, 3)) { - var original = proof.execution; - var later = proof.newControlledExecution(); - assertThatThrownBy(() -> proof.precharge(later)).isInstanceOf(IllegalStateException.class); - var denial = UUID.randomUUID(); - proof.settle(original, denial); - proof.settle(original, denial); - assertThatThrownBy(() -> proof.settle(original, UUID.randomUUID())) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(() -> proof.insertExecution(original, "INSTALL_DISPATCHED", null)) - .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining("Exact retained capacity evidence charge required"); - - proof.seedUndeliveredDispatch(later); - assertThatThrownBy(() -> proof.settle(later, UUID.randomUUID())) - .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining("Execution custody prevents capacity evidence settlement"); - assertThat(proof.executionState(later)).isEqualTo("INSTALL_DISPATCHED"); - assertThat(proof.executionState(original)).isNull(); - assertThat(proof.physicalExecutionExists(original)).isFalse(); + void actualAuthorizationHoldingRegionRowMakesFreezeWaitAndRetainsThatOriginal() throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), Clock.systemUTC()); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution); + var gate = new RegionRowLockGate(); + ExecutorService executor = Executors.newFixedThreadPool(2)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + Future authorization = + executor.submit( + () -> + proof + .capacity(gate.attach(proof.sql)) + .authorize( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline())); + gate.awaitLock(); + Future freeze = + executor.submit( + () -> + proof.transfers.within( + transferDeadline(), + ignored -> proof.transfers.begin(proof.scope, proof.prior))); + try { + assertDatabaseWaitsFor(proof.sql, gate.backendPid()); + assertThat(freeze.isDone()).isFalse(); + } finally { + gate.release(); + } + authorization.get(10, TimeUnit.SECONDS); + UUID id = freeze.get(10, TimeUnit.SECONDS); + assertThat(id).isNotNull(); + assertThat(proof.executionState(proof.execution)).isEqualTo("AUTHORIZED"); + List captured = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertThat(captured) + .extracting(item -> item.execution().digest()) + .containsExactly(proof.execution.digest()); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); } } @Test - void retainedDenialHistoryRemainsBoundedIndependentlyOfActiveSlots() throws Exception { - try (var proof = new TransferSqlProof(1, 1_048_576L, 2)) { - proof.settle(proof.execution, UUID.randomUUID()); - var next = proof.newControlledExecution(); - proof.precharge(next); - proof.settle(next, UUID.randomUUID()); - assertThatThrownBy(() -> proof.precharge(proof.newControlledExecution())) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Original NEW capacity evidence budget is unavailable"); - } - } + void actualFreezeUsesReadCommittedWithRepeatableReadDatasourceAfterAuthorizationWaits() + throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), Clock.systemUTC()); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution); + var gate = new RegionRowLockGate(); + ExecutorService executor = Executors.newFixedThreadPool(2)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + Future authorization = + executor.submit( + () -> + proof + .capacity(gate.attach(proof.sql)) + .authorize( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline())); + gate.awaitLock(); - @Test - void postgresSerializesTheLastEvidenceChargeAcrossConcurrentAttempts() throws Exception { - try (var proof = withCapacityBudget(2, 2_097_152L); - var callers = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) { - var first = proof.newControlledExecution(); - var second = proof.newControlledExecution(); - var ready = new java.util.concurrent.CountDownLatch(2); - var start = new java.util.concurrent.CountDownLatch(1); - var assignment = - proof.tags.assignmentForTransition(proof.admission.candidate().bindingDecisionId()); - var selected = - new CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner( - proof.execution.selectedOwnerId(), proof.execution.selectedOwnerFence()); - java.util.function.Function< - OriginalNewCapacityExecution, java.util.concurrent.Future> - compete = - attempt -> - callers.submit( - () -> { - ready.countDown(); - if (!start.await(2, java.util.concurrent.TimeUnit.SECONDS)) { - throw new IllegalStateException("Concurrent proof start unavailable"); - } - try { - proof.sql.transaction( - configuration -> - CanonicalGameplayCapacityEvidenceBudget.precharge( - DSL.using(configuration), - attempt.request(), - attempt.candidateDigest(), - selected, - assignment.tenantGameplayTag())); - return true; - } catch (IllegalStateException refused) { - assertThat(refused) - .hasMessage("Original NEW capacity evidence budget is unavailable"); - return false; - } - }); - var firstResult = compete.apply(first); - var secondResult = compete.apply(second); - assertThat(ready.await(2, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); - start.countDown(); - assertThat( - List.of( - firstResult.get(5, java.util.concurrent.TimeUnit.SECONDS), - secondResult.get(5, java.util.concurrent.TimeUnit.SECONDS))) - .containsExactlyInAnyOrder(true, false); + var repeatableReadSource = + new DriverManagerDataSource() { + @Override + public java.sql.Connection getConnection() throws java.sql.SQLException { + java.sql.Connection connection = super.getConnection(); + connection.setTransactionIsolation(java.sql.Connection.TRANSACTION_REPEATABLE_READ); + return connection; + } + }; + repeatableReadSource.setDriverClassName(postgresContainer().getDriverClassName()); + String url = postgresContainer().getJdbcUrl(); + String schema = proof.sql.fetchSingle("SELECT current_schema()").get(0, String.class); + repeatableReadSource.setUrl( + url + (url.contains("?") ? "&" : "?") + "currentSchema=" + schema); + repeatableReadSource.setUsername(postgresContainer().getUsername()); + repeatableReadSource.setPassword(postgresContainer().getPassword()); + var repeatableReadTransfers = + new CanonicalGameplayRegionOwnerTransferRepository( + DSL.using(repeatableReadSource, SQLDialect.POSTGRES), proof.clock, proof.tags); + Future freeze = + executor.submit( + () -> + repeatableReadTransfers.within( + transferDeadline(), + ignored -> repeatableReadTransfers.begin(proof.scope, proof.prior))); + try { + assertDatabaseWaitsFor(proof.sql, gate.backendPid()); + assertThat(freeze.isDone()).isFalse(); + } finally { + gate.release(); + } + + authorization.get(10, TimeUnit.SECONDS); + UUID transferId = freeze.get(10, TimeUnit.SECONDS); + assertThat(transferId).isNotNull(); + assertThat(proof.executionState(proof.execution)).isEqualTo("AUTHORIZED"); assertThat( proof .sql .fetchSingle( - "SELECT count(*) FROM game_session_capacity_evidence_charge WHERE tenant_id=?", - assignment.tenantId()) - .get(0, Long.class)) - .isEqualTo(2L); + "SELECT state FROM game_session_region_owner_transfer WHERE transfer_id=?", + transferId) + .get(0, String.class)) + .isEqualTo("FROZEN"); + List captured = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(transferId)); + assertThat(captured) + .extracting(item -> item.execution().digest()) + .containsExactly(proof.execution.digest()); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); } } @@ -214,23 +271,12 @@ void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch( proof.seedUndeliveredDispatch(seeded); var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + var freezing = proof.transfers(gate.attach(proof.sql)); Future freeze = executor.submit( () -> - gate.attach(proof.sql) - .transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); - transaction.fetchSingle( - "SELECT 1 FROM game_session_region_runtime_status" - + " WHERE tenant_id=? AND game_instance_id=? AND region_id=?" - + " FOR UPDATE", - proof.scope.tenantId(), - proof.scope.gameInstanceId(), - proof.scope.regionId()); - return proof.insertRawFrozenTransfer(transaction); - })); + freezing.within( + transferDeadline(), ignored -> freezing.begin(proof.scope, proof.prior))); gate.awaitLock(); Future refused = executor.submit( @@ -263,8 +309,11 @@ void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch( assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); // The INSERT trigger independently takes the same row lock and rejects raw late dispatch. assertSqlGuard(() -> proof.seedUndeliveredDispatch(proof.execution)); - proof.insertRawTransferItem(proof.sql, id, 0, seeded); - assertThat(proof.transferExecutionDigests(id)).containsExactly(seeded.digest()); + List captured = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertThat(captured) + .extracting(item -> item.execution().digest()) + .containsExactly(seeded.digest()); assertThat(proof.currentOwner()).isEqualTo(proof.prior); } } @@ -289,7 +338,9 @@ void rawFrozenTransferInsertLocksExactCurrentRegionBeforeLateCapacityDispatch() () -> { try (var connection = java.sql.DriverManager.getConnection( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + postgresContainer().getJdbcUrl(), + postgresContainer().getUsername(), + postgresContainer().getPassword())) { connection.setSchema(schema); connection.setAutoCommit(false); DSLContext rawSql = DSL.using(connection, SQLDialect.POSTGRES); @@ -375,7 +426,9 @@ void rawFrozenTransferInsertWaitsForActualDispatchAndRetainsIt() throws Exceptio () -> { try (var connection = java.sql.DriverManager.getConnection( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + postgresContainer().getJdbcUrl(), + postgresContainer().getUsername(), + postgresContainer().getPassword())) { connection.setSchema(schema); connection.setAutoCommit(false); DSLContext rawSql = DSL.using(connection, SQLDialect.POSTGRES); @@ -394,8 +447,11 @@ void rawFrozenTransferInsertWaitsForActualDispatchAndRetainsIt() throws Exceptio authorization.get(10, TimeUnit.SECONDS); UUID transferId = freeze.get(10, TimeUnit.SECONDS); assertThat(proof.executionState(proof.execution)).isEqualTo("AUTHORIZED"); - proof.insertRawTransferItem(proof.sql, transferId, 0); - assertThat(proof.transferExecutionDigests(transferId)) + var captured = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(transferId)); + assertThat(captured) + .extracting(item -> item.execution().digest()) .containsExactly(proof.execution.digest()); assertThat(proof.currentOwner()).isEqualTo(proof.prior); } @@ -434,7 +490,7 @@ void rawFrozenInsertAndCapacityDispatchRejectRepeatableRead() throws Exception { failure -> { assertThat(failure.getSQLState()).isEqualTo("23514"); assertThat(failure.getMessage()) - .contains("Region dispatch requires READ COMMITTED owner fencing"); + .contains("requires READ COMMITTED"); }); assertThat(proof.executionState(proof.execution)).isNull(); assertThat( @@ -452,7 +508,9 @@ void rawOwnerReplacementRejectsSnapshotThatPredatesCommittedDispatch() throws Ex String schema = proof.sql.fetchSingle("SELECT current_schema()").get(0, String.class); try (var connection = java.sql.DriverManager.getConnection( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + postgresContainer().getJdbcUrl(), + postgresContainer().getUsername(), + postgresContainer().getPassword())) { connection.setSchema(schema); connection.setAutoCommit(false); DSLContext tx = DSL.using(connection, SQLDialect.POSTGRES); @@ -487,7 +545,7 @@ void rawTransferChildInsertSerializesWithCompletionAcrossCurrentAndOlderSnapshot try (var proof = new TransferSqlProof(); ExecutorService executor = Executors.newFixedThreadPool(2)) { proof.seedUndeliveredDispatch(proof.execution); - UUID transferId = proof.insertRawFrozenTransfer(proof.sql); + UUID transferId = proof.begin(); var inserted = new CountDownLatch(1); var release = new CountDownLatch(1); var blockerPid = new AtomicInteger(); @@ -497,7 +555,9 @@ void rawTransferChildInsertSerializesWithCompletionAcrossCurrentAndOlderSnapshot () -> { try (var connection = java.sql.DriverManager.getConnection( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + postgresContainer().getJdbcUrl(), + postgresContainer().getUsername(), + postgresContainer().getPassword())) { connection.setSchema(schema); connection.setAutoCommit(false); DSLContext rawSql = DSL.using(connection, SQLDialect.POSTGRES); @@ -524,10 +584,12 @@ void rawTransferChildInsertSerializesWithCompletionAcrossCurrentAndOlderSnapshot DSLContext tx = DSL.using(configuration); tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); tx.fetchSingle( - "SELECT state FROM game_session_region_owner_transfer WHERE transfer_id=?", + "SELECT state FROM game_session_region_owner_transfer WHERE" + + " transfer_id=?", transferId); tx.execute( - "UPDATE game_session_region_owner_transfer SET state='COMPLETED'," + "UPDATE game_session_region_owner_transfer SET" + + " state='COMPLETED'," + "new_owner_id='sql-proof-successor',new_owner_fence=?,new_lease_correlation=?" + " WHERE transfer_id=?", proof.prior.executorFence().longValueExact() + 1, @@ -563,7 +625,8 @@ void rawTransferChildInsertSerializesWithCompletionAcrossCurrentAndOlderSnapshot proof .sql .fetchSingle( - "SELECT count(*) FROM game_session_region_owner_transfer_item WHERE transfer_id=?", + "SELECT count(*) FROM game_session_region_owner_transfer_item WHERE" + + " transfer_id=?", transferId) .get(0, Long.class)) .isEqualTo(1L); @@ -609,6 +672,85 @@ void acknowledgedBridgeRetryWaitsBeforeTransitionWhileAuthorizationOwnsRegion() } } + @Test + void frozenContinuationWaitsBeforeRegionWhileAcknowledgedBridgeOwnsInventory() throws Exception { + try (var gate = new InventoryRowLockGate(); + var proof = new TransferSqlProof(gate); + ExecutorService executor = Executors.newFixedThreadPool(2)) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var captured = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertThat(captured).hasSize(1); + var original = + proof.transfers.within( + transferDeadline(), + ignored -> proof.transfers.frozenOriginal(proof.execution.transitionId())); + String before = proof.transferImage(id); + gate.arm(); + Future replay = executor.submit(proof::replayBridge); + gate.awaitLock(); + Future continuation = + executor.submit( + () -> + proof.transfers.within( + transferDeadline(), + ignored -> { + proof.transfers.requireFrozenOriginal(original, proof.scope, proof.prior); + return null; + })); + try { + assertDatabaseWaitsFor(proof.sql, gate.backendPid()); + assertThat(continuation.isDone()).isFalse(); + } finally { + gate.release(); + } + replay.get(10, TimeUnit.SECONDS); + continuation.get(10, TimeUnit.SECONDS); + assertThat(proof.transferImage(id)).isEqualTo(before); + assertThat(proof.executionState(proof.execution)).isEqualTo("INSTALL_DISPATCHED"); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + } + } + + @Test + void competingTransferCreatorsAndLostBeginReplyKeepOneOriginalIntent() throws Exception { + try (var proof = new TransferSqlProof(); + ExecutorService executor = Executors.newFixedThreadPool(2)) { + proof.seedUndeliveredDispatch(proof.execution); + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var other = proof.transfers(proof.sql); + Future first = + executor.submit(() -> beginAfterBarrier(proof, proof.transfers, ready, start)); + Future second = executor.submit(() -> beginAfterBarrier(proof, other, ready, start)); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + UUID retained = first.get(10, TimeUnit.SECONDS); + assertThat(second.get(10, TimeUnit.SECONDS)).isEqualTo(retained); + String original = proof.transferImage(retained); + assertThatThrownBy( + () -> { + other.within(transferDeadline(), ignored -> other.begin(proof.scope, proof.prior)); + throw new IllegalStateException( + "Controlled lost begin reply after committed readback"); + }) + .hasMessage("Controlled lost begin reply after committed readback"); + var recreated = proof.transfers(proof.sql); + UUID replayed = + recreated.within( + transferDeadline(), ignored -> recreated.begin(proof.scope, proof.prior)); + assertThat(replayed).isEqualTo(retained); + assertThat(proof.transferImage(retained)).isEqualTo(original); + assertThat( + proof + .sql + .fetchSingle("SELECT count(*) FROM game_session_region_owner_transfer") + .get(0, Long.class)) + .isEqualTo(1L); + } + } + @Test void postgresSerializesTheLastTransferParentAcrossRegionsOfTheSameTenant() throws Exception { try (var proof = withTransferHistoryBudget(1, 2); @@ -645,7 +787,9 @@ void postgresSerializesTheLastTransferParentAcrossRegionsOfTheSameTenant() throw () -> { try (var connection = java.sql.DriverManager.getConnection( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + postgresContainer().getJdbcUrl(), + postgresContainer().getUsername(), + postgresContainer().getPassword())) { connection.setSchema(schema); connection.setAutoCommit(false); DSLContext rawSql = DSL.using(connection, SQLDialect.POSTGRES); @@ -689,243 +833,4 @@ void postgresSerializesTheLastTransferParentAcrossRegionsOfTheSameTenant() throw assertThat(status.find(otherScope)).contains(otherPrior); } } - - @Test - void fullTransferItemBudgetAllowsReservedCompletionButRefusesTheNextFreeze() throws Exception { - try (var proof = withTransferHistoryBudget(2, 1)) { - proof.seedUndeliveredDispatch(proof.execution); - String originalExecution = proof.originalImage(); - UUID id = proof.insertRawFrozenTransfer(proof.sql); - assertThat(id).isNotNull(); - assertThat( - proof - .sql - .fetchSingle( - "SELECT reserved_execution_items FROM game_session_region_owner_transfer WHERE transfer_id=?", - id) - .get(0, Integer.class)) - .isEqualTo(1); - assertThat(proof.itemImage(id)).isEqualTo("[]"); - assertTransferHistoryGuard( - () -> proof.insertRawTransferItem(proof.sql, id, 1), - "Transfer item is outside its reserved inventory"); - assertThat(proof.itemImage(id)).isEqualTo("[]"); - proof.insertRawTransferItem(proof.sql, id, 0); - assertThat(proof.transferExecutionDigests(id)).containsExactly(proof.execution.digest()); - proof.retainControlledTransferReceipt(id); - var installed = proof.rawCompleteAndInstall(id, "sql-proof-successor", "e".repeat(64), false); - String completed = proof.transferImage(id); - String items = proof.itemImage(id); - assertTransferHistoryGuard( - () -> proof.insertRawFrozenTransfer(proof.sql, proof.scope, installed), - "Transfer history cannot reserve its full execution inventory"); - assertThat(proof.originalImage()).isEqualTo(originalExecution); - assertThat(proof.currentOwner()).isEqualTo(installed); - assertThat(proof.transferImage(id)).isEqualTo(completed); - assertThat(proof.itemImage(id)).isEqualTo(items); - } - } - - @Test - void capturedOriginalThatBecomesTerminalStillRequiresQualifiedTransferCompletion() - throws Exception { - try (var proof = new TransferSqlProof(); - var credential = - new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( - proof.admission.candidate(), proof.clock); - var raw = credential.template(); - var template = raw.bindCapacityExecution(proof.execution)) { - var account = proof.controlledAccountOpen(); - var issuer = proof.issuerOpen(); - proof - .capacity(proof.sql) - .authorize( - proof.admission, template, account, issuer, proof.execution, transferDeadline()); - try (var readback = - new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( - proof.redis, proof.scripts, proof.clock, proof.tags) - .finalizeOriginalNewOnce( - proof.admission, - template, - account, - issuer, - proof.execution, - transferDeadline())) { - UUID id = proof.insertRawFrozenTransfer(proof.sql); - proof.insertRawTransferItem(proof.sql, id, 0); - assertThat(proof.transferExecutionDigests(id)).containsExactly(proof.execution.digest()); - new CanonicalGameplayBindingInventoryRepository(proof.sql) - .commitOriginalNewFinalAdmission(readback); - assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED"); - String frozen = proof.transferImage(id); - String inventory = proof.itemImage(id); - assertThatThrownBy( - () -> proof.rawCompleteAndInstall(id, "sql-proof-successor", "e".repeat(64), true)) - .rootCause() - .isInstanceOfSatisfying( - org.postgresql.util.PSQLException.class, - failure -> { - assertThat(failure.getSQLState()).isEqualTo("23514"); - assertThat(failure.getMessage()) - .contains( - "Captured region transfer item lacks its full exact current receipt"); - }); - assertThat(proof.currentOwner()).isEqualTo(proof.prior); - assertThat(proof.transferImage(id)).isEqualTo(frozen); - assertThat(proof.itemImage(id)).isEqualTo(inventory); - var status = new CanonicalGameplayRegionRuntimeStatusRepository(proof.sql); - - assertThatThrownBy( - () -> - status.installOwner( - proof.scope, - proof.prior.regionEpoch(), - proof.prior, - "e".repeat(64), - "game-session-service", - "sql-proof-successor", - proof.clock.instant())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("region ownership is unavailable"); - assertThat(proof.currentOwner()).isEqualTo(proof.prior); - assertThat(proof.transferImage(id)).isEqualTo(frozen); - assertThat(proof.itemImage(id)).isEqualTo(inventory); - } - } - } - - @Test - void originalCapacityExecutionRefusesForgedInitialAuthorizationAndTerminalEvidence() - throws Exception { - try (var proof = new TransferSqlProof()) { - byte[] forgedReadback = {1}; - for (String status : List.of("AUTHORIZED", "COMMITTED", "CLOSED", "INSTALL_DISPATCHED")) { - byte[] readback = "AUTHORIZED".equals(status) ? null : forgedReadback; - assertThatThrownBy(() -> proof.insertExecution(proof.execution, status, readback)) - .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining( - "Original NEW capacity execution cannot start with an authorization or terminal proof"); - } - assertThat(proof.executionState(proof.execution)).isNull(); - assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); - assertThat(proof.currentOwner()).isEqualTo(proof.prior); - - proof.seedUndeliveredDispatch(proof.execution); - assertThat(proof.executionState(proof.execution)).isEqualTo("INSTALL_DISPATCHED"); - assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); - } - } - - @Test - void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throws Exception { - try (var proof = new TransferSqlProof()) { - assertThat(proof.currentOwner()).isEqualTo(proof.prior); - proof.seedUndeliveredDispatch(proof.execution); - String original = proof.originalImage(); - assertSqlGuard(() -> proof.rawReplaceOwner("unretained-successor", "e".repeat(64))); - String forgedOwner = "forged-successor"; - String forgedLease = "e".repeat(64); - long forgedFence = - proof - .sql - .fetchSingle("SELECT nextval('game_session_region_executor_fence_seq')") - .get(0, Long.class); - for (String state : List.of("COMPLETED", "FROZEN")) { - boolean completed = "COMPLETED".equals(state); - assertThatThrownBy( - () -> - proof.sql.execute( - "INSERT INTO game_session_region_owner_transfer" - + " (transfer_id,tenant_id,game_instance_id,region_id,region_epoch,old_owner_id,old_owner_fence," - + " old_lease_correlation,source_digest,intent_digest,state,incarnation_digest,verification_round," - + " verification_cursor,verification_complete,new_owner_id,new_owner_fence,new_lease_correlation)" - + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,true,?,?,?)", - UUID.randomUUID(), - proof.scope.tenantId(), - proof.scope.gameInstanceId(), - proof.scope.regionId(), - proof.prior.regionEpoch(), - proof.prior.ownerInstanceId(), - proof.prior.executorFence().longValueExact(), - proof.prior.leaseTokenCorrelation(), - "sha256:" + "b".repeat(64), - "sha256:" + "c".repeat(64), - state, - "sha256:" + "a".repeat(64), - UUID.randomUUID(), - 0L, - completed ? forgedOwner : null, - completed ? forgedFence : null, - completed ? forgedLease : null)) - .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining("Region transfer must start as a clean frozen intent"); - } - assertSqlGuard( - () -> - proof.sql.execute( - "UPDATE game_session_region_runtime_status SET owner_instance_id=?,executor_fence=?,lease_token_correlation=?" - + " WHERE tenant_id=? AND game_instance_id=? AND region_id=?", - forgedOwner, - forgedFence, - forgedLease, - proof.scope.tenantId(), - proof.scope.gameInstanceId(), - proof.scope.regionId())); - assertThat(proof.currentOwner()).isEqualTo(proof.prior); - UUID id = proof.insertRawFrozenTransfer(proof.sql); - assertSqlGuard(() -> proof.rawReplaceOwner("frozen-successor", "e".repeat(64))); - proof.insertRawTransferItem(proof.sql, id, 0); - assertSqlGuard( - () -> - proof.sql.execute( - "UPDATE game_session_region_owner_transfer SET state='COMPLETED'," - + " new_owner_id='forged-successor',new_owner_fence=?,new_lease_correlation=?," - + " incarnation_digest=?,verification_round=?,verification_complete=true WHERE transfer_id=?", - proof.prior.executorFence().longValueExact() + 1, - "e".repeat(64), - "sha256:" + "a".repeat(64), - UUID.randomUUID(), - id)); - assertThat(proof.originalImage()).isEqualTo(original); - assertThat(proof.currentOwner()).isEqualTo(proof.prior); - assertThat(proof.transferExecutionDigests(id)).containsExactly(proof.execution.digest()); - proof.sql.execute( - "UPDATE game_session_region_owner_transfer_item" - + " SET fence_dispatch_id=?,fence_dispatch_incarnation=? WHERE transfer_id=?", - UUID.randomUUID(), - "sha256:" + "a".repeat(64), - id); - String dispatched = proof.itemImage(id); - assertSqlGuard( - () -> - proof.sql.execute( - "UPDATE game_session_region_owner_transfer_item SET fence_dispatch_id=?" - + " WHERE transfer_id=?", - UUID.randomUUID(), - id)); - assertThatThrownBy( - () -> proof.rawCompleteAndInstall(id, "sql-proof-successor", "e".repeat(64), true)) - .rootCause() - .isInstanceOfSatisfying( - org.postgresql.util.PSQLException.class, - failure -> { - assertThat(failure.getSQLState()).isEqualTo("23514"); - assertThat(failure.getMessage()) - .contains("Region transfer requires settled fence dispatch custody"); - }); - assertThat(proof.itemImage(id)).isEqualTo(dispatched); - proof.retainControlledTransferReceipt(id); - var installed = proof.rawCompleteAndInstall(id, "sql-proof-successor", "e".repeat(64), false); - String completed = proof.transferImage(id); - assertSqlGuard(() -> proof.rawReplaceOwner("different-successor", "f".repeat(64))); - var lateExecution = proof.newControlledExecution(); - proof.retainExactChargeForControlledSeed(lateExecution); - assertThatThrownBy(() -> proof.seedUndeliveredDispatch(lateExecution)) - .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining("Region dispatch requires the exact current selected owner"); - assertThat(proof.currentOwner()).isEqualTo(installed); - assertThat(proof.transferImage(id)).isEqualTo(completed); - assertThat(proof.originalImage()).isEqualTo(original); - } - } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java index 6633a17968..91a9080419 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java @@ -11,6 +11,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -50,6 +51,7 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; import org.jooq.ConnectionProvider; @@ -59,6 +61,7 @@ import org.jooq.impl.DefaultConfiguration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.test.util.ReflectionTestUtils; /** Controlled acquisition/driver behavior, not database or owner-evidence qualification. */ @@ -246,7 +249,6 @@ void preparedTimelineRetainsAdmissionThroughRejectedCallersAsyncClose() throws E verify(connection, timeout(1000)).closeAsync(); assertPermitRemainsHeld(operations, operationMaximum); assertPermitRemainsHeld(background, backgroundMaximum); - verify(commands, never()).evalsha(any(), any(), any(), any()); close.complete(null); assertThat(operations.tryAcquire(operationMaximum, 2, TimeUnit.SECONDS)).isTrue(); @@ -254,7 +256,10 @@ void preparedTimelineRetainsAdmissionThroughRejectedCallersAsyncClose() throws E assertThat(background.tryAcquire(backgroundMaximum, 2, TimeUnit.SECONDS)).isTrue(); background.release(backgroundMaximum); verify(connection, org.mockito.Mockito.times(1)).closeAsync(); - verify(commands, never()).evalsha(any(), any(), any(), any()); + ArgumentCaptor arguments = ArgumentCaptor.forClass(byte[][].class); + verify(commands, times(1)).evalsha(any(), any(), any(byte[][].class), arguments.capture()); + assertThat(arguments.getValue()[1]) + .isEqualTo("PROBE".getBytes(java.nio.charset.StandardCharsets.US_ASCII)); } finally { if (prepared != null) prepared.close(); close.complete(null); @@ -558,6 +563,152 @@ void actualOwnerReadReturnsAtDeadlineAndLateAcquisitionNeverExecutes() throws Ex } } + @Test + void actualTransferCommittedReadBoundsAcquisitionAndCannotExecuteAfterItsDeadline() + throws Exception { + ConnectionProvider provider = mock(); + Connection connection = mock(); + CountDownLatch entered = new CountDownLatch(1), release = new CountDownLatch(1); + when(provider.acquire()) + .thenAnswer( + invocation -> { + entered.countDown(); + awaitUninterruptibly(release); + return connection; + }); + var inventory = new CanonicalGameplayBindingInventoryRepository(source(provider)); + var candidate = mock(CanonicalGameplayOriginalNewCandidate.class); + UUID transitionId = UUID.randomUUID(); + when(candidate.bindingDecisionId()).thenReturn(transitionId); + long started = System.nanoTime(); + try { + assertThatThrownBy( + () -> + inventory.withinTransferRead( + CLOCK, + CLOCK.millis() + 1000, + scoped -> scoped.readRegionTransferCommittedSource(transitionId, candidate))) + .isInstanceOf(IllegalStateException.class); + assertThat(entered.await(1, TimeUnit.SECONDS)).isTrue(); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2500); + verifyNoInteractions(connection); + } finally { + release.countDown(); + verify(provider, timeout(2000)).release(connection); + verifyNoInteractions(connection); + } + } + + @Test + void handoffStatusReadBoundsAcquisitionAndCannotExecuteAfterItsDeadline() throws Exception { + ConnectionProvider provider = mock(); + Connection connection = mock(); + CountDownLatch entered = new CountDownLatch(1), release = new CountDownLatch(1); + when(provider.acquire()) + .thenAnswer( + invocation -> { + entered.countDown(); + awaitUninterruptibly(release); + return connection; + }); + var dsl = source(provider); + var transferRepository = + new CanonicalGameplayRegionOwnerTransferRepository( + dsl, CLOCK, mock(CanonicalGameplayTenantGameplayTagRepository.class)); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + dsl, + CLOCK, + transferRepository, + mock(CanonicalGameplayOriginalNewCapacityExecutionOwner.class), + mock(CanonicalGameplayProtectedIncarnationReceiver.class)); + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.randomUUID(), + "prod", + tenantId, + "world", + gameInstanceId, + UUID.randomUUID(), + "SHARED", + true, + "budget-test", + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + var regionSource = + new CanonicalGameplayRegionRuntimeStatusRepository.Source( + tenantId, + gameInstanceId, + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + 0L, + lifecycleRequest, + UUID.randomUUID(), + "d".repeat(64), + "sha256:" + "e".repeat(64)); + + try { + assertThatThrownBy( + () -> + transfer.withStatusRepository( + CLOCK.millis() + 1000, + statusRepository -> statusRepository.findTimelinePreparation(regionSource))) + .isInstanceOf(IllegalStateException.class); + assertThat(entered.await(1, TimeUnit.SECONDS)).isTrue(); + verifyNoInteractions(connection); + } finally { + release.countDown(); + verify(provider, timeout(2000)).release(connection); + verifyNoInteractions(connection); + } + } + + @Test + void transferReadDerivesItsOwnTransactionProviderAndKeepsTheOriginalAbsoluteDeadline() { + ConnectionProvider provider = mock(); + Connection connection = mock(); + when(provider.acquire()).thenReturn(connection); + try { + when(connection.getAutoCommit()).thenReturn(true); + } catch (java.sql.SQLException failure) { + throw new AssertionError(failure); + } + var original = source(provider); + var sharedTransactions = mock(org.jooq.TransactionProvider.class); + original.configuration().set(sharedTransactions); + var inventory = new CanonicalGameplayBindingInventoryRepository(original); + AtomicLong wall = new AtomicLong(CLOCK.millis()); + Clock clock = mock(); + when(clock.millis()).thenAnswer(ignored -> wall.get()); + long deadline = wall.get() + 2000; + boolean read = + inventory.withinTransferRead( + clock, + deadline, + scoped -> { + var sql = (DSLContext) ReflectionTestUtils.getField(scoped, "dsl"); + assertThat(sql).isNotNull(); + assertThat(sql.configuration().connectionProvider()).isNotSameAs(provider); + assertThat(sql.configuration().transactionProvider()).isNotSameAs(sharedTransactions); + return sql.transactionResult( + transaction -> DSL.using(transaction).connectionResult(owned -> Boolean.TRUE)); + }); + assertThat(read).isTrue(); + verify(provider).acquire(); + verify(provider).release(connection); + verifyNoInteractions(sharedTransactions); + wall.set(deadline); + assertThatThrownBy(() -> inventory.withinTransferRead(clock, deadline, scoped -> Boolean.TRUE)) + .isInstanceOf(IllegalStateException.class); + verify(provider, org.mockito.Mockito.times(1)).acquire(); + } + @Test void activeStatementCancellationFinishesBeforePoolReturn() throws Exception { ConnectionProvider provider = mock(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java new file mode 100644 index 0000000000..66026a2fe4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java @@ -0,0 +1,984 @@ +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.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +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.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Real RSA verification with controlled local signing custody, not deployed attestor proof. */ +class CanonicalGameplayRegionOwnerTransferObservationReceiverTest { + private static final String SCHEMA = "firemud.gs.protected-region-owner-transfer-read/v1"; + private static final String KEY_ID = "controlled-transfer-key"; + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final String OTHER_DIGEST = "sha256:" + "e".repeat(64); + private static final String TRANSFER_INTENT_DIGEST = "sha256:" + "1".repeat(64); + private static final String FROZEN_SOURCE_DIGEST = "sha256:" + "2".repeat(64); + private static final String EXECUTION_DIGEST = "sha256:" + "3".repeat(64); + private static final String CANDIDATE_DIGEST = "sha256:" + "4".repeat(64); + private static final long NOW = 1_794_355_200_000L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final KeyPair KEYS = controlledKeys(); + + @Test + void verifiesExactFrozenItemTwiceWithRealSignatureAndCapsAtOperationDeadline() { + var fixture = new Fixture(); + var proof = fixture.observe(NOW + 500L); + + assertThat(proof.ownerKind()) + .isEqualTo(CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER); + assertThat(proof.regionOwnerTransferContext()).isSameAs(fixture.original); + assertThat(fixture.original.transferIntentDigest()).isEqualTo(TRANSFER_INTENT_DIGEST); + assertThat(fixture.original.frozenSourceDigest()).isEqualTo(FROZEN_SOURCE_DIGEST); + assertThat(fixture.original.executionDigest()).isEqualTo(EXECUTION_DIGEST); + assertThat(fixture.original.candidateDigest()).isEqualTo(CANDIDATE_DIGEST); + assertThat(proof.operationId()).isEqualTo(fixture.original.transferId()); + assertThat(proof.requestId()).isEqualTo(fixture.original.requestId()); + assertThat(proof.accountId()).isEqualTo(fixture.original.accountId()); + assertThat(proof.targetOrdinal()).isEqualTo(fixture.original.targetOrdinal()); + assertThat(proof.tenantId()).isEqualTo(fixture.original.tenantId()); + assertThat(proof.playableStateNamespaceId()) + .isEqualTo(fixture.original.playableStateNamespaceId()); + assertThat(proof.tenantGameplayTag()).isEqualTo(fixture.original.tenantGameplayTag()); + assertThat(proof.issuedAtEpochMillis()).isEqualTo(NOW); + assertThat(proof.observedAtEpochMillis()).isEqualTo(NOW); + assertThat(proof.expiresAtEpochMillis()).isEqualTo(NOW + 500L); + assertThat(proof.observationNonce()).matches("[A-Za-z0-9_-]{43}"); + assertThat(proof.payloadDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(proof.incarnationDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(fixture.sourceReads).hasValue(2); + assertThat(fixture.channelCalls).hasValue(1); + assertThat(proof.operationFence()).isNull(); + assertThat(proof.plannedAccountAdmissionFence()).isNull(); + assertThat(proof.originalCallerContextId()).isNull(); + } + + @Test + void configuredObservationTtlShorterThanTheOperationBudgetWinsAndUsesFreshNonce() { + var fixture = new Fixture(); + fixture.ttl = Duration.ofSeconds(2); + var first = fixture.observe(NOW + 60_000L); + var second = fixture.observe(NOW + 60_000L); + assertThat(first.expiresAtEpochMillis()).isEqualTo(NOW + 2_000L); + assertThat(second.observationNonce()).isNotEqualTo(first.observationNonce()); + assertThat(second.incarnationDigest()).isEqualTo(first.incarnationDigest()); + } + + @Test + void observationExpiryCannotExceedTheLocalOperationCap() { + var fixture = new Fixture(); + assertThat(fixture.observe(NOW + 60_000L).expiresAtEpochMillis()).isEqualTo(NOW + 5_000L); + } + + @ParameterizedTest + @ValueSource( + strings = { + "firemud.gs.protected-incarnation-read/v1", + "firemud.gs.protected-initial-account-barrier-read/v1" + }) + void accountAndInitialSignedSchemasCannotBeReplayedAsTransfer(String schema) { + var fixture = new Fixture(); + fixture.mutation = root -> root.put("schema", schema); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(1); + } + + @ParameterizedTest + @ValueSource(strings = {"ACCOUNT_FENCE", "INITIAL_ACCOUNT_BARRIER"}) + void accountAndInitialOwnerProofsCannotBeReplayedAsTransfer(String kind) { + var fixture = new Fixture(); + fixture.mutation = root -> object(root, "owner").put("ownerKind", kind); + assertRejected(fixture); + } + + @Test + void transferSignedPurposeCannotBeReplayedThroughAccountReceiver() { + var fixture = new Fixture(); + var repository = mock(CanonicalGameplayAccountAdmissionBarrierRepository.class); + var intent = mock(CanonicalGameplayAccountAdmissionFenceIntent.class); + var context = fixture.original; + when(repository.readCurrentFenceIntent(context.transferId())).thenReturn(intent); + when(intent.operationId()).thenReturn(context.transferId()); + when(intent.requestId()).thenReturn(context.requestId()); + when(intent.accountId()).thenReturn(context.accountId()); + when(intent.operationFence()).thenReturn(BigInteger.ONE); + when(intent.plannedAccountAdmissionFence()).thenReturn(UUID.randomUUID()); + when(intent.inventorySnapshotRevision()).thenReturn(BigInteger.ONE); + when(intent.cohortDigest()).thenReturn(DIGEST); + when(intent.barrierTargetDigest()).thenReturn(DIGEST); + when(intent.state()) + .thenReturn(CanonicalGameplayAccountAdmissionFenceIntent.State.ACQUISITION_INTENT); + when(intent.barrierTargets()) + .thenReturn( + List.of( + CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( + context.targetOrdinal(), + context.tenantId(), + context.playableStateNamespaceId()))); + when(fixture.assignment.isBindingTransition()).thenReturn(false); + when(fixture.assignment.admissionFenceIntentOperationId()).thenReturn(context.transferId()); + when(fixture.assignment.barrierTargetOrdinal()).thenReturn(context.targetOrdinal()); + when(fixture.tags.assignmentForBarrierTarget(context.transferId(), context.targetOrdinal())) + .thenReturn(fixture.assignment); + var receiver = + new CanonicalGameplayProtectedIncarnationReceiver( + repository, fixture.tags, fixture::signed, fixture.trust(), fixture.clock); + assertThatThrownBy( + () -> receiver.observeForFenceTarget(context.transferId(), context.targetOrdinal())) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + assertThat(fixture.channelCalls).hasValue(1); + } + + @Test + void transferSignedPurposeCannotBeReplayedThroughInitialReceiver() { + var fixture = new Fixture(); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + var context = fixture.original; + var initial = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitialObservationContext( + UUID.randomUUID(), + context.requestId(), + UUID.randomUUID(), + 1L, + context.accountId(), + context.tenantId(), + context.playableStateNamespaceId(), + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.ZERO, + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST); + when(repository.readCurrentObservationContext(context.requestId())).thenReturn(initial); + when(fixture.assignment.isBindingTransition()).thenReturn(false); + when(fixture.assignment.isInitialBarrierTarget()).thenReturn(true); + when(fixture.assignment.initialBarrierInitializerId()).thenReturn(initial.initializerId()); + when(fixture.assignment.initialBarrierOriginalRequestId()).thenReturn(context.requestId()); + when(fixture.tags.assignmentForInitialBarrierTarget(context.requestId())) + .thenReturn(fixture.assignment); + var receiver = + new CanonicalGameplayProtectedIncarnationReceiver( + repository, fixture.tags, fixture::signed, fixture.trust(), fixture.clock); + assertThatThrownBy(() -> receiver.observeForInitialAccountBarrier(context.requestId())) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + assertThat(fixture.channelCalls).hasValue(1); + } + + @ParameterizedTest + @ValueSource( + strings = { + "transferId", + "transferIntentDigest", + "frozenSourceDigest", + "oldRegionOwnerId", + "oldRegionOwnerFence", + "gameInstanceId", + "regionId", + "regionEpoch", + "transitionId", + "requestId", + "accountId", + "executionDigest", + "candidateDigest", + "controlState", + "completionDigest" + }) + void everySignedTransferOwnerTupleMutationRefuses(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> mutate(object(root, "owner"), field); + assertRejected(fixture); + } + + @Test + void signedMalformedTransferIdRefuses() { + var fixture = new Fixture(); + fixture.mutation = root -> object(root, "owner").put("transferId", "invalid-transfer-id"); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = { + "targetOrdinal", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "workloadNamespace", + "allocationVersion" + }) + void everySignedTargetTupleMutationRefuses(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> mutate(object(root, "target"), field); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = { + "deploymentIdentity", "deploymentGeneration", "canonicalNodeSet", "redisBuildIdentity", + "luaScriptRegistryVersion", "luaScriptRegistryDigest", "startupState", "bootGeneration", + "startupGeneration", "storageGeneration", "aofGeneration" + }) + void everySignedDeploymentIncarnationMutationRefuses(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> mutate(object(root, "targetDeploymentEvidence"), field); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = { + "attestorBinding", + "attestorKeyId", + "acceptedAttestationDigest", + "observationNonce", + "coordOpsRoAclDigest", + "coordRedisConfigObservedDigest" + }) + void signedTrustAndCorrelationMutationRefuses(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> mutate(root, field); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = { + "isBindingTransition", + "transitionId", + "accountId", + "tenantId", + "gameInstanceId", + "playableStateNamespaceId", + "tenantGameplayTag", + "workloadNamespace", + "allocationVersion" + }) + void independentlyResolvedAssignmentMustMatchBeforeRemoteCall(String field) { + var fixture = new Fixture(); + fixture.breakAssignment(field); + assertRejected(fixture); + assertThat(fixture.channelCalls).hasValue(0); + } + + @Test + void assignmentMustStillMatchAfterSignatureVerification() { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.breakAssignment("allocationVersion"); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + assertThat(fixture.channelCalls).hasValue(1); + } + + @ParameterizedTest + @ValueSource( + strings = { + "transferIntentDigest", + "frozenSourceDigest", + "oldRegionOwnerId", + "oldRegionOwnerFence", + "regionEpoch", + "executionDigest", + "candidateDigest" + }) + void frozenSourceMutationDuringSignedReadRefuses(String field) { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.current.set(changed(fixture.original, field)); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void missingOrNoLongerFrozenSourceAfterSignatureCannotProduceProof() { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.current.set(null); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void unavailableCurrentSourceAfterSignatureCannotProduceProof() { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.sourceUnavailable = true; + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void sealedCompletedContextProducesOnlyItsExactReadOnlyCurrentnessObservation() { + var fixture = new Fixture("game-session-original", "COMPLETED", DIGEST); + var proof = fixture.observe(NOW + 1_000L); + assertThat(proof.regionOwnerTransferContext()).isSameAs(fixture.original); + assertThat(proof.regionOwnerTransferContext().controlState()).isEqualTo("COMPLETED"); + assertThat(proof.regionOwnerTransferContext().completionDigest()).isEqualTo(DIGEST); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void completionRacingSignatureVerificationCannotReuseFrozenContextProof() { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.current.set(withPhase(fixture.original, "COMPLETED", DIGEST)); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void changedSealedCompletionDuringObservationRefuses() { + var fixture = new Fixture("game-session-original", "COMPLETED", DIGEST); + fixture.afterSign = + () -> fixture.current.set(withPhase(fixture.original, "COMPLETED", OTHER_DIGEST)); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + } + + @ParameterizedTest + @ValueSource(strings = {"FROZEN", "COMPLETED"}) + void signedProofCannotSubstituteTheOtherControlPhase(String currentPhase) { + var fixture = + new Fixture( + "game-session-original", + currentPhase, + "COMPLETED".equals(currentPhase) ? DIGEST : null); + fixture.mutation = + root -> { + var owner = object(root, "owner"); + boolean wasFrozen = "FROZEN".equals(currentPhase); + owner.put("controlState", wasFrozen ? "COMPLETED" : "FROZEN"); + owner.put("completionDigest", wasFrozen ? DIGEST : null); + }; + assertRejected(fixture); + } + + @Test + void completedSignedDigestMustMatchExactSealedCompletion() { + var fixture = new Fixture("game-session-original", "COMPLETED", DIGEST); + fixture.mutation = root -> object(root, "owner").put("completionDigest", OTHER_DIGEST); + assertRejected(fixture); + } + + @Test + void phaseAndCompletionFieldsMustBothBePresentEvenForFrozenNullCompletion() { + for (String field : List.of("controlState", "completionDigest")) { + var fixture = new Fixture(); + fixture.mutation = root -> object(root, "owner").remove(field); + assertRejected(fixture); + } + } + + @Test + void sourceContextRejectsUnsupportedOrMismatchedControlPhaseAndCompletion() { + var context = new Fixture().original; + assertThatThrownBy(() -> withPhase(context, "UNKNOWN", null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "FROZEN", DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "COMPLETED", null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "COMPLETED", "not-a-digest")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void retainedTrimmedOwnerIdentityNeedsNoAdditionalCharacterGrammar() { + var fixture = new Fixture("game-session/worker α", "FROZEN", null); + var proof = fixture.observe(NOW + 1_000L); + assertThat(proof.regionOwnerTransferContext().oldRegionOwnerId()) + .isEqualTo("game-session/worker α"); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void retainedOwnerLengthUsesThePostgresCharacterBound() { + String ownerId = "\uD83C\uDFAE".repeat(120); + var fixture = new Fixture(ownerId, "FROZEN", null); + assertThat(fixture.observe(NOW + 1_000L).regionOwnerTransferContext().oldRegionOwnerId()) + .isEqualTo(ownerId); + assertThatThrownBy(() -> new Fixture(ownerId + "x", "FROZEN", null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource( + strings = {"issued", "observed-before", "observed-after-expiry", "expires", "clock-back"}) + void timeWindowMismatchOrDeadlineExpiryRefuses(String mode) { + var fixture = new Fixture(); + switch (mode) { + case "issued" -> + fixture.mutation = root -> root.put("observationIssuedAtEpochMillis", NOW - 1L); + case "observed-before" -> + fixture.mutation = root -> root.put("observationObservedAtEpochMillis", NOW - 1L); + case "observed-after-expiry" -> + fixture.mutation = root -> root.put("observationObservedAtEpochMillis", NOW + 1_001L); + case "expires" -> + fixture.mutation = root -> root.put("observationExpiresAtEpochMillis", NOW + 999L); + case "clock-back" -> fixture.afterSign = () -> fixture.now.set(NOW - 1L); + default -> throw new IllegalArgumentException(mode); + } + assertRejected(fixture); + } + + @Test + void expiredObservationSkipsTheSecondSourceRead() { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.now.set(NOW + 1_000L); + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + assertThat(fixture.sourceReads).hasValue(1); + } + + @Test + void futureObservationWithinSignedExpiryReachesCurrentClockRefusal() { + var fixture = new Fixture(); + fixture.mutation = root -> root.put("observationObservedAtEpochMillis", NOW + 1L); + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class) + .hasMessage("Protected observation is expired or out of window"); + // A second source read occurs only after the signed payload and its time window are verified. + assertThat(fixture.sourceReads).hasValue(2); + assertThat(fixture.channelCalls).hasValue(1); + } + + @Test + void expiredOperationNeverReadsSourceOrCallsChannel() { + var fixture = new Fixture(); + assertThatThrownBy(() -> fixture.observe(NOW)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + assertThat(fixture.sourceReads).hasValue(0); + assertThat(fixture.channelCalls).hasValue(0); + } + + @Test + void sourceReadCannotRenewAnOperationThatExpiredBeforeChannelDispatch() { + var fixture = new Fixture(); + fixture.onSourceRead = () -> fixture.now.set(NOW + 1_000L); + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + assertThat(fixture.channelCalls).hasValue(0); + } + + @Test + void stalledChannelReturnsByDeadlineAndRetainsBackgroundAdmission() throws Exception { + var fixture = new Fixture(); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var peerEntered = new CountDownLatch(1); + var peerRelease = new CountDownLatch(1); + fixture.afterSign = + () -> { + entered.countDown(); + awaitRelease(release); + }; + var peer = + Thread.ofVirtual() + .start( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + Clock.systemUTC(), + System.currentTimeMillis() + 5_000L, + budget -> { + peerEntered.countDown(); + awaitRelease(peerRelease); + return null; + })); + try { + assertThat(peerEntered.await(2, TimeUnit.SECONDS)).isTrue(); + long started = System.nanoTime(); + assertThatThrownBy(() -> fixture.observe(NOW + 500L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + assertThat(entered.getCount()).isZero(); + assertThat(System.nanoTime() - started).isLessThan(TimeUnit.SECONDS.toNanos(2)); + var denied = new Fixture(); + assertThatThrownBy(() -> denied.observe(NOW + 500L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + assertThat(denied.sourceReads).hasValue(0); + assertThat(fixture.sourceReads).hasValue(1); + } finally { + release.countDown(); + peerRelease.countDown(); + peer.join(2_000L); + var backgroundPermits = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, + "BACKGROUND_OPERATIONS")); + int slots = CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_BACKGROUND_OPERATIONS; + assertThat(backgroundPermits.tryAcquire(slots, 2, TimeUnit.SECONDS)).isTrue(); + backgroundPermits.release(slots); + } + } + + private static void awaitRelease(CountDownLatch release) { + try { + if (!release.await(3, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled observation was not released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Controlled observation was interrupted", interrupted); + } + } + + @ParameterizedTest + @ValueSource(strings = {"root", "owner", "target", "targetDeploymentEvidence"}) + void signedUnknownFieldsAreRejectedInEveryClosedObject(String object) { + var fixture = new Fixture(); + fixture.mutation = + root -> ("root".equals(object) ? root : object(root, object)).put("unknown", "value"); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = { + "operationId", + "operationFence", + "initializerId", + "originalAttemptFence", + "progressCursor", + "completedCount" + }) + void accountInitialAndMutableProgressFieldsAreNotTransferOwnerFields(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> object(root, "owner").put(field, "unexpected"); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = {"signature", "unpinned", "noncanonical", "duplicate", "oversized", "utf8"}) + void cryptographicCanonicalParsingAndSizeFailuresRefuse(String mode) { + var fixture = new Fixture(); + fixture.encodingFailure = mode; + assertRejected(fixture); + } + + @Test + void ambientTransactionRefusesBeforeReadingSqlOrCallingChannel() { + var fixture = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clear(); + } + assertThat(fixture.sourceReads).hasValue(0); + assertThat(fixture.channelCalls).hasValue(0); + } + + @Test + void sourceContextRejectsInvalidUuidFenceEpochDigestAndBoundedIdentifiers() { + var context = new Fixture().original; + for (String field : + List.of( + "nil-transfer", + "negative-ordinal", + "zero-fence", + "zero-epoch", + "digest", + "owner", + "owner-null", + "owner-blank", + "owner-untrimmed", + "workload", + "allocation")) { + assertThatThrownBy(() -> invalid(context, field)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static void assertRejected(Fixture fixture) { + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + } + + private static CanonicalGameplayRegionOwnerTransferObservationSource.Context changed( + CanonicalGameplayRegionOwnerTransferObservationSource.Context c, String field) { + return new CanonicalGameplayRegionOwnerTransferObservationSource.Context( + c.transferId(), + c.targetOrdinal(), + "transferIntentDigest".equals(field) ? OTHER_DIGEST : c.transferIntentDigest(), + "frozenSourceDigest".equals(field) ? OTHER_DIGEST : c.frozenSourceDigest(), + "oldRegionOwnerId".equals(field) ? "different-owner" : c.oldRegionOwnerId(), + "oldRegionOwnerFence".equals(field) + ? c.oldRegionOwnerFence() + 1L + : c.oldRegionOwnerFence(), + c.tenantId(), + c.gameInstanceId(), + c.regionId(), + "regionEpoch".equals(field) ? c.regionEpoch() + 1L : c.regionEpoch(), + c.transitionId(), + c.requestId(), + c.accountId(), + c.playableStateNamespaceId(), + "executionDigest".equals(field) ? OTHER_DIGEST : c.executionDigest(), + "candidateDigest".equals(field) ? OTHER_DIGEST : c.candidateDigest(), + c.tenantGameplayTag(), + c.workloadNamespace(), + c.allocationVersion(), + c.controlState(), + c.completionDigest()); + } + + private static CanonicalGameplayRegionOwnerTransferObservationSource.Context withPhase( + CanonicalGameplayRegionOwnerTransferObservationSource.Context c, + String phase, + String completionDigest) { + return new CanonicalGameplayRegionOwnerTransferObservationSource.Context( + c.transferId(), + c.targetOrdinal(), + c.transferIntentDigest(), + c.frozenSourceDigest(), + c.oldRegionOwnerId(), + c.oldRegionOwnerFence(), + c.tenantId(), + c.gameInstanceId(), + c.regionId(), + c.regionEpoch(), + c.transitionId(), + c.requestId(), + c.accountId(), + c.playableStateNamespaceId(), + c.executionDigest(), + c.candidateDigest(), + c.tenantGameplayTag(), + c.workloadNamespace(), + c.allocationVersion(), + phase, + completionDigest); + } + + private static CanonicalGameplayRegionOwnerTransferObservationSource.Context invalid( + CanonicalGameplayRegionOwnerTransferObservationSource.Context c, String field) { + String owner = + switch (field) { + case "owner" -> "x".repeat(121); + case "owner-null" -> null; + case "owner-blank" -> " "; + case "owner-untrimmed" -> " owner "; + default -> c.oldRegionOwnerId(); + }; + return new CanonicalGameplayRegionOwnerTransferObservationSource.Context( + "nil-transfer".equals(field) ? new UUID(0L, 0L) : c.transferId(), + "negative-ordinal".equals(field) ? -1L : c.targetOrdinal(), + "digest".equals(field) ? "sha256:" + "A".repeat(64) : c.transferIntentDigest(), + c.frozenSourceDigest(), + owner, + "zero-fence".equals(field) ? 0L : c.oldRegionOwnerFence(), + c.tenantId(), + c.gameInstanceId(), + c.regionId(), + "zero-epoch".equals(field) ? 0L : c.regionEpoch(), + c.transitionId(), + c.requestId(), + c.accountId(), + c.playableStateNamespaceId(), + c.executionDigest(), + c.candidateDigest(), + c.tenantGameplayTag(), + "workload".equals(field) ? "INVALID_NAMESPACE" : c.workloadNamespace(), + "allocation".equals(field) ? 0 : c.allocationVersion(), + c.controlState(), + c.completionDigest()); + } + + @SuppressWarnings("unchecked") + private static Map object(Map root, String field) { + return (Map) root.get(field); + } + + private static void mutate(Map object, String field) { + Object old = object.get(field); + Object replacement; + if (old instanceof Number number) { + replacement = number.longValue() + 1L; + } else if (old instanceof List) { + replacement = List.of("different-node"); + } else if (old instanceof String text && text.startsWith("sha256:")) { + replacement = OTHER_DIGEST; + } else { + replacement = + switch (field) { + case "transferId", + "gameInstanceId", + "regionId", + "transitionId", + "requestId", + "accountId", + "tenantId", + "playableStateNamespaceId" -> + UUID.randomUUID().toString(); + default -> "different-" + old; + }; + } + object.put(field, replacement); + } + + private static KeyPair controlledKeys() { + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } catch (java.security.GeneralSecurityException failure) { + throw new IllegalStateException("Controlled test key generation failed", failure); + } + } + + private static final class Fixture { + private final AtomicLong now = new AtomicLong(NOW); + private final Clock clock = mock(Clock.class); + private final AtomicInteger sourceReads = new AtomicInteger(); + private final AtomicInteger channelCalls = new AtomicInteger(); + private final CanonicalGameplayRegionOwnerTransferObservationSource.Context original; + private final AtomicReference + current; + private final CanonicalGameplayTenantGameplayTagRepository tags = + mock(CanonicalGameplayTenantGameplayTagRepository.class); + private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + private Consumer> mutation = root -> {}; + private Runnable afterSign = () -> {}; + private Runnable onSourceRead = () -> {}; + private Duration ttl = Duration.ofSeconds(30); + private boolean sourceUnavailable; + private String encodingFailure = ""; + + private Fixture() { + this("game-session-original", "FROZEN", null); + } + + private Fixture(String ownerId, String controlState, String completionDigest) { + UUID tenant = UUID.randomUUID(); + original = + new CanonicalGameplayRegionOwnerTransferObservationSource.Context( + UUID.randomUUID(), + 3L, + TRANSFER_INTENT_DIGEST, + FROZEN_SOURCE_DIGEST, + ownerId, + 7L, + tenant, + UUID.randomUUID(), + UUID.randomUUID(), + 11L, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + EXECUTION_DIGEST, + CANDIDATE_DIGEST, + "g1-" + tenant.toString().replace("-", ""), + "test-workload", + 1, + controlState, + completionDigest); + current = new AtomicReference<>(original); + when(clock.millis()).thenAnswer(invocation -> now.get()); + when(tags.assignmentForTransition(original.transitionId())).thenReturn(assignment); + when(assignment.isBindingTransition()).thenReturn(true); + when(assignment.transitionId()).thenReturn(original.transitionId()); + when(assignment.accountId()).thenReturn(original.accountId()); + when(assignment.tenantId()).thenReturn(original.tenantId()); + when(assignment.gameInstanceId()).thenReturn(original.gameInstanceId()); + when(assignment.playableStateNamespaceId()).thenReturn(original.playableStateNamespaceId()); + when(assignment.tenantGameplayTag()).thenReturn(original.tenantGameplayTag()); + when(assignment.workloadNamespace()).thenReturn(original.workloadNamespace()); + when(assignment.allocationVersion()).thenReturn(original.allocationVersion()); + } + + private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observe( + long deadline) { + return CanonicalGameplayProtectedIncarnationReceiver.forRegionOwnerTransfer( + (transferId, ordinal) -> { + sourceReads.incrementAndGet(); + onSourceRead.run(); + if (sourceUnavailable) { + throw new CanonicalGameplayProtectedIncarnationReceiver + .ObservationUnavailableException( + "Controlled current SQL transfer source became unavailable"); + } + return current.get(); + }, + tags, + this::signed, + trust(), + clock) + .observeForRegionOwnerTransfer(original.transferId(), original.targetOrdinal(), deadline); + } + + private void breakAssignment(String field) { + switch (field) { + case "isBindingTransition" -> when(assignment.isBindingTransition()).thenReturn(false); + case "transitionId" -> when(assignment.transitionId()).thenReturn(UUID.randomUUID()); + case "accountId" -> when(assignment.accountId()).thenReturn(UUID.randomUUID()); + case "tenantId" -> when(assignment.tenantId()).thenReturn(UUID.randomUUID()); + case "gameInstanceId" -> when(assignment.gameInstanceId()).thenReturn(UUID.randomUUID()); + case "playableStateNamespaceId" -> + when(assignment.playableStateNamespaceId()).thenReturn(UUID.randomUUID()); + case "tenantGameplayTag" -> + when(assignment.tenantGameplayTag()).thenReturn("g1-" + "f".repeat(32)); + case "workloadNamespace" -> + when(assignment.workloadNamespace()).thenReturn("different-workload"); + case "allocationVersion" -> when(assignment.allocationVersion()).thenReturn(2); + default -> throw new IllegalArgumentException(field); + } + } + + private CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration trust() { + var evidence = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-target", + "generation-1", + List.of("redis-a", "redis-b"), + "redis-build", + "registry-1", + DIGEST, + "READY", + "boot-1", + "startup-1", + "storage-1", + "aof-1"); + return new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + "controlled-transfer-binding", + DIGEST, + Map.of(KEY_ID, (RSAPublicKey) KEYS.getPublic()), + evidence, + DIGEST, + DIGEST, + 16 * 1024, + 2, + ttl); + } + + private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation signed( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + channelCalls.incrementAndGet(); + Map root = payload(request); + mutation.accept(root); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + switch (encodingFailure) { + case "noncanonical" -> + bytes = + (new String(bytes, StandardCharsets.UTF_8) + " ") + .getBytes(StandardCharsets.UTF_8); + case "duplicate" -> + bytes = + ("{\"schema\":\"duplicate\"," + + new String(bytes, StandardCharsets.UTF_8).substring(1)) + .getBytes(StandardCharsets.UTF_8); + case "oversized" -> bytes = new byte[17 * 1024]; + case "utf8" -> bytes = new byte[] {(byte) 0xc3, (byte) 0x28}; + default -> {} + } + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(KEYS.getPrivate()); + signer.update(bytes); + byte[] signature = signer.sign(); + if ("signature".equals(encodingFailure)) signature[0] ^= 1; + afterSign.run(); + return new CanonicalGameplayProtectedIncarnationReceiver.SignedObservation( + "unpinned".equals(encodingFailure) ? "unknown-key" : KEY_ID, bytes, signature); + } catch (java.security.GeneralSecurityException | java.io.IOException failure) { + throw new IllegalStateException("Controlled transfer signing failed", failure); + } + } + + private Map payload( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + var c = original; + Map owner = new LinkedHashMap<>(); + owner.put("ownerKind", "REGION_OWNER_TRANSFER"); + owner.put("transferId", c.transferId().toString()); + owner.put("transferIntentDigest", c.transferIntentDigest()); + owner.put("frozenSourceDigest", c.frozenSourceDigest()); + owner.put("oldRegionOwnerId", c.oldRegionOwnerId()); + owner.put("oldRegionOwnerFence", c.oldRegionOwnerFence()); + owner.put("gameInstanceId", c.gameInstanceId().toString()); + owner.put("regionId", c.regionId().toString()); + owner.put("regionEpoch", c.regionEpoch()); + owner.put("transitionId", c.transitionId().toString()); + owner.put("requestId", c.requestId().toString()); + owner.put("accountId", c.accountId().toString()); + owner.put("executionDigest", c.executionDigest()); + owner.put("candidateDigest", c.candidateDigest()); + owner.put("controlState", c.controlState()); + owner.put("completionDigest", c.completionDigest()); + Map target = new LinkedHashMap<>(); + target.put("targetOrdinal", c.targetOrdinal()); + target.put("tenantId", c.tenantId().toString()); + target.put("playableStateNamespaceId", c.playableStateNamespaceId().toString()); + target.put("tenantGameplayTag", c.tenantGameplayTag()); + target.put("workloadNamespace", c.workloadNamespace()); + target.put("allocationVersion", c.allocationVersion()); + var e = request.expectedEvidence(); + Map evidence = new LinkedHashMap<>(); + evidence.put("deploymentIdentity", e.deploymentIdentity()); + evidence.put("deploymentGeneration", e.deploymentGeneration()); + evidence.put("canonicalNodeSet", e.canonicalNodeSet()); + evidence.put("redisBuildIdentity", e.redisBuildIdentity()); + evidence.put("luaScriptRegistryVersion", e.luaScriptRegistryVersion()); + evidence.put("luaScriptRegistryDigest", e.luaScriptRegistryDigest()); + evidence.put("startupState", e.startupState()); + evidence.put("bootGeneration", e.bootGeneration()); + evidence.put("startupGeneration", e.startupGeneration()); + evidence.put("storageGeneration", e.storageGeneration()); + evidence.put("aofGeneration", e.aofGeneration()); + Map root = new LinkedHashMap<>(); + root.put("schema", SCHEMA); + root.put("attestorBinding", request.attestorBinding()); + root.put("attestorKeyId", KEY_ID); + root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); + root.put("observationNonce", request.nonce()); + root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis()); + root.put("owner", owner); + root.put("target", target); + root.put("targetDeploymentEvidence", evidence); + root.put("coordOpsRoAclDigest", request.coordOpsRoAclDigest()); + root.put("coordRedisConfigObservedDigest", request.coordRedisConfigObservedDigest()); + return root; + } + } +} From a76e509a21428f80a2adafa658b87d0ebe0f4ad6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:23:18 +1300 Subject: [PATCH 02/51] Stage region handoff review fixes and coordinated migration carry --- .../OriginalNewCapacityExecution.java | 17 ++- .../capacity/CapacityAdmissionDigestTest.java | 44 +++++++ ...calGameplayBindingInventoryRepository.java | 11 +- ...playOriginalNewCapacityExecutionOwner.java | 4 +- ...ayOriginalNewFinalAdmissionRedisOwner.java | 3 +- .../CanonicalGameplayRegionLeaseOwner.java | 103 ++++++++++++--- ...onicalGameplayRegionLeaseOwnerFactory.java | 3 +- ...anonicalGameplayRegionLeaseRedisOwner.java | 88 +++++++++++++ ...ind_fence_receipt_dispatch_incarnation.sql | 45 +++++++ ..._align_capacity_runtime_owner_identity.sql | 57 ++++++++ ...pair_frozen_required_member_projection.sql | 84 ++++++++++++ ...e-session-original-new-final-admission.lua | 29 ++++- ...ingInventoryRepositoryIntegrationTest.java | 74 +++++++++-- ...CapacityRetentionOwnerIntegrationTest.java | 49 +++++++ ...NewFinalAdmissionOwnerIntegrationTest.java | 78 +++++++++++ ...meplayRegionLeaseOwnerIntegrationTest.java | 94 ++++++++++---- ...GameplayRegionOwnerCompositionFixture.java | 122 ++++++++---------- ...ransferCapacityCustodyIntegrationTest.java | 47 +++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 88 ++++++++++++- ...riginalNewCapacityExecutionBudgetTest.java | 113 ++++++++++++++++ 20 files changed, 1003 insertions(+), 150 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.11__bind_fence_receipt_dispatch_incarnation.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.12__align_capacity_runtime_owner_identity.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.13__repair_frozen_required_member_projection.sql diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java index 23cbe5db8a..9198910871 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java @@ -23,7 +23,11 @@ public record OriginalNewCapacityExecution( requireOriginalNewRequest(request); Objects.requireNonNull(reservation).requireBinding(request); TenantCapacityAdmission.uuid(transitionId); - if (selectedOwnerId == null || !selectedOwnerId.matches("[A-Za-z0-9._:-]{1,120}")) + if (selectedOwnerId == null + || selectedOwnerId.isBlank() + || !selectedOwnerId.equals(selectedOwnerId.trim()) + || selectedOwnerId.codePointCount(0, selectedOwnerId.length()) > 120 + || selectedOwnerId.codePoints().anyMatch(cp -> cp == 0 || (cp >= 0xD800 && cp <= 0xDFFF))) throw new IllegalArgumentException("Exact selected owner instance required"); if ((reservation.state() != TenantCapacityAdmission.State.RESERVED && reservation.state() != TenantCapacityAdmission.State.FINALIZED) @@ -46,7 +50,7 @@ public static void requireOriginalNewRequest(TenantCapacityAdmission.Request req } } - /** All strings have closed grammars; the complete canonical attempt includes Account evidence. */ + /** Canonical JSON escapes runtime identity text; the attempt includes exact Account evidence. */ public byte[] canonicalBytes() { Map fields = new LinkedHashMap<>(); fields.put("schema", "gs-original-new-capacity-execution/v1"); @@ -70,14 +74,9 @@ public byte[] canonicalBytes() { fields.put( "canonicalAttemptPayload", Base64.getEncoder().encodeToString(CapacityAdmissionDigest.preimage(request))); - StringBuilder json = new StringBuilder("{"); - fields.forEach( - (name, value) -> { - if (json.length() > 1) json.append(','); - json.append('"').append(name).append("\":\"").append(value).append('"'); - }); try { - return Rfc8785CanonicalJson.canonicalizeUtf8(json.append('}').toString()); + return Rfc8785CanonicalJson.canonicalizeUtf8( + tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(fields)); } catch (java.io.IOException malformed) { throw new IllegalArgumentException("Invalid capacity execution", malformed); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index a8f6b0e863..239faf0682 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -296,6 +296,50 @@ void nonExpandingRecoveryStillRequiresCreationEligibleEvidence() { assertThatThrownBy(recovery::requireCommittable).isInstanceOf(IllegalArgumentException.class); } + @Test + void originalExecutionPreservesAndEscapesOpaqueRuntimeOwnerIdentity() throws Exception { + Request request = CapacityAdmissionTestFixture.playerRequest(); + var reservation = + new TenantCapacityAdmission.Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.fromString("b1111111-1111-4111-8111-111111111111"), + 1, + request.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + for (String owner : + List.of("owner-1", "game-session/worker α", "worker\"\\α", "😀".repeat(120))) { + var execution = + new OriginalNewCapacityExecution( + request, + reservation, + request.identity().admissionId(), + "sha256:" + "a".repeat(64), + owner, + 1); + var json = JsonMapper.builder().build().readTree(execution.canonicalBytes()); + assertThat(json.get("selectedOwnerId").asText()).isEqualTo(owner); + assertThat(execution.canonicalBytes()).isEqualTo(execution.canonicalBytes()); + } + for (String owner : + List.of("", " ", " owner", "owner\t", "😀".repeat(121), "bad\u0000id", "bad\uD800id")) { + assertThatThrownBy( + () -> + new OriginalNewCapacityExecution( + request, + reservation, + request.identity().admissionId(), + "sha256:" + "a".repeat(64), + owner, + 1)) + .isInstanceOf(IllegalArgumentException.class); + } + } + @Test void boundReleasedAndQuarantinedResultsCannotAuthorizeOriginalExecution() { Request request = CapacityAdmissionTestFixture.playerRequest(); 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 d298c3fb58..656b72c567 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 @@ -4428,7 +4428,7 @@ private static void requireCompletedMemberRepairAcknowledgement( } if (currentInventoryRevision != null && (completedRevision.compareTo(operation.inventorySnapshotRevision()) <= 0 - || completedRevision.compareTo(currentInventoryRevision) >= 0 + || completedRevision.compareTo(currentInventoryRevision) > 0 || (operation.originalObligation().projectionState() == CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED && !completedRevision.equals(obligation.projectionInventoryRevision())))) { @@ -5561,8 +5561,7 @@ private static void persistMemberRepairAcknowledgement( "UPDATE " + ACCOUNT_OBLIGATION + " SET status = 'ACKNOWLEDGED', projection_state = 'PRESENT_AWAITING_COVERAGE'," - + " projection_member = ?, projection_inventory_revision = COALESCE(" - + " projection_inventory_revision, ?), inventory_revision = ?" + + " projection_member = ?, projection_inventory_revision = ?, inventory_revision = ?" + " WHERE transition_id = ? AND obligation_ordinal = 0" + " AND binding_ref = ? AND account_id = ? AND tenant_id = ?" + " AND action = 'ADD_OR_RETAIN' AND binding_generation = ?" @@ -5573,7 +5572,11 @@ private static void persistMemberRepairAcknowledgement( + " AND projection_inventory_revision IS NULL)" + " OR (projection_state = 'PRESENT_AWAITING_COVERAGE' AND projection_member = ?))", member, - decimal(nextRevision), + decimal( + operation.originalObligation().projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED + ? nextRevision + : operation.originalObligation().projectionInventoryRevision()), decimal(nextRevision), operation.transitionId(), operation.bindingRef().bytes(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index dc1b198acd..5d3d3ce21b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -916,7 +916,9 @@ private CurrentOwner currentOwner(CanonicalGameplayOriginalNewCandidate candidat String instance = current.get("owner_instance_id", String.class); Long fence = current.get("executor_fence", Long.class); if (instance == null - || !instance.matches("[A-Za-z0-9._:-]{1,120}") + || instance.isBlank() + || !instance.equals(instance.trim()) + || instance.codePointCount(0, instance.length()) > 120 || fence == null || fence <= 0) throw unavailable(); return new CurrentOwner(instance, fence); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index 317804aac2..bd2902180d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -341,7 +341,8 @@ Readback readCommittedForRetention( requireNoAmbientTransaction(); var candidate = requireSource(source); requireExecutionBinding(source, execution); - var assignment = tenantTags.assignmentForTransition(execution.transitionId()); + var assignment = + tenantTags.readAssignmentForRetainedCapacityExecution(execution.transitionId()); requireAssignment(assignment, candidate); String accountKey = ACCOUNT_PREFIX diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index e9a2419998..432f28351f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.repository; +import io.grpc.Context; import io.grpc.Deadline; import java.math.BigInteger; import java.time.Clock; @@ -36,6 +37,7 @@ final class CanonicalGameplayRegionLeaseOwner { private final RuntimeIdentity runtimeIdentity; private final Duration leaseTtl; private final Clock clock; + private final boolean deadlineBoundInstallation; CanonicalGameplayRegionLeaseOwner( CanonicalGameplayBindingInventoryRepository bindingInventory, @@ -46,6 +48,29 @@ final class CanonicalGameplayRegionLeaseOwner { RuntimeIdentity runtimeIdentity, Duration leaseTtl, Clock clock) { + this( + bindingInventory, + statusRepository, + redisOwner, + incarnationSource, + worldRegionResolver, + runtimeIdentity, + leaseTtl, + clock, + false); + } + + CanonicalGameplayRegionLeaseOwner( + CanonicalGameplayBindingInventoryRepository bindingInventory, + CanonicalGameplayRegionRuntimeStatusRepository statusRepository, + CanonicalGameplayRegionLeaseRedisOwner redisOwner, + CanonicalGameplayRegionIncarnationSource incarnationSource, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock, + boolean deadlineBoundInstallation) { + this.deadlineBoundInstallation = deadlineBoundInstallation; this.bindingInventory = Objects.requireNonNull(bindingInventory, "bindingInventory"); this.statusRepository = Objects.requireNonNull(statusRepository, "statusRepository"); this.redisOwner = Objects.requireNonNull(redisOwner, "redisOwner"); @@ -91,10 +116,20 @@ Installation installForTransition( Objects.requireNonNull(worldRequest, "worldRequest"); // Freeze the existing five-second transfer budget once, not once per inventory read. long startedAt = clock.millis(); + long requestedDeadline = absoluteDeadlineMillis; + if (transferOwner != null || deadlineBoundInstallation) { + if (Context.current().isCancelled()) throw unavailable(); + if (Context.current().getDeadline() != null) { + long remaining = Context.current().getDeadline().timeRemaining(TimeUnit.MILLISECONDS); + if (remaining <= 0) throw unavailable(); + requestedDeadline = + Math.min(requestedDeadline, Math.addExact(startedAt, Math.min(5000L, remaining))); + } + } final long handoffDeadline = - transferOwner == null - ? absoluteDeadlineMillis - : Math.min(absoluteDeadlineMillis, Math.addExact(startedAt, 5_000L)); + transferOwner == null && !deadlineBoundInstallation + ? requestedDeadline + : Math.min(requestedDeadline, Math.addExact(startedAt, 5_000L)); Deadline worldDeadline = worldDeadline(startedAt, handoffDeadline); // A prior advance may have retained the positive SQL result before a later observation // failed. Recover only its captured original, never synthetic provisional authority. @@ -175,7 +210,9 @@ Installation installForTransition( transferOwner.requireFrozenOriginal(frozenOriginal, source, prior, handoffDeadline); } CanonicalGameplayRegionLeaseRedisOwner handoffRedisOwner = - transferOwner == null ? redisOwner : redisOwner.forHandoffDeadline(clock, handoffDeadline); + transferOwner == null && !deadlineBoundInstallation + ? redisOwner + : redisOwner.forHandoffDeadline(clock, handoffDeadline); UUID transferId = null; CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource = retainedOriginal; @@ -185,6 +222,7 @@ Installation installForTransition( CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; boolean reusingRegionGrant = false; + boolean recoveringInitialGrant = false; if (prior == null) { if (existingRegionInstallation != null) throw unavailable(); preparation = @@ -324,7 +362,27 @@ Installation installForTransition( if (!matchesInitialization || !resumablePhase) { throw unavailable(); } - if (existingRegionInstallation == null) { + if (existingRegionInstallation == null + && sameInitializationAttempt + && expectedRegionEpoch == 1L + && (transferOwner == null + || preparation.phase() + == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .REDIS_INITIALIZED)) { + grant = handoffRedisOwner.readRetainedInitialGrant(preparation, prior, runtimeIdentity); + handoffRedisOwner.requireCurrent(grant); + handoffRedisOwner.verifyInitializedTimeline(grant, preparation); + if (!prior.equals( + withTransferStatusRepository( + transferOwner, handoffDeadline, repository -> repository.find(source)) + .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable))) { + throw unavailable(); + } + recoveringInitialGrant = true; + } else if (existingRegionInstallation == null) { + // Compatibility calls may create the first owner or recover its exact retained live grant, + // but replacing an installed owner requires the explicit frozen transfer protocol. + if (transferOwner == null) throw unavailable(); // A stable instance ID can survive a restart. The fresh-token acquire establishes // scoped lease absence atomically and refuses every live incumbent or competing grant. grant = handoffRedisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); @@ -408,27 +466,30 @@ Installation installForTransition( handoffDeadline, worldDeadline); requireSameSource(source, afterAcquire); - handoffRedisOwner.renew(grant, leaseTtl); + if (!recoveringInitialGrant) handoffRedisOwner.renew(grant, leaseTtl); handoffRedisOwner.requireCurrent(grant); requireSameIncarnation( incarnation, readInstallationIncarnation(transferOwner, handoffDeadline, source)); handoffRedisOwner.verifyInitializedTimeline(grant, preparation); - if (transferOwner != null && clock.millis() >= handoffDeadline) throw unavailable(); + if ((transferOwner != null || deadlineBoundInstallation) && clock.millis() >= handoffDeadline) + throw unavailable(); if (transferId == null) { var installed = - withTransferStatusRepository( - transferOwner, - handoffDeadline, - repository -> - repository.installOwner( - source, - expectedRegionEpoch, - prior, - grant.tokenCorrelation(), - grant.ownerService(), - grant.ownerInstanceId(), - clock.instant())); + recoveringInitialGrant + ? prior + : withTransferStatusRepository( + transferOwner, + handoffDeadline, + repository -> + repository.installOwner( + source, + expectedRegionEpoch, + prior, + grant.tokenCorrelation(), + grant.ownerService(), + grant.ownerInstanceId(), + clock.instant())); return verifyInstallation( transitionId, worldRequest, @@ -576,7 +637,9 @@ private Installation verifyInstallation( long handoffDeadline, Deadline worldDeadline) { CanonicalGameplayRegionLeaseRedisOwner handoffRedisOwner = - transferOwner == null ? redisOwner : redisOwner.forHandoffDeadline(clock, handoffDeadline); + transferOwner == null && !deadlineBoundInstallation + ? redisOwner + : redisOwner.forHandoffDeadline(clock, handoffDeadline); handoffRedisOwner.requireCurrent(grant); handoffRedisOwner.verifyInitializedTimeline(grant, preparation); CanonicalGameplayRegionRuntimeStatus observed = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java index 8394d4fdca..4049a82859 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java @@ -37,6 +37,7 @@ static CanonicalGameplayRegionLeaseOwner compose( Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"), Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"), Objects.requireNonNull(leaseTtl, "leaseTtl"), - Objects.requireNonNull(clock, "clock")); + Objects.requireNonNull(clock, "clock"), + true); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index e4685dfb51..233753c1e2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -134,6 +134,29 @@ CanonicalGameplayRegionLeaseRedisOwner forHandoffDeadline(Clock clock, long dead deadline); } + /** Freeze one deadline before the composed installation performs any source or SQL work. */ + CanonicalGameplayRegionLeaseRedisOwner forInstallation(Clock clock) { + // URI-less owners are the explicitly unbudgeted ordinary installation composition. + if (coordinationUri == null) return this; + Context caller = Context.current(); + if (caller.isCancelled()) throw unavailable(); + long remainingMillis = COMMAND_TIMEOUT_MILLIS; + if (caller.getDeadline() != null) { + remainingMillis = + Math.min(remainingMillis, caller.getDeadline().timeRemaining(TimeUnit.MILLISECONDS)); + } + if (remainingMillis <= 0) throw unavailable(); + long deadline; + try { + deadline = Math.addExact(clock.millis(), remainingMillis); + } catch (ArithmeticException invalid) { + throw unavailable(invalid); + } + if (handoffClock != null) deadline = Math.min(deadline, handoffDeadlineMillis); + if (deadline <= clock.millis()) throw unavailable(); + return forHandoffDeadline(clock, deadline); + } + LeaseGrant acquire( CanonicalGameplayRegionRuntimeStatusRepository.Source source, long regionEpoch, @@ -310,6 +333,71 @@ private PreparedTimelineInitialization prepareTimelineInitialization( } } + /** Recovers the same live first-owner grant; never acquires or replaces a lease. */ + LeaseGrant readRetainedInitialGrant( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + CanonicalGameplayRegionRuntimeStatus status, + RuntimeIdentity identity) { + requireNoAmbientTransaction(); + if (status.paused() + || status.regionEpoch() != 1L + || preparation.regionEpoch() != 1L + || !requireOwnerService(identity).equals(status.ownerService()) + || !requireOwnerInstance(identity).equals(status.ownerInstanceId()) + || !Objects.equals(preparation.leaseTokenCorrelation(), status.leaseTokenCorrelation())) { + throw unavailable(); + } + if (handoffClock != null) { + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + handoffClock, + handoffDeadlineMillis, + budget -> readRetainedInitialGrant(preparation, status, budget)); + } + return readRetainedInitialGrant( + preparation, status, (CanonicalGameplayOriginalNewCapacityExecutionBudget) null); + } + + private LeaseGrant readRetainedInitialGrant( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + CanonicalGameplayRegionRuntimeStatus status, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + StatefulRedisConnection connection = null; + byte[] tokenBytes = null; + try { + connection = + budget == null ? redisClient.connect(ByteArrayCodec.INSTANCE) : openConnection(budget); + var commands = connection.async(); + requirePrincipal(await(commands::aclWhoami, budget)); + var source = preparation.source(); + byte[] key = + ascii( + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId())); + tokenBytes = await(() -> commands.get(key), budget); + Long ttl = await(() -> commands.pttl(key), budget); + if (tokenBytes == null || tokenBytes.length != 36 || ttl == null || ttl <= 0) + throw unavailable(); + String token = new String(tokenBytes, StandardCharsets.US_ASCII); + UUID parsed = UUID.fromString(token); + if (!parsed.toString().equals(token) || parsed.equals(new UUID(0L, 0L))) throw unavailable(); + var grant = + new LeaseGrant( + source, status.regionEpoch(), token, status.ownerService(), status.ownerInstanceId()); + if (!grant.tokenCorrelation().equals(status.leaseTokenCorrelation())) throw unavailable(); + return grant; + } catch (RuntimeException failure) { + throw unavailable(failure); + } finally { + if (tokenBytes != null) Arrays.fill(tokenBytes, (byte) 0); + if (connection != null) { + if (budget == null) connection.close(); + else + budget.awaitAsyncClose( + CanonicalGameplayOriginalNewCapacityExecutionBudget.startRedisClose(connection)); + } + } + } + void verifyInitializedTimeline( LeaseGrant grant, CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation) { diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.11__bind_fence_receipt_dispatch_incarnation.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.11__bind_fence_receipt_dispatch_incarnation.sql new file mode 100644 index 0000000000..6deb284eca --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.11__bind_fence_receipt_dispatch_incarnation.sql @@ -0,0 +1,45 @@ +-- Keep receipt recovery bound to the storage incarnation that actually received dispatch. +-- Validate existing tuples; never rewrite immutable dispatch/receipt history. +-- [jooq ignore start] +ALTER TABLE game_session_region_owner_transfer_item + ADD CONSTRAINT gs_region_fence_receipt_dispatch_incarnation CHECK ( + fence_dispatch_id IS NULL OR fence_readback IS NULL + OR incarnation_digest = fence_dispatch_incarnation); + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1065.0.10' + ) AND ($needle$; + replacement := $replacement$WHERE version='1065.0.10' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.11__bind_fence_receipt_dispatch_incarnation.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.11' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.10'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.11'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.10','V1065.0.10__bound_capacity_closure_receipt_lookup.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.11'',''V1065.0.11__bind_fence_receipt_dispatch_incarnation.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.12__align_capacity_runtime_owner_identity.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.12__align_capacity_runtime_owner_identity.sql new file mode 100644 index 0000000000..e8bff81294 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.12__align_capacity_runtime_owner_identity.sql @@ -0,0 +1,57 @@ +-- Preserve opaque runtime-owner text and all immutable execution evidence. +-- Qualify the exact generated predecessor CHECK rather than guessing truncated names. +-- [jooq ignore start] +DO $owners$ +DECLARE target TEXT; constraint_name TEXT; definition TEXT; +BEGIN + FOREACH target IN ARRAY ARRAY['game_session_original_new_capacity_execution', 'game_session_capacity_evidence_charge'] LOOP + SELECT c.conname, pg_get_constraintdef(c.oid) INTO STRICT constraint_name, definition + FROM pg_constraint c JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attname='selected_owner_id' + WHERE c.conrelid=(quote_ident(current_schema())||'.'||quote_ident(target))::regclass + AND c.contype='c' AND c.conkey=ARRAY[a.attnum]::smallint[]; + IF position('^[A-Za-z0-9._:-]{1,120}$' IN definition)=0 THEN + RAISE EXCEPTION 'Expected exact ASCII owner identity predecessor constraint'; + END IF; + EXECUTE format('ALTER TABLE %I DROP CONSTRAINT %I', target, constraint_name); + EXECUTE format($check$ALTER TABLE %I ADD CONSTRAINT %I CHECK (selected_owner_id <> '' AND btrim(selected_owner_id)=selected_owner_id)$check$, target, constraint_name); + END LOOP; +END; +$owners$; + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1065.0.11' + ) AND ($needle$; + replacement := $replacement$WHERE version='1065.0.11' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.12__align_capacity_runtime_owner_identity.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.12' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.11'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.12'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.11','V1065.0.11__bind_fence_receipt_dispatch_incarnation.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.12'',''V1065.0.12__align_capacity_runtime_owner_identity.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.13__repair_frozen_required_member_projection.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.13__repair_frozen_required_member_projection.sql new file mode 100644 index 0000000000..620665cae0 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.13__repair_frozen_required_member_projection.sql @@ -0,0 +1,84 @@ +-- The old ACK writer retained a concurrent intermediate PRESENT stamp with COALESCE. +-- The frozen REQUIRED operation instead owns the completed readback revision. +-- Repair only that mutable projection on still-provisional exact first-NEW rows. +-- Never rewrite the frozen operation, readback, completion, fences, or abort evidence. +-- Data-only PostgreSQL UPDATE FROM cannot be emulated by the jOOQ H2 exporter. +-- [jooq ignore start] +UPDATE game_session_canonical_binding_account_index_obligation AS obligation +SET projection_inventory_revision = repair.completed_inventory_revision +FROM game_session_canonical_account_member_repair_operation AS repair, + game_session_canonical_binding_transition AS transition +WHERE obligation.transition_id = repair.transition_id + AND obligation.obligation_ordinal = repair.obligation_ordinal + AND transition.transition_id = repair.transition_id + AND transition.status = 'PROVISIONAL' + AND transition.expected_prior_binding_ref IS NULL + AND transition.expected_prior_binding_generation IS NULL + AND transition.candidate_binding_ref = repair.binding_ref + AND transition.candidate_binding_generation = repair.binding_generation + AND transition.candidate_account_index_fence = repair.account_index_fence + AND transition.admission_orphan_cleanup_id IS NULL + AND obligation.binding_ref = repair.binding_ref + AND obligation.account_id = repair.account_id + AND obligation.tenant_id = repair.tenant_id + AND obligation.binding_generation = repair.binding_generation + AND obligation.account_index_fence = repair.account_index_fence + AND obligation.action = repair.original_action + AND obligation.expected_prior_generation IS NULL + AND obligation.execution_phase = repair.original_execution_phase + AND obligation.status = 'ACKNOWLEDGED' + AND obligation.projection_state = 'PRESENT_AWAITING_COVERAGE' + AND obligation.projection_member = repair.member + AND obligation.inventory_revision = transition.inventory_revision + AND repair.status = 'ACKNOWLEDGED' + AND repair.original_projection_state = 'REQUIRED' + AND repair.original_projection_member IS NULL + AND repair.original_projection_inventory_revision IS NULL + AND repair.readback_state = 'PRESENT' + AND repair.readback_member = repair.member + AND repair.completed_inventory_revision > repair.inventory_snapshot_revision + AND repair.completed_inventory_revision <= obligation.inventory_revision + AND obligation.projection_inventory_revision > repair.inventory_snapshot_revision + AND obligation.projection_inventory_revision < repair.completed_inventory_revision; + +-- [jooq ignore stop] + +-- Runtime-family catalog registration +-- [jooq ignore start] +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1065.0.12' + ) AND ($needle$; + replacement := $replacement$WHERE version='1065.0.12' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.13__repair_frozen_required_member_projection.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.13' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.12'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.13'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.12','V1065.0.12__align_capacity_runtime_owner_identity.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.13'',''V1065.0.13__repair_frozen_required_member_projection.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua index c71d18931b..ff8782ee75 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua @@ -17,6 +17,33 @@ local sessionNames = {'schemaVersion', 'admissionState', 'originalCandidate', 'b 'authTokenIssuedAt', 'authTokenExpiresAt', 'tokenGeneration', 'issuanceFence', 'rebindHandle', 'continuityBindingExpiresAt', 'membershipBaseline', 'authorityTuple', 'outboxCheckpoints', 'canonicalSessionDurationMillis', 'capacityExecutionDigest'} +-- Runtime IDs are opaque Unicode text, not ASCII identifiers. Count valid scalar values. +local function ownerIdentity(value) + if type(value) ~= 'string' or #value == 0 or #value > 480 + or string.byte(value, 1) <= 32 or string.byte(value, #value) <= 32 then return false end + local i, count = 1, 0 + while i <= #value do + local first = string.byte(value, i) + local width, cp + if first < 128 then width, cp = 1, first + elseif first >= 194 and first <= 223 then width, cp = 2, first - 192 + elseif first >= 224 and first <= 239 then width, cp = 3, first - 224 + elseif first >= 240 and first <= 244 then width, cp = 4, first - 240 + else return false end + if i + width - 1 > #value then return false end + for offset = 1, width - 1 do + local byte = string.byte(value, i + offset) + if byte < 128 or byte > 191 then return false end + cp = cp * 64 + byte - 128 + end + if cp == 0 or (width == 3 and cp < 2048) or (width == 4 and cp < 65536) + or (cp >= 55296 and cp <= 57343) or cp > 1114111 then return false end + count = count + 1 + if count > 120 then return false end + i = i + width + end + return true +end local function uuid(value) return type(value) == 'string' and #value == 36 and value == string.lower(value) and value ~= '00000000-0000-0000-0000-000000000000' @@ -71,7 +98,7 @@ if not capacity or capacity.schema ~= 'gs-original-new-capacity-execution/v1' or not string.match(capacityDigest, '^sha256:[0-9a-f]+$') or not uuid(capacity.requestId) or not uuid(capacity.admissionId) or not uuid(capacity.admissionAttemptId) or not uuid(capacity.reservationId) - or type(capacity.selectedOwnerId) ~= 'string' or #capacity.selectedOwnerId < 1 or #capacity.selectedOwnerId > 120 + or not ownerIdentity(capacity.selectedOwnerId) or not uuid(capacity.transitionId) or not positive(capacity.capacityRearmFence) or not positive(capacity.reservationFence) or not positive(capacity.selectedOwnerFence) then return -2 end 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 83dddafaac..79e37ad9bd 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 @@ -497,8 +497,10 @@ void missingAccountCoverageControlRowCannotAuthorizeMemberRepair() { } } - @Test - void memberRepairPreservesAnEarlierPresentObservationUntilActualAcknowledgement() { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void memberRepairPreservesTheFrozenProjectionContractAcrossConcurrentObservation( + boolean observeAfterFreeze) throws Exception { TestSchema testSchema = newTestSchema("gs_member_present_"); RedisMemberFixture redisFixture = null; try { @@ -508,6 +510,8 @@ void memberRepairPreservesAnEarlierPresentObservationUntilActualAcknowledgement( String member = CanonicalGameplayAccountIndexMember.of(fixture.evidence().candidate()).value(); + var frozenBeforeObservation = + observeAfterFreeze ? fixture.repository().beginAccountMemberRepair(TRANSITION_ID) : null; // The old owner records PRESENT_AWAITING_COVERAGE but does not satisfy the obligation. var historicalObservation = fixture.repository().markCandidateAccountIndexPresent(fixture.evidence(), member); @@ -523,14 +527,14 @@ void memberRepairPreservesAnEarlierPresentObservationUntilActualAcknowledgement( .CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED); var operation = fixture.repository().beginAccountMemberRepair(TRANSITION_ID); - assertThat(operation.originalObligation().projectionState()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingAccountIndexObligation.ProjectionState - .PRESENT_AWAITING_COVERAGE); - assertThat(operation.originalObligation().projectedMember()).isEqualTo(member); - assertThat(operation.originalObligation().inventoryRevision()) - .isEqualTo(historicalObservation.projectionInventoryRevision()); + if (observeAfterFreeze) { + assertThat(operation).isEqualTo(frozenBeforeObservation); + assertThat(operation.originalObligation().projectionInventoryRevision()).isNull(); + } else { + assertThat(operation.originalObligation().projectedMember()).isEqualTo(member); + assertThat(operation.originalObligation().inventoryRevision()) + .isEqualTo(historicalObservation.projectionInventoryRevision()); + } assertThat(fixture.repository().readSnapshot()).isEqualTo(beforeRepair); var redisOwner = @@ -541,6 +545,56 @@ void memberRepairPreservesAnEarlierPresentObservationUntilActualAcknowledgement( var acknowledgement = fixture.repository().acknowledgeAccountMemberRepair(operation, readback); assertThat(acknowledgement.member()).isEqualTo(member); + var completed = fixture.repository().readSnapshot(); + assertThat(completed.accountIndexObligations().getFirst().projectionInventoryRevision()) + .isEqualTo( + observeAfterFreeze + ? completed.inventoryRevision() + : historicalObservation.projectionInventoryRevision()); + assertThat(fixture.repository().acknowledgeAccountMemberRepair(operation, readback)) + .isEqualTo(acknowledgement); + var immutableRepairBefore = + testSchema + .dsl() + .fetchSingle( + "SELECT to_jsonb(repair)::text AS evidence FROM" + + " game_session_canonical_account_member_repair_operation repair" + + " WHERE transition_id = ?", + TRANSITION_ID) + .get("evidence", String.class); + if (observeAfterFreeze) { + // Reproduce the old COALESCE writer's completed row, not a new repair operation. + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_binding_account_index_obligation" + + " SET projection_inventory_revision = ? WHERE transition_id = ?", + historicalObservation.projectionInventoryRevision(), + TRANSITION_ID); + } + try (var migration = + getClass() + .getResourceAsStream( + "/db/migration/V1065.0.13__repair_frozen_required_member_projection.sql")) { + assertThat(migration).isNotNull(); + String correction = + new String(migration.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8) + .split("-- Runtime-family catalog registration", 2)[0]; + assertThat(testSchema.dsl().execute(correction)).isEqualTo(observeAfterFreeze ? 1 : 0); + assertThat(testSchema.dsl().execute(correction)).isZero(); + } + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT to_jsonb(repair)::text AS evidence FROM" + + " game_session_canonical_account_member_repair_operation repair" + + " WHERE transition_id = ?", + TRANSITION_ID) + .get("evidence", String.class)) + .isEqualTo(immutableRepairBefore); + assertThat(fixture.repository().readSnapshot().accountIndexObligations()) + .isEqualTo(completed.accountIndexObligations()); assertThat(fixture.repository().readSnapshot().accountIndexObligations()) .singleElement() .satisfies( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java index 96c9dcde9d..9c9da53b05 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java @@ -292,6 +292,51 @@ void committedFinalAdmissionReplayAtomicallyRetainsPreviouslySplitExecutionEvide } } + @Test + void lostTopologyCannotBeReallocatedDuringPositiveRetention() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + byte[] committed; + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var ignored = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + committed = admin.get(ascii(installation.sessionKey())); + } + fixture + .dsl() + .transaction( + configuration -> { + var damaged = org.jooq.impl.DSL.using(configuration); + // Simulate lost durable topology, not an authorized mapping retirement. + damaged.execute("SET LOCAL session_replication_role = replica"); + damaged.execute("DELETE FROM game_session_canonical_tenant_gameplay_tag"); + }); + var physical = physicalImage(); + assertThatThrownBy( + () -> + capacityOwner() + .retainCommittedBeforeCleanup( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThat( + fixture + .dsl() + .fetchCount(org.jooq.impl.DSL.table("game_session_canonical_tenant_gameplay_tag"))) + .isZero(); + assertThat(physicalImage()).isEqualTo(physical); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); + } + @Test void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff() throws Exception { @@ -313,6 +358,10 @@ void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff( deadline())) { committed = admin.get(ascii(installation.sessionKey())); } + // A lost SQL completion keeps the durable provisional fence: STOP cannot race retention. + assertThatThrownBy(() -> fixture.dsl().execute("UPDATE game_instances SET status='STOPPED'")) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("runtime row is fenced"); // No SQL final receipt was retained by the interrupted final caller. assertThat( fixture diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 8f2933f76f..285108560f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -51,6 +51,84 @@ GenericContainer redisContainer() { return REDIS; } + @Test + void explicitHandoffPreservesAcknowledgementAndRefusesRewritingBridgeForNewGrant() + throws Exception { + regionBinding = CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( + fixture.dsl(), ownerClient, ownerUri, fixture.transitionId(), sources.request, + sources.resolver, sources.entity); + var original = regionBinding.installation(); + var before = inventory.readSnapshot(); + var transfers = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var transfer = new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, transfers, capacityOwner(), + new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(transfers, tags)); + var successor = CanonicalGameplayRegionLeaseOwnerFactory.compose( + fixture.dsl(), ownerClient, ownerUri, catalog, scope -> original.incarnation, + sources.resolver, + new net.firedevops.firemud.common.runtime.RuntimeIdentity( + "game-session-service", "explicit-bridge-successor", "localhost", CLOCK.instant(), + "test", "test", "controlled-image"), + java.time.Duration.ofSeconds(30), CLOCK); + assertThat(admin.pexpire(ascii(original.grant.key()), 0)).isTrue(); + var installed = successor.installForTransition( + null, fixture.transitionId(), sources.request, transfer, deadline()); + assertThat(installed.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThatThrownBy(() -> new CanonicalGameplayRegionBindingBridgeOwner(successor, sources.entity) + .bridge(installed)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("A completed region bridge acknowledgement cannot be rewritten for a new grant"); + assertThat(inventory.readSnapshot()).isEqualTo(before); + } + + @Test + void compatibilityInstallationCannotReplaceAnExpiredOwnerWithoutFrozenTransfer() { + repairAccountMember(); + bridge(false); + var original = regionBinding.installation(); + // A caller holding the actual live private grant remains a supported compatibility case. + assertThat( + regionBinding.owner().installForTransition( + original, fixture.transitionId(), sources.request).grant) + .isSameAs(original.grant); + var statuses = new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()); + var before = statuses.find(original.source).orElseThrow(); + assertThat(admin.pexpire(ascii(original.grant.key()), 0)).isTrue(); + String rows = sqlImage(); + assertThatThrownBy( + () -> regionBinding.owner().installForTransition( + fixture.transitionId(), sources.request)) + .isInstanceOf(IllegalStateException.class); + assertThat(statuses.find(original.source)).contains(before); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(admin.get(ascii(original.grant.key()))).isNull(); + } + + @Test + void finalSourceAcceptsMemberRepairAsTheLatestInventoryMutation() { + regionBinding = + CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( + fixture.dsl(), + ownerClient, + ownerUri, + fixture.transitionId(), + sources.request, + sources.resolver, + sources.entity); + repairAccountMember(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + assertThat(source.candidate().transition().transitionId()).isEqualTo(fixture.transitionId()); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT completed_inventory_revision FROM game_session_canonical_account_member_repair_operation WHERE transition_id = ?", + fixture.transitionId()) + .get(0, java.math.BigDecimal.class) + .toBigIntegerExact()) + .isEqualTo(inventory.readSnapshot().inventoryRevision()); + } + @Test void recreatedCapacityOwnerRecoversCommittedRedisWithoutOriginalCredentialOrGrant() throws Exception { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 4b453a1cfd..e9fb844334 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -200,12 +200,32 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws try (RedisFixture redis = RedisFixture.open()) { var redisOwner = - new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + org.mockito.Mockito.spy( + new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog())); WorldFixture world = WorldFixture.open(); ControlledStableIncarnationSource incarnationSource = new ControlledStableIncarnationSource(); var bindingEvidence = provisionalEvidence(world.request()); var bindingInventory = mock(CanonicalGameplayBindingInventoryRepository.class); when(bindingInventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(bindingEvidence); + // Inventory is controlled in this component fixture. Actual transfer SQL still proves + // there are no pending executions; populated transfer coverage lives in the handoff suite. + org.mockito.Mockito.doAnswer(invocation -> { + java.util.function.Function read = + invocation.getArgument(2); + return read.apply(bindingInventory); + }).when(bindingInventory).withinTransferRead( + org.mockito.ArgumentMatchers.any(Clock.class), + org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.any()); + when(bindingInventory.readRegionTransferOriginalCandidate(TRANSITION_ID, bindingEvidence)) + .thenReturn(mock(CanonicalGameplayOriginalNewCandidate.class)); + var transferClock = Clock.fixed(NOW, ZoneOffset.UTC); + var transferTags = new CanonicalGameplayTenantGameplayTagRepository(dsl, "test", 1); + var transfers = new CanonicalGameplayRegionOwnerTransferRepository(dsl, transferClock, transferTags); + var transfer = new CanonicalGameplayRegionOwnerTransferCoordinator( + dsl, transferClock, transfers, + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + dsl, redis.ownerClient(), redis.catalog(), transferClock, transferTags), + mock(CanonicalGameplayProtectedIncarnationReceiver.class)); var firstOwner = owner( @@ -330,7 +350,34 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws incarnationSource.restoreRecoveryEvidence(); assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + var loseFirstCompletion = new java.util.concurrent.atomic.AtomicBoolean(true); + org.mockito.Mockito.doAnswer( + invocation -> { + invocation.callRealMethod(); + if (statusRepository.find(qualifiedSource).isPresent() + && loseFirstCompletion.getAndSet(false)) { + throw new IllegalStateException("controlled lost first installation completion"); + } + return null; + }) + .when(redisOwner) + .requireCurrent(org.mockito.ArgumentMatchers.any()); + assertThatThrownBy(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + var retainedFirstOwner = statusRepository.find(qualifiedSource).orElseThrow(); + assertThat(statusRepository.findTimelinePreparation(qualifiedSource).orElseThrow().phase()) + .isEqualTo( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .REDIS_INITIALIZED); + incarnationSource.changeStorageGeneration("changed-before-lost-completion-retry"); + assertThatThrownBy(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(statusRepository.find(qualifiedSource).orElseThrow()) + .isEqualTo(retainedFirstOwner); + incarnationSource.restoreStorageGeneration(); var firstInstallation = firstOwner.installForTransition(TRANSITION_ID, world.request()); + assertThat(statusRepository.find(qualifiedSource).orElseThrow()) + .isEqualTo(retainedFirstOwner); var firstStatus = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(firstStatus.regionEpoch()).isEqualTo(1L); assertThat(firstStatus.lifecycleEpoch()).isEqualTo(7L); @@ -455,7 +502,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws world, "instance-b", incarnationSource); - secondOwner.installForTransition(TRANSITION_ID, world.request()); + secondOwner.installForTransition(null, TRANSITION_ID, world.request(), transfer, NOW.toEpochMilli() + 5_000L); var secondStatus = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(secondStatus.executorFence()).isGreaterThan(firstStatus.executorFence()); assertThat(secondStatus.regionEpoch()).isEqualTo(firstStatus.regionEpoch()); @@ -496,7 +543,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws world, "instance-c", incarnationSource); - var thirdInstallation = thirdOwner.installForTransition(TRANSITION_ID, world.request()); + var thirdInstallation = thirdOwner.installForTransition(null, TRANSITION_ID, world.request(), transfer, NOW.toEpochMilli() + 5_000L); var thirdStatus = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(thirdStatus.executorFence()).isGreaterThan(progressed.executorFence()); assertThat(thirdStatus.regionEpoch()).isEqualTo(1L); @@ -517,7 +564,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws "changed-incarnation", incarnationSource); assertThatThrownBy( - () -> changedIncarnationOwner.installForTransition(TRANSITION_ID, world.request())) + () -> changedIncarnationOwner.installForTransition(null, TRANSITION_ID, world.request(), transfer, NOW.toEpochMilli() + 5_000L)) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().get(redisKey)).containsExactly(liveLeaseBeforeIncarnationChange); assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); @@ -535,13 +582,14 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws world, "instance-d", incarnationSource); - assertThatThrownBy(() -> fourthOwner.installForTransition(TRANSITION_ID, world.request())) + assertThatThrownBy(() -> fourthOwner.installForTransition(null, TRANSITION_ID, world.request(), transfer, NOW.toEpochMilli() + 5_000L)) .isInstanceOf(IllegalStateException.class); assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); world.resetReads(); - world.replaceOnRead(3, changed); + // Explicit transfer adds a pre-freeze source read; inject after SQL installation. + world.replaceOnRead(4, changed); var fifthOwner = owner( bindingInventory, @@ -550,7 +598,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws world, "instance-e", incarnationSource); - assertThatThrownBy(() -> fifthOwner.installForTransition(TRANSITION_ID, world.request())) + assertThatThrownBy(() -> fifthOwner.installForTransition(null, TRANSITION_ID, world.request(), transfer, NOW.toEpochMilli() + 5_000L)) .isInstanceOf(IllegalStateException.class); var installedBeforeChangedSourceGate = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(installedBeforeChangedSourceGate.executorFence()) @@ -571,7 +619,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws "instance-f", incarnationSource); Throwable sqlOutageFailure = - catchThrowable(() -> sixthOwner.installForTransition(TRANSITION_ID, world.request())); + catchThrowable(() -> sixthOwner.installForTransition(null, TRANSITION_ID, world.request(), transfer, NOW.toEpochMilli() + 5_000L)); dataSource.restoreConnections(); assertThat(sqlOutageFailure) .isInstanceOf(RuntimeException.class) @@ -1145,7 +1193,7 @@ void accountMemberAcknowledgementAfterRegionBridgePreservesOriginalBridgeEvidenc } @Test - void acknowledgedRegionBridgeSurvivesExpiredGrantReplacement() throws Exception { + void acknowledgedRegionBridgeRefusesCompatibilityTakeoverWithoutMutation() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); TestSchema testSchema = newTestSchema(); try { @@ -1159,8 +1207,8 @@ void acknowledgedRegionBridgeSurvivesExpiredGrantReplacement() throws Exception testSchema.dataSource(), UUID.randomUUID(), "firemud"); WorldFixture world = WorldFixture.open(runtimeTarget); try (var entitySource = EntityReferenceFixture.open()) { - CanonicalGameplayRegionOwnerCompositionFixture.ChangedGrantProof proof = - CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeThenChangedGrantRefuses( + CanonicalGameplayRegionOwnerCompositionFixture.CompatibilityTakeoverProof proof = + CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeThenCompatibilityTakeoverRefuses( testSchema.dsl(), REDIS.getHost(), REDIS.getMappedPort(REDIS_PORT), @@ -1170,13 +1218,13 @@ void acknowledgedRegionBridgeSurvivesExpiredGrantReplacement() throws Exception entitySource.client()); assertThat(proof.acknowledgedBridge().exactLostReplyRetry()).isTrue(); - assertThat(proof.replacementGrantInstalled()).isTrue(); + assertThat(proof.replacementGrantInstalled()).isFalse(); assertThat(proof.replacementExecutorFence()) - .isGreaterThan(proof.acknowledgedBridge().executorFence()); - assertThat(proof.bridgeRefused()).isTrue(); + .isEqualTo(proof.acknowledgedBridge().executorFence()); + assertThat(proof.takeoverRefused()).isTrue(); assertThat(proof.refusalMessage()) .isEqualTo( - "A completed region bridge acknowledgement cannot be rewritten for a new grant"); + "Canonical Game Session region lease is unavailable"); assertThat(proof.acknowledgementRowPreserved()).isTrue(); assertThat(proof.inventoryStatePreserved()).isTrue(); assertThat(proof.physicalBridgeStatePreserved()).isTrue(); @@ -1536,7 +1584,7 @@ void createdOriginNativeBridgeRetainsOriginalPurposeAndRejectsSourceSubstitution } @Test - void laterPlacementAcquiresFreshGrantWithoutChangingInitialTimeline() throws Exception { + void laterPlacementWithoutPrivateGrantRefusesCompatibilityTakeover() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); TestSchema schema = newTestSchema(); try { @@ -1586,8 +1634,7 @@ void laterPlacementAcquiresFreshGrantWithoutChangingInitialTimeline() throws Exc var second = new WorldFixture(secondEvidence, secondRequest); assertThat(secondLifecycle.readRequestId()).isNotEqualTo(original.readRequestId()); try (var entity = EntityReferenceFixture.open(secondRequest.getCharacterUuid())) { - var result = - CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeTwoCandidates( + assertThatThrownBy(() -> CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeTwoCandidates( schema.dsl(), REDIS.getHost(), REDIS.getMappedPort(REDIS_PORT), @@ -1600,14 +1647,9 @@ void laterPlacementAcquiresFreshGrantWithoutChangingInitialTimeline() throws Exc target.playableTarget(), second.resolver(), entity.client(), - true)); - assertThat(result.firstTimelineUnchanged()).isTrue(); - assertThat(result.initialMetaUnchanged()).isTrue(); - assertThat(result.first().exactLostReplyRetry()).isTrue(); - assertThat(result.second().exactLostReplyRetry()).isTrue(); - assertThat(result.second().executorFence()).isGreaterThan(result.first().executorFence()); - assertThat(result.foreignOwnerCapabilityRejectedWithoutStateChange()).isTrue(); - assertThat(result.expiredGrantRejectedWithoutStateChange()).isTrue(); + true))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Game Session region lease is unavailable"); } } finally { dropSchema(schema.schema()); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index db4e5551c5..b01faed5a7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -89,7 +89,7 @@ static ExistingBinding installExistingOriginalCandidate( var runtimeIdentity = new RuntimeIdentity( "game-session-service", - "final-owner-composition", + "game-session/worker α", "localhost", Instant.now(), "test", @@ -655,8 +655,8 @@ private static List createdBridgeState( physical); } - /** Reacquires a real region grant after the bridge ACK and proves that the ACK remains closed. */ - public static ChangedGrantProof installAndBridgeThenChangedGrantRefuses( + /** Refuses compatibility takeover after lease expiry without mutating owner or bridge evidence. */ + public static CompatibilityTakeoverProof installAndBridgeThenCompatibilityTakeoverRefuses( DSLContext dsl, String redisHost, int redisPort, @@ -665,7 +665,7 @@ public static ChangedGrantProof installAndBridgeThenChangedGrantRefuses( CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) throws Exception { - var capture = new AtomicReference(); + var capture = new AtomicReference(); installAndBridgeInternal( dsl, redisHost, @@ -1013,7 +1013,7 @@ private static TwoBindingProof installAndBridgeInternal( CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, SecondBinding secondBinding, - AtomicReference changedGrantProofCapture) + AtomicReference compatibilityTakeoverProofCapture) throws Exception { return installAndBridgeInternal( dsl, @@ -1024,7 +1024,7 @@ private static TwoBindingProof installAndBridgeInternal( worldRegionResolver, entityReferenceClient, secondBinding, - changedGrantProofCapture, + compatibilityTakeoverProofCapture, null, null, null); @@ -1039,7 +1039,7 @@ private static TwoBindingProof installAndBridgeInternal( CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, SecondBinding secondBinding, - AtomicReference changedGrantProofCapture, + AtomicReference compatibilityTakeoverProofCapture, CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient, java.util.function.Consumer afterBridge, BridgeSqlPhaseRunner phaseRunner) @@ -1182,9 +1182,9 @@ private static TwoBindingProof installAndBridgeInternal( afterBridge.accept(new ExistingBinding(bridgeOwner, installation, firstAcknowledgement)); } if (secondBinding == null) { - if (changedGrantProofCapture != null) { - changedGrantProofCapture.set( - reacquireGrantAfterAcknowledgement( + if (compatibilityTakeoverProofCapture != null) { + compatibilityTakeoverProofCapture.set( + refuseCompatibilityTakeoverAfterAcknowledgement( dsl, redis, scriptCatalog, @@ -1288,9 +1288,19 @@ private static TwoBindingProof installAndBridgeInternal( runtimeIdentity, Duration.ofSeconds(30), Clock.systemUTC()); - secondInstallation = - secondBridgeOwner.installForTransition( - secondTransitionId, secondBinding.worldRequest()); + var beforeTakeover = snapshotRegionOwnerSqlState( + dsl, identity.tenantId(), identity.gameInstanceId(), identity.regionId()); + try { + secondBridgeOwner.installForTransition(secondTransitionId, secondBinding.worldRequest()); + throw new AssertionError("Compatibility takeover unexpectedly succeeded"); + } catch (IllegalStateException expected) { + if (redis.admin().get(redisKey) != null + || !beforeTakeover.equals(snapshotRegionOwnerSqlState( + dsl, identity.tenantId(), identity.gameInstanceId(), identity.regionId()))) { + throw new AssertionError("Refused compatibility takeover changed region state", expected); + } + throw expected; + } } else { secondInstallation = bridgeOwner.installForTransition( @@ -1509,7 +1519,7 @@ public T run( }; } - private static ChangedGrantProof reacquireGrantAfterAcknowledgement( + private static CompatibilityTakeoverProof refuseCompatibilityTakeoverAfterAcknowledgement( DSLContext dsl, RegionRedis redis, RedisScriptCatalog scriptCatalog, @@ -1552,64 +1562,34 @@ private static ChangedGrantProof reacquireGrantAfterAcknowledgement( replacementIdentity, Duration.ofSeconds(30), Clock.systemUTC()); - var replacementInstallation = - replacementOwner.installForTransition(acknowledged.transitionId(), worldRequest); - CanonicalGameplayRegionRuntimeStatus replacementStatus = - new CanonicalGameplayRegionRuntimeStatusRepository(dsl) - .find(originalInstallation.source) - .orElseThrow(); - - String acknowledgedRowBeforeRefusal = regionBridgeRowImage(dsl, acknowledged.transitionId()); - Record acknowledgedRow = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" - + " WHERE transition_id = ?", - acknowledged.transitionId()), - "acknowledged bridge row after grant replacement"); - RegionBridgeRedisState physicalBridgeBeforeRefusal = - snapshotRegionBridgeRedisState(redis, acknowledgedRow, acknowledged.runtimeEntityId()); - var inventoryBeforeRefusal = - new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot(); - - boolean bridgeRefused; - String refusalMessage; + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var beforeInventory = inventory.readSnapshot(); + var beforeRegion = snapshotRegionOwnerSqlState( + dsl, originalInstallation.source.tenantId(), originalInstallation.source.gameInstanceId(), + originalInstallation.source.regionId()); + Record acknowledgedRow = Objects.requireNonNull(dsl.fetchOne( + "SELECT * FROM game_session_canonical_binding_region_bridge_obligation WHERE transition_id = ?", + acknowledged.transitionId())); + var beforePhysical = snapshotRegionBridgeRedisState(redis, acknowledgedRow, acknowledged.runtimeEntityId()); + String refusalMessage = null; try { - replacementOwner.bridge(replacementInstallation); - bridgeRefused = false; - refusalMessage = null; - } catch (CanonicalGameplayBindingInventoryConflictException expected) { - bridgeRefused = true; + replacementOwner.installForTransition(acknowledged.transitionId(), worldRequest); + } catch (IllegalStateException expected) { refusalMessage = expected.getMessage(); } - - String acknowledgedRowAfterRefusal = regionBridgeRowImage(dsl, acknowledged.transitionId()); - var acknowledgedRowAfter = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" - + " WHERE transition_id = ?", - acknowledged.transitionId()), - "acknowledged bridge row after changed-grant bridge refusal"); - RegionBridgeRedisState physicalBridgeAfterRefusal = - snapshotRegionBridgeRedisState(redis, acknowledgedRowAfter, acknowledged.runtimeEntityId()); - var inventoryAfterRefusal = new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot(); - boolean replacementGrantInstalled = - replacementStatus.executorFence().compareTo(acknowledged.executorFence()) > 0 - && !originalStatus - .leaseTokenCorrelation() - .equals(replacementStatus.leaseTokenCorrelation()) - && "region-owner-composition-replacement".equals(replacementStatus.ownerInstanceId()); - return new ChangedGrantProof( - acknowledged, - replacementStatus.executorFence(), - replacementGrantInstalled, - bridgeRefused, - refusalMessage, - acknowledgedRowBeforeGrant.equals(acknowledgedRowBeforeRefusal) - && acknowledgedRowBeforeRefusal.equals(acknowledgedRowAfterRefusal), - inventoryBeforeRefusal.equals(inventoryAfterRefusal), - physicalBridgeBeforeRefusal.equals(physicalBridgeAfterRefusal)); + var after = new CanonicalGameplayRegionRuntimeStatusRepository(dsl) + .find(originalInstallation.source).orElseThrow(); + if (refusalMessage == null || redis.admin().get(leaseKey) != null + || !beforeRegion.equals(snapshotRegionOwnerSqlState( + dsl, originalInstallation.source.tenantId(), originalInstallation.source.gameInstanceId(), + originalInstallation.source.regionId()))) { + throw new IllegalStateException("Compatibility takeover mutated retained owner state"); + } + return new CompatibilityTakeoverProof( + acknowledged, after.executorFence(), false, true, refusalMessage, + acknowledgedRowBeforeGrant.equals(regionBridgeRowImage(dsl, acknowledged.transitionId())), + beforeInventory.equals(inventory.readSnapshot()), + beforePhysical.equals(snapshotRegionBridgeRedisState(redis, acknowledgedRow, acknowledged.runtimeEntityId()))); } private static String regionBridgeRowImage(DSLContext dsl, UUID transitionId) { @@ -2238,11 +2218,11 @@ public record MemberRepairProof( boolean accountControlStatePreserved, boolean exactMemberRetryPreservedState) {} - public record ChangedGrantProof( + public record CompatibilityTakeoverProof( Proof acknowledgedBridge, BigInteger replacementExecutorFence, boolean replacementGrantInstalled, - boolean bridgeRefused, + boolean takeoverRefused, String refusalMessage, boolean acknowledgementRowPreserved, boolean inventoryStatePreserved, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 964b405328..10c7826c57 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -688,6 +688,53 @@ void originalCapacityExecutionRefusesForgedInitialAuthorizationAndTerminalEviden } } + @Test + void resumedFenceReceiptCannotChangeDispatchedStorageIncarnation() throws Exception { + try (var proof = new TransferSqlProof()) { + UUID id = proof.insertRawFrozenTransfer(proof.sql); + proof.insertRawTransferItem(proof.sql, id, 0); + proof.sql.execute( + "UPDATE game_session_region_owner_transfer_item SET fence_dispatch_id=?,fence_dispatch_incarnation=? WHERE transfer_id=?", + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + id); + String dispatched = proof.itemImage(id); + assertThatThrownBy( + () -> + proof.sql.transaction( + configuration -> { + var transaction = DSL.using(configuration); + var changed = "sha256:" + "b".repeat(64); + var round = UUID.randomUUID(); + transaction.execute( + "UPDATE game_session_region_owner_transfer SET incarnation_digest=?,verification_round=? WHERE transfer_id=?", + changed, + round, + id); + transaction.execute( + "UPDATE game_session_region_owner_transfer_item SET fence_readback=?,incarnation_digest=?,before_payload_digest=?,after_payload_digest=?,verified_round=? WHERE transfer_id=?", + new byte[] {1}, + changed, + changed, + changed, + round, + id); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("gs_region_fence_receipt_dispatch_incarnation"); + assertThat(proof.itemImage(id)).isEqualTo(dispatched); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + assertThat( + proof + .sql + .fetchSingle( + "SELECT state FROM game_session_region_owner_transfer WHERE transfer_id=?", + id) + .get(0, String.class)) + .isEqualTo("FROZEN"); + } + } + @Test void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throws Exception { try (var proof = new TransferSqlProof()) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 57985743cd..0393f8a0d2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(19); + assertThat(catalog.catalogEpoch()).isEqualTo(22); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -209,7 +209,10 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1065.0.7", "catalog-installation:1065.0.8", "catalog-installation:1065.0.9", - "catalog-installation:1065.0.10") + "catalog-installation:1065.0.10", + "catalog-installation:1065.0.11", + "catalog-installation:1065.0.12", + "catalog-installation:1065.0.13") .noneMatch( identity -> identity.contains(":1057:") @@ -230,7 +233,10 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1065.0.7:") || identity.contains(":1065.0.8:") || identity.contains(":1065.0.9:") - || identity.contains(":1065.0.10:")); + || identity.contains(":1065.0.10:") + || identity.contains(":1065.0.11:") + || identity.contains(":1065.0.12:") + || identity.contains(":1065.0.13:")); assertThat( f.dsl .fetchSingle( @@ -773,7 +779,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(19); + assertThat(original.catalog().catalogEpoch()).isEqualTo(22); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -927,7 +933,10 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.7", "1065.0.8", "1065.0.9", - "1065.0.10")) { + "1065.0.10", + "1065.0.11", + "1065.0.12", + "1065.0.13")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -974,7 +983,10 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.7", "1065.0.8", "1065.0.9", - "1065.0.10")) { + "1065.0.10", + "1065.0.11", + "1065.0.12", + "1065.0.13")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -1888,6 +1900,38 @@ void retainedRegionFenceDispatchUpgradePreservesPopulatedCatalogAtEpochEighteen( } } + @Test + void opaqueRuntimeOwnerIdentityUpgradePreservesRetainedRowsAndCatalogEvidence() { + try (Fixture f = fixture("1065.0.11")) { + f.populatePredecessor(); + var original = f.owner().capture(request()); + var before = f.rows(f.tables()); + before.remove(f.history); + before.remove(EPOCHS); + var history = f.historyRows(false); + var evidence = f.evidence(original.request()); + migration(f.source, f.schema, f.history, "1065.0.12").migrate(); + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat(f.historyRows(false).subList(0, history.size())).isEqualTo(history); + assertThat(f.historyRows(false)).hasSize(history.size() + 1); + assertThat(f.evidence(original.request())).isEqualTo(evidence); + assertThat(f.dsl.fetchSingle("SELECT max(catalog_epoch) FROM " + EPOCHS).get(0, Long.class)) + .isEqualTo(21L); + for (String table : + List.of( + "game_session_original_new_capacity_execution", + "game_session_capacity_evidence_charge")) { + var definition = + f.dsl + .fetchSingle( + "SELECT pg_get_constraintdef(c.oid) FROM pg_constraint c JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attname='selected_owner_id' WHERE c.conrelid=?::regclass AND c.contype='c' AND c.conkey=ARRAY[a.attnum]::smallint[]", + table) + .get(0, String.class); + assertThat(definition).contains("btrim").doesNotContain("A-Za-z0-9"); + } + } + } + @Test void capacityClosureReceiptLookupUpgradePreservesPopulatedCatalogAtEpochNineteen() { try (Fixture f = fixture("1065.0.9")) { @@ -1905,6 +1949,38 @@ void capacityClosureReceiptLookupUpgradePreservesPopulatedCatalogAtEpochNineteen } } + @Test + void fenceReceiptDispatchIncarnationUpgradePreservesPopulatedCatalogAtEpochTwenty() { + try (Fixture f = fixture("1065.0.10")) { + assertCapacityCatalogGuardUpgrade( + f, + "1065.0.11", + 19, + "V1065.0.11__bind_fence_receipt_dispatch_incarnation.sql", + Map.of(), + Map.of(), + Map.of( + "game_session_region_owner_transfer_item.gs_region_fence_receipt_dispatch_incarnation", + List.of("fence_dispatch_incarnation")), + Map.of()); + } + } + + @Test + void projectionRepairUpgradePreservesPopulatedCatalogAtEpochTwentyTwo() { + try (Fixture f = fixture("1065.0.12")) { + assertCapacityCatalogGuardUpgrade( + f, + "1065.0.13", + 21, + "V1065.0.13__repair_frozen_required_member_projection.sql", + Map.of(), + Map.of(), + Map.of(), + Map.of()); + } + } + private static void assertCapacityCatalogGuardUpgrade( Fixture f, String target, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java index 91a9080419..eb8406e950 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java @@ -96,6 +96,119 @@ void awaitResourceAndCancellationWorkerCleanup() throws InterruptedException { background.release(maximumBackground); } + @Test + void retainedInitialGrantOnlyReadsSameLiveTokenAndRejectsReplacement() throws Exception { + RedisClient client = mock(RedisClient.class); + StatefulRedisConnection connection = mock(); + RedisAsyncCommands commands = mock(); + RedisFuture principal = mock(); + RedisFuture tokenRead = mock(); + RedisFuture ttlRead = mock(); + var source = mock(CanonicalGameplayRegionRuntimeStatusRepository.Source.class); + when(source.tenantId()).thenReturn(UUID.randomUUID()); + when(source.gameInstanceId()).thenReturn(UUID.randomUUID()); + when(source.regionId()).thenReturn(UUID.randomUUID()); + var preparation = + mock(CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation.class); + when(preparation.source()).thenReturn(source); + when(preparation.regionEpoch()).thenReturn(1L); + var status = + mock(net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus.class); + String token = UUID.randomUUID().toString(); + String correlation = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(java.nio.charset.StandardCharsets.US_ASCII))); + when(preparation.leaseTokenCorrelation()).thenReturn(correlation); + when(status.leaseTokenCorrelation()).thenReturn(correlation); + when(status.regionEpoch()).thenReturn(1L); + when(status.ownerService()).thenReturn("game-session-service"); + when(status.ownerInstanceId()).thenReturn("same-instance"); + var identity = + new RuntimeIdentity( + "game-session-service", + "same-instance", + "localhost", + CLOCK.instant(), + "test", + "test", + "test"); + var owner = new CanonicalGameplayRegionLeaseRedisOwner(client, mock(RedisScriptCatalog.class)); + when(client.connect(ByteArrayCodec.INSTANCE)).thenReturn(connection); + when(connection.async()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(principal); + when(principal.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn("gamesession_coord_app"); + when(commands.get(any(byte[].class))).thenReturn(tokenRead); + when(tokenRead.get(anyLong(), eq(TimeUnit.MILLISECONDS))) + .thenAnswer(ignored -> token.getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + when(commands.pttl(any(byte[].class))).thenReturn(ttlRead); + when(ttlRead.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(1000L); + assertThat(owner.readRetainedInitialGrant(preparation, status, identity).tokenCorrelation()) + .isEqualTo(correlation); + when(ttlRead.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(-2L); + assertThatThrownBy(() -> owner.readRetainedInitialGrant(preparation, status, identity)) + .isInstanceOf(IllegalStateException.class); + when(ttlRead.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(1000L); + when(tokenRead.get(anyLong(), eq(TimeUnit.MILLISECONDS))) + .thenAnswer( + ignored -> + UUID.randomUUID().toString().getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + assertThatThrownBy(() -> owner.readRetainedInitialGrant(preparation, status, identity)) + .isInstanceOf(IllegalStateException.class); + when(status.ownerInstanceId()).thenReturn("replacement-instance"); + assertThatThrownBy(() -> owner.readRetainedInitialGrant(preparation, status, identity)) + .isInstanceOf(IllegalStateException.class); + verify(commands, org.mockito.Mockito.times(3)).aclWhoami(); + verify(commands, org.mockito.Mockito.times(3)).get(any(byte[].class)); + verify(commands, org.mockito.Mockito.times(3)).pttl(any(byte[].class)); + org.mockito.Mockito.verifyNoMoreInteractions(commands); + } + + @Test + void manualFactoryEnablesPerInstallationDeadline() { + var owner = + CanonicalGameplayRegionLeaseOwnerFactory.compose( + mock(DSLContext.class), + mock(RedisClient.class), + RedisURI.create("redis://localhost:6379"), + mock(RedisScriptCatalog.class), + mock(CanonicalGameplayRegionIncarnationSource.class), + mock( + net.firedevops.firemud.gamesession.service + .CanonicalInitialPlayerLocationRegionResolver.class), + mock(RuntimeIdentity.class), + Duration.ofSeconds(30), + CLOCK); + assertThat(ReflectionTestUtils.getField(owner, "deadlineBoundInstallation")).isEqualTo(true); + } + + @Test + void installationFreezesDeadlineAndNeverExtendsExistingBudget() { + Clock frozenClock = Clock.fixed(CLOCK.instant(), java.time.ZoneOffset.UTC); + RedisClient client = mock(RedisClient.class); + var owner = + new CanonicalGameplayRegionLeaseRedisOwner( + client, RedisURI.create("redis://localhost:6379"), mock(RedisScriptCatalog.class)); + var bounded = owner.forInstallation(frozenClock); + assertThat(ReflectionTestUtils.getField(bounded, "handoffDeadlineMillis")) + .isEqualTo(frozenClock.millis() + 5000L); + var shorter = + owner + .forHandoffDeadline(frozenClock, frozenClock.millis() + 1000L) + .forInstallation(frozenClock); + assertThat(ReflectionTestUtils.getField(shorter, "handoffDeadlineMillis")) + .isEqualTo(frozenClock.millis() + 1000L); + try (var context = Context.current().withCancellation()) { + context.cancel(new IllegalStateException("cancelled before installation")); + context.run( + () -> + assertThatThrownBy(() -> owner.forInstallation(frozenClock)) + .isInstanceOf(IllegalStateException.class)); + } + verifyNoInteractions(client); + } + @Test void timedOutHandoffRedisConnectRetainsAdmissionThroughLateClose() throws Exception { RedisClient redis = mock(); From 73fe10b1205d0eb208a510d539f602c0512d32e3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:19:03 +1300 Subject: [PATCH 03/51] Fix region handoff fixture catalog and redundant guard --- .../CanonicalGameplayRegionLeaseOwner.java | 88 +++++++++---------- ...lAdmissionOwnerIntegrationTestSupport.java | 2 + 2 files changed, 45 insertions(+), 45 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 432f28351f..60f8db1186 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -386,56 +386,54 @@ Installation installForTransition( // A stable instance ID can survive a restart. The fresh-token acquire establishes // scoped lease absence atomically and refuses every live incumbent or competing grant. grant = handoffRedisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); - if (transferOwner != null) { - redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); - requireSameSource( - source, - resolveCurrentInstallationSource( - worldRequest, - evidence, - transferSource, - transferTopologyCandidate, + redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); + requireSameSource( + source, + resolveCurrentInstallationSource( + worldRequest, + evidence, + transferSource, + transferTopologyCandidate, + transferOwner, + handoffDeadline, + worldDeadline)); + requireSameIncarnation( + incarnation, readInstallationIncarnation(transferOwner, handoffDeadline, source)); + handoffRedisOwner.verifyInitializedTimeline(grant, preparation); + if (transferCandidate == null) { + transferCandidate = + readInstallationInventory( transferOwner, handoffDeadline, - worldDeadline)); - requireSameIncarnation( - incarnation, readInstallationIncarnation(transferOwner, handoffDeadline, source)); - handoffRedisOwner.verifyInitializedTimeline(grant, preparation); - if (transferCandidate == null) { - transferCandidate = - readInstallationInventory( + inventory -> + inventory.readRegionTransferOriginalCandidate(transitionId, evidence)); + } + CanonicalGameplayOriginalNewCandidate pinnedTransferCandidate = transferCandidate; + handoffRedisOwner.requireCurrent(grant); + transferId = + frozenOriginal == null + ? transferOwner.advance(source, prior, handoffDeadline) + : transferOwner.resume(frozenOriginal, source, prior, handoffDeadline); + // Advance may retain a COMMITTED winner and activate its SQL inventory row. Keep that + // exact terminal source separate from provisional binding/bridge authority. + transferTopologyCandidate = + readInstallationInventory( transferOwner, handoffDeadline, inventory -> - inventory.readRegionTransferOriginalCandidate(transitionId, evidence)); - } - CanonicalGameplayOriginalNewCandidate pinnedTransferCandidate = transferCandidate; - handoffRedisOwner.requireCurrent(grant); - transferId = - frozenOriginal == null - ? transferOwner.advance(source, prior, handoffDeadline) - : transferOwner.resume(frozenOriginal, source, prior, handoffDeadline); - // Advance may retain a COMMITTED winner and activate its SQL inventory row. Keep that - // exact terminal source separate from provisional binding/bridge authority. - transferTopologyCandidate = - readInstallationInventory( - transferOwner, - handoffDeadline, - inventory -> - inventory.readRegionTransferAbortedCandidate( - transitionId, pinnedTransferCandidate)) - .orElse(null); - transferSource = - transferTopologyCandidate != null - ? null - : readInstallationInventory( - transferOwner, - handoffDeadline, - inventory -> - inventory.readRegionTransferCommittedSource( - transitionId, pinnedTransferCandidate)) - .orElse(null); - } + inventory.readRegionTransferAbortedCandidate( + transitionId, pinnedTransferCandidate)) + .orElse(null); + transferSource = + transferTopologyCandidate != null + ? null + : readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferCommittedSource( + transitionId, pinnedTransferCandidate)) + .orElse(null); } else { requireReusableRegionGrant( existingRegionInstallation, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java index bda0171380..33c6365e25 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java @@ -116,6 +116,8 @@ void setUp() throws Exception { .CanonicalGameplayAccountMemberRepairRedisScriptContribution(), new net.firedevops.firemud.gamesession.service .CanonicalGameplayRegionLeaseRedisScriptContribution(), + new net.firedevops.firemud.gamesession.service + .CanonicalGameplayRegionBindingBridgeRedisScriptContribution(), new net.firedevops.firemud.gamesession.service .CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())); // Allocate test PKI and start controlled source servers before the short lease starts. From 37a4590d004968fc6d724dbcd696dda200dfc868 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:22:15 +1300 Subject: [PATCH 04/51] Bound region handoff install by renewed grant lifetime --- .../CanonicalGameplayRegionLeaseOwner.java | 17 ++++++++++- ...ameplayRegionLeaseInstallDeadlineTest.java | 30 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseInstallDeadlineTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index a7fdb74556..37359944a5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -523,6 +523,11 @@ private Installation installForTransition( handoffDeadline, worldDeadline); requireSameSource(source, afterAcquire); + // Response and SQL latency consume the renewed grant, never extend its authority. + long installDeadline = + transferOwner == null + ? handoffDeadline + : renewedGrantDeadline(clock.millis(), leaseTtl, handoffDeadline); if (!recoveringInitialGrant) handoffRedisOwner.renew(grant, leaseTtl); handoffRedisOwner.requireCurrent(grant); requireSameIncarnation( @@ -591,7 +596,7 @@ private Installation installForTransition( grant.tokenCorrelation(), grant.ownerService(), grant.ownerInstanceId(), - handoffDeadline); + installDeadline); return verifyInstallation( bindingInventory, statusRepository, @@ -1410,6 +1415,16 @@ private static void requireSameIncarnation( } } + static long renewedGrantDeadline(long renewalStartedAt, Duration leaseTtl, long deadline) { + try { + long ttlMillis = leaseTtl.toMillis(); + if (ttlMillis <= 0L) throw unavailable(); + return Math.min(deadline, Math.addExact(renewalStartedAt, ttlMillis)); + } catch (ArithmeticException invalid) { + throw unavailable(); + } + } + private static long exactExpectedRegionEpoch(BigInteger value) { Objects.requireNonNull(value, "regionEpoch"); try { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseInstallDeadlineTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseInstallDeadlineTest.java new file mode 100644 index 0000000000..764478d912 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseInstallDeadlineTest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Duration; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayRegionLeaseInstallDeadlineTest { + @Test + void shortGrantBoundsInstallBeforeLongerHandoffBudget() { + assertThat(CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( + 1000L, Duration.ofMillis(100), 6000L)).isEqualTo(1100L); + } + + @Test + void longerGrantNeverExtendsHandoffBudget() { + assertThat(CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( + 1000L, Duration.ofSeconds(30), 6000L)).isEqualTo(6000L); + } + + @Test + void rejectsSubmillisecondGrantAndOverflowInsteadOfExtendingAuthority() { + assertThatThrownBy(() -> CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( + 1000L, Duration.ofNanos(1), 6000L)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( + Long.MAX_VALUE - 1, Duration.ofMillis(2), Long.MAX_VALUE)) + .isInstanceOf(IllegalStateException.class); + } +} From 3197cb8839ccb1141c43ffff9395c28597ac6275 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:27:55 +1300 Subject: [PATCH 05/51] Format grant lifetime boundary regressions --- ...ameplayRegionLeaseInstallDeadlineTest.java | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseInstallDeadlineTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseInstallDeadlineTest.java index 764478d912..025250fb73 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseInstallDeadlineTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseInstallDeadlineTest.java @@ -9,22 +9,31 @@ class CanonicalGameplayRegionLeaseInstallDeadlineTest { @Test void shortGrantBoundsInstallBeforeLongerHandoffBudget() { - assertThat(CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( - 1000L, Duration.ofMillis(100), 6000L)).isEqualTo(1100L); + assertThat( + CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( + 1000L, Duration.ofMillis(100), 6000L)) + .isEqualTo(1100L); } @Test void longerGrantNeverExtendsHandoffBudget() { - assertThat(CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( - 1000L, Duration.ofSeconds(30), 6000L)).isEqualTo(6000L); + assertThat( + CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( + 1000L, Duration.ofSeconds(30), 6000L)) + .isEqualTo(6000L); } @Test void rejectsSubmillisecondGrantAndOverflowInsteadOfExtendingAuthority() { - assertThatThrownBy(() -> CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( - 1000L, Duration.ofNanos(1), 6000L)).isInstanceOf(IllegalStateException.class); - assertThatThrownBy(() -> CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( - Long.MAX_VALUE - 1, Duration.ofMillis(2), Long.MAX_VALUE)) + assertThatThrownBy( + () -> + CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( + 1000L, Duration.ofNanos(1), 6000L)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRegionLeaseOwner.renewedGrantDeadline( + Long.MAX_VALUE - 1, Duration.ofMillis(2), Long.MAX_VALUE)) .isInstanceOf(IllegalStateException.class); } } From 7f84c1d1cd30a1cff7eadfa248d9de39b70af4e4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:01:59 +1300 Subject: [PATCH 06/51] fix: resume exact terminal transfer retention after interruption --- ...playOriginalNewCapacityExecutionOwner.java | 17 ++++++- ...ransferCapacityCustodyIntegrationTest.java | 48 ++++++++++++------- 2 files changed, 46 insertions(+), 19 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 5ef1155615..36b3b183cd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -793,7 +793,22 @@ TransferFence fenceForTransfer( return within(deadline, owner -> owner.fenceForTransfer(item, dispatch, deadline)); budget.check(); UUID dispatchId = dispatch.takeSubmission(item); - if (dispatchId == null) return readTransferFence(item, deadline); + if (dispatchId == null) { + // A prior one-use dispatch may have observed a terminal hash before SQL retention. + // Reconcile only exact positive/negative evidence; never submit the fence again. + var execution = item.execution(); + Map physical = + readExecution(execution, item.assignment().tenantGameplayTag()); + String state = text(physical.get("state")); + if ("COMMITTED".equals(state)) { + exactPhysicalBinding(physical, execution, state); + retainCommittedBeforeCleanup(execution.request(), execution.reservation(), deadline); + } else if ("CLOSED".equals(state)) { + exactPhysicalBinding(physical, execution, state); + closeOriginalAttempt(execution.request(), execution.reservation()); + } + return readTransferFence(item, deadline); + } var execution = item.execution(); Record row = find(sql(), execution); if (row == null) throw unavailable(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 24b256e711..ed86e48426 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -875,8 +875,9 @@ void lostFenceDispatchReplyRecoversOnlyItsPhysicalWitnessAndCannotRecreateIt() t } } - @Test - void interruptedFenceRetentionRecoversExactTerminalProofWithoutDispatchingAgain() + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {true, false}) + void interruptedFenceRetentionRecoversExactTerminalProofWithoutDispatchingAgain(boolean committed) throws Exception { try (var proof = new TransferSqlProof(); var credential = @@ -890,16 +891,26 @@ void interruptedFenceRetentionRecoversExactTerminalProofWithoutDispatchingAgain( .capacity(proof.sql) .authorize( proof.admission, template, account, issuer, proof.execution, transferDeadline()); - try (var physicalCommit = + var finalOwner = new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( - proof.redis, proof.scripts, proof.clock, proof.tags) - .finalizeOriginalNewOnce( - proof.admission, - template, - account, - issuer, - proof.execution, - transferDeadline())) { + proof.redis, proof.scripts, proof.clock, proof.tags); + var assignment = proof.tags.assignmentForTransition(proof.execution.transitionId()); + if (!committed) { + finalOwner.closeCapacityExecutionOnce( + proof.execution, proof.admission.candidate(), assignment, transferDeadline()); + } + try (var physicalCommit = + committed + ? new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + proof.redis, proof.scripts, proof.clock, proof.tags) + .finalizeOriginalNewOnce( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline()) + : null) { UUID id = proof.begin(); long deadline = transferDeadline(); var item = @@ -910,13 +921,14 @@ void interruptedFenceRetentionRecoversExactTerminalProofWithoutDispatchingAgain( var before = proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), deadline); var dispatch = proof.transfers.fenceDispatch(item, before); - proof - .capacity(proof.sql) - .forTransferBudget(budget) - .fenceForTransfer(item, dispatch, deadline); + UUID submission = dispatch.takeSubmission(item); + assertThat(submission).isNotNull(); + finalOwner.fenceCapacityExecutionOnce( + item.execution(), item.candidate(), item.assignment(), submission, deadline); + // Simulate process loss after terminal Redis observation but before SQL retention. return null; }); - assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED"); + assertThat(proof.executionState(proof.execution)).isEqualTo("AUTHORIZED"); assertThat(proof.itemImage(id)).contains("\"fence_readback\": null"); UUID retainedDispatch = proof @@ -927,13 +939,13 @@ void interruptedFenceRetentionRecoversExactTerminalProofWithoutDispatchingAgain( id) .get("fence_dispatch_id", UUID.class); assertThat(retainedDispatch).isNotNull(); - String original = proof.originalImage(); proof.recreateTransferOwners(); proof.fence(item); assertThat(proof.itemImage(id)) .contains(retainedDispatch.toString()) .doesNotContain("\"fence_readback\": null"); - assertThat(proof.originalImage()).isEqualTo(original); + assertThat(proof.executionState(proof.execution)) + .isEqualTo(committed ? "COMMITTED" : "CLOSED"); proof.verifyPage(id); boolean verified = proof.transfers.within( From 6697c4b7d0ca14319150c1f839533c1d7e0580e6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:28:40 +1300 Subject: [PATCH 07/51] Fix World composition fixture deadline-aware owner reads --- ...ationOwnerCompositionCrossServiceTest.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index e8c044e834..5fab67560c 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -4030,6 +4030,17 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( }) .when(initialLocationClient) .readInitialPlayerLocationRegion(Mockito.any(CanonicalInitialPlayerLocationRequest.class)); + Mockito.doAnswer( + invocation -> { + CanonicalInitialPlayerLocationRequest request = invocation.getArgument(0); + io.grpc.Deadline deadline = invocation.getArgument(1); + if (secondRequest.equals(request)) return secondObservation; + return actualInitialLocationClient.readInitialPlayerLocationRegion(request, deadline); + }) + .when(initialLocationClient) + .readInitialPlayerLocationRegion( + Mockito.any(CanonicalInitialPlayerLocationRequest.class), + Mockito.any(io.grpc.Deadline.class)); var lifecycleClient = Mockito.mock(WorldCanonicalInstanceLifecycleClient.class); Mockito.doAnswer( invocation -> { @@ -4039,6 +4050,17 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( }) .when(lifecycleClient) .read(Mockito.any(WorldCanonicalInstanceLifecycleEvidence.Request.class)); + Mockito.doAnswer( + invocation -> { + WorldCanonicalInstanceLifecycleEvidence.Request request = invocation.getArgument(0); + io.grpc.Deadline deadline = invocation.getArgument(1); + if (secondLifecycleRequest.equals(request)) return secondLifecycleEvidence; + return actualLifecycleClient.read(request, deadline); + }) + .when(lifecycleClient) + .read( + Mockito.any(WorldCanonicalInstanceLifecycleEvidence.Request.class), + Mockito.any(io.grpc.Deadline.class)); var secondWorldRegionResolver = new CanonicalInitialPlayerLocationRegionResolver( initialLocationClient, new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); From 4110065159eff67102f650bc7b0230668b3d3ffd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:43:34 +1300 Subject: [PATCH 08/51] Validate committed transfer metadata and exercise actual incarnation boundaries --- ...playOriginalNewCapacityExecutionOwner.java | 22 ++++++- .../CanonicalGameplayRegionLeaseOwner.java | 11 +++- ...meplayRegionLeaseOwnerIntegrationTest.java | 17 +++-- ...ransferCapacityCustodyIntegrationTest.java | 66 +++++++++++++++++++ 4 files changed, 109 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 36b3b183cd..4f8e2e270f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -870,6 +870,25 @@ TransferFence readTransferFence( // The immutable terminal reader independently proves the full retained positive/negative // result. readExact(execution.request(), execution.reservation(), false); + if ("COMMITTED".equals(state)) { + // Historical SQL proof alone does not qualify the currently observed transfer hash. + // Bind all committed metadata to the exact physical finalized session and SQL receipt. + Record receipt = transition(execution); + var candidate = + CanonicalGameplayOriginalNewCandidate.parseCanonical( + receipt.get("original_new_candidate_bytes", byte[].class)); + String sessionSha1 = + requireCandidateAndIndexes( + retained, + candidate, + receipt.get("original_new_final_session_sha256", String.class), + execution); + if (!sessionSha1.equals(text(physical.get("sessionSha1"))) + || !Long.toString(receipt.get("original_new_admission_at_ms", Long.class)) + .equals(text(physical.get("admissionAt"))) + || !Long.toString(receipt.get("original_new_continuity_expires_at_ms", Long.class)) + .equals(text(physical.get("continuityExpiresAt")))) throw unavailable(); + } } var output = new java.io.ByteArrayOutputStream(); physical.entrySet().stream() @@ -961,7 +980,7 @@ private Record transition(OriginalNewCapacityExecution execution) { return row; } - private void requireCandidateAndIndexes( + private String requireCandidateAndIndexes( Record row, CanonicalGameplayOriginalNewCandidate candidate, String expectedFinalDigest, @@ -1027,6 +1046,7 @@ private void requireCandidateAndIndexes( receipt.get("original_new_continuity_expires_at_ms", Long.class)))) throw unavailable(); } + return expectedFinalDigest == null ? null : sha1(actual); } finally { if (actual != null) Arrays.fill(actual, (byte) 0); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 21fbdc262c..0dd3a5e051 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -385,7 +385,7 @@ private Installation installForTransition( worldDeadline); requireSameSource(source, beforeClaimWorld.source); CanonicalGameplayRegionIncarnationSource.StableEvidence - beforeClaimIncarnation = readCurrentIncarnation(source); + beforeClaimIncarnation = readInstallationIncarnation(budget, source); requireSameIncarnation(incarnation, beforeClaimIncarnation); if (!statusRepository.matchesTimelinePreparation( initializationPreparation, @@ -1471,6 +1471,15 @@ CanonicalGameplayRegionIncarnationSource.StableEvidence readInstallationIncarnat }); } + /** Reuses the prepared initialization worker instead of acquiring a third background permit. */ + CanonicalGameplayRegionIncarnationSource.StableEvidence readInstallationIncarnation( + CanonicalGameplayOriginalNewCapacityExecutionBudget retainedBudget, + CanonicalGameplayRegionRuntimeStatusRepository.Source source) { + // The legacy non-deadline preparation has no resource permit to reuse. + if (retainedBudget != null) retainedBudget.check(); + return readCurrentIncarnation(source); + } + private static void requireSameIncarnation( CanonicalGameplayRegionIncarnationSource.StableEvidence expected, CanonicalGameplayRegionIncarnationSource.StableEvidence actual) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 33c38376fd..eb842ab743 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -566,7 +566,8 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(thirdStatus.ownerInstanceId()).isEqualTo("instance-c"); assertThat(thirdInstallation).isNotNull(); - byte[] liveLeaseBeforeIncarnationChange = redis.admin().get(redisKey); + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + assertThat(redis.admin().get(redisKey)).isNull(); Long fenceBeforeIncarnationChange = fenceSequenceValue(dsl); incarnationSource.changeStorageGeneration("storage-generation-2"); var changedIncarnationOwner = @@ -586,12 +587,12 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws transfer, transferClock.millis() + 5_000L)) .isInstanceOf(IllegalStateException.class); - assertThat(redis.admin().get(redisKey)).containsExactly(liveLeaseBeforeIncarnationChange); + assertThat(redis.admin().get(redisKey)).isNull(); assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); assertThat(fenceSequenceValue(dsl)).isEqualTo(fenceBeforeIncarnationChange); incarnationSource.restoreStorageGeneration(); - assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + assertThat(redis.admin().get(redisKey)).isNull(); WorldCanonicalInstanceLifecycleEvidence changed = changedEvidence(world.originalEvidence()); world.replaceOnRead(2, changed); var fourthOwner = @@ -776,8 +777,14 @@ void preparedTimelineIncarnationReadReusesPermitWhenBothBackgroundSlotsAreHeld() CanonicalGameplayBindingInventoryRepository::readSnapshot)) .isNotNull(); assertThat( - incarnationSource.readCurrent( - CanonicalGameplayRegionIncarnationSource.RegionScope.from(source))) + ownerWithLiveClock( + bindingInventory, + statusRepository, + redisOwner, + world, + "retained-permit-incarnation", + incarnationSource) + .readInstallationIncarnation(retainedBudget, source)) .isEqualTo(incarnation); return new CanonicalGameplayRegionRuntimeStatusRepository( retainedBudget.sql(testSchema.dsl())) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index ed86e48426..9ac7f40243 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -625,6 +625,72 @@ void capturedOriginalThatBecomesTerminalStillRequiresQualifiedTransferCompletion } } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "admissionAt,1", + "continuityExpiresAt,1", + "sessionSha1,0000000000000000000000000000000000000000" + }) + void committedTransferRejectsPhysicalMetadataDrift(String field, String replacement) + throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), proof.clock); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + proof + .capacity(proof.sql) + .authorize( + proof.admission, template, account, issuer, proof.execution, transferDeadline()); + try (var readback = + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + proof.redis, proof.scripts, proof.clock, proof.tags) + .finalizeOriginalNewOnce( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline())) { + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + new CanonicalGameplayBindingInventoryRepository(proof.sql) + .commitOriginalNewFinalAdmission(readback); + proof.fence(item); + String retained = proof.itemImage(id); + String original = proof.originalImage(); + String tag = + proof.tags.assignmentForTransition(proof.execution.transitionId()).tenantGameplayTag(); + byte[] key = + ("session:game:capacity-execution:{" + + tag + + "}:" + + proof.execution.request().admissionAttemptId()) + .getBytes(StandardCharsets.UTF_8); + try (var connection = proof.redis.connect(ByteArrayCodec.INSTANCE)) { + byte[] name = field.getBytes(StandardCharsets.UTF_8); + byte[] prior = connection.sync().hget(key, name); + assertThat(prior).isNotNull(); + connection.sync().hset(key, name, replacement.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> proof.capacity(proof.sql).readTransferFence(item, transferDeadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(proof.itemImage(id)).isEqualTo(retained); + assertThat(proof.originalImage()).isEqualTo(original); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + connection.sync().hset(key, name, prior); + assertThat(proof.capacity(proof.sql).readTransferFence(item, transferDeadline())) + .isNotNull(); + } + } + } + } + @Test void standaloneTransferObservationCancelsBlockedSqlAtItsExplicitDeadline() throws Exception { try (var proof = new TransferSqlProof(); From d0f4c44078cb80212da8330d4e105441b693c2d3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:26:22 +1300 Subject: [PATCH 09/51] Recheck final installation lease and pin canonical execution vector --- .../capacity/CapacityAdmissionDigestTest.java | 11 +++- .../original-new-execution-v1-ascii.json | 1 + .../CanonicalGameplayRegionLeaseOwner.java | 3 + ...meplayRegionLeaseOwnerIntegrationTest.java | 56 +++++++++++++++++++ 4 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 services/common-platform-core/src/test/resources/capacity/original-new-execution-v1-ascii.json diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index 239faf0682..5482da76fa 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -323,7 +323,16 @@ void originalExecutionPreservesAndEscapesOpaqueRuntimeOwnerIdentity() throws Exc 1); var json = JsonMapper.builder().build().readTree(execution.canonicalBytes()); assertThat(json.get("selectedOwnerId").asText()).isEqualTo(owner); - assertThat(execution.canonicalBytes()).isEqualTo(execution.canonicalBytes()); + if (owner.equals("owner-1")) { + // Fixed pre-change ASCII v1 vector: a serializer change must not silently rebind evidence. + try (var expected = + getClass().getResourceAsStream("/capacity/original-new-execution-v1-ascii.json")) { + assertThat(expected).isNotNull(); + assertThat(execution.canonicalBytes()).containsExactly(expected.readAllBytes()); + } + assertThat(execution.digest()) + .isEqualTo("sha256:9637a55ec42dd112eea2fab0d937e0fffe9df4ead7ab31a0905e1a57646e8f7a"); + } } for (String owner : List.of("", " ", " owner", "owner\t", "😀".repeat(121), "bad\u0000id", "bad\uD800id")) { diff --git a/services/common-platform-core/src/test/resources/capacity/original-new-execution-v1-ascii.json b/services/common-platform-core/src/test/resources/capacity/original-new-execution-v1-ascii.json new file mode 100644 index 0000000000..0d7e8521f2 --- /dev/null +++ b/services/common-platform-core/src/test/resources/capacity/original-new-execution-v1-ascii.json @@ -0,0 +1 @@ +{"admissionAttemptId":"55555555-5555-4555-8555-555555555555","admissionId":"44444444-4444-4444-8444-444444444444","candidateDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","canonicalAttemptPayload":"MTc6bXV0YXRpb25EaWdlc3QvdjEyMDphY3Rpb25GYW1pbHlTY2hlbWFJZDY6c3RyaW5nMTE4OmNhcGFjaXR5LWFkbWlzc2lvbjI1OmFjdGlvbkZhbWlseVNjaGVtYVZlcnNpb242OnN0cmluZzExOjE1OnNjb3BlNjpvYmplY3QxMTgyOjE6Mzg6dGVuYW50SWQ2OnN0cmluZzEzNjoyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjI5OnJlcXVlc3RJZDY6c3RyaW5nMTM2OjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMzExOmFkbWlzc2lvbklkNjpzdHJpbmcxMzY6NDQ0NDQ0NDQtNDQ0NC00NDQ0LTg0NDQtNDQ0NDQ0NDQ0NDQ0Njp0YXJnZXQ2Om9iamVjdDE2NDY6MTozMTI6b3duZXJTZXJ2aWNlNjpzdHJpbmcxMjA6Z2FtZS1zZXNzaW9uLXNlcnZpY2UxNTp0YXJnZXROYW1lc3BhY2U2OnN0cmluZzE0OnByb2QxMjpvd25lckNvbnRleHQ2Om9iamVjdDE1MzU6MTo5OTphY2NvdW50SWQ2OnN0cmluZzEzNjoxMTExMTExMS0xMTExLTQxMTEtODExMS0xMTExMTExMTExMTE4OnRlbmFudElkNjpzdHJpbmcxMzY6MjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyMjQ6cGxheWFibGVTdGF0ZU5hbWVzcGFjZUlkNjpzdHJpbmcxMzY6NjY2NjY2NjYtNjY2Ni00NjY2LTg2NjYtNjY2NjY2NjY2NjY2MTQ6Z2FtZUluc3RhbmNlSWQ2OnN0cmluZzEzNjo3Nzc3Nzc3Ny03Nzc3LTQ3NzctODc3Ny03Nzc3Nzc3Nzc3NzcxMTpjaGFyYWN0ZXJJZDY6c3RyaW5nMTM2Ojg4ODg4ODg4LTg4ODgtNDg4OC04ODg4LTg4ODg4ODg4ODg4ODk6c2Vzc2lvbklkNjpzdHJpbmcxMzY6OTk5OTk5OTktOTk5OS00OTk5LTg5OTktOTk5OTk5OTk5OTk5NzpyZWFsbUlkNjpzdHJpbmcxMzY6YWFhYWFhYWEtYWFhYS00YWFhLThhYWEtYWFhYWFhYWFhYWFhOTpyZXF1ZXN0SWQ2OnN0cmluZzEzNjozMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMxODpwbGF5YWJsZVN0YXRlU2NvcGU2OnN0cmluZzE2OlNIQVJFRDE1OmV4cGVjdGVkVmVyc2lvbjY6b2JqZWN0MTEwNToxOjIxODphZG1pc3Npb25BdHRlbXB0SWQ2OnN0cmluZzEzNjo1NTU1NTU1NS01NTU1LTQ1NTUtODU1NS01NTU1NTU1NTU1NTUxODpjYXBhY2l0eVJlYXJtRmVuY2U2Om51bWJlcjExOjE4Om11dGF0aW9uNjpvYmplY3QxODUzOToxOjU5Om9wZXJhdGlvbjY6c3RyaW5nMTE3OkNBUEFDSVRZX0NSRUFUSU5HMTA6cHJpb3JTaGFwZTY6b2JqZWN0MTk3OjE6MzE0OmFjdGl2ZVNlc3Npb25zNjpudW1iZXIxMTowMjM6Y29uY3VycmVudEdhbWVJbnN0YW5jZXM2Om51bWJlcjExOjAxMjpzdG9yYWdlQnl0ZXM2Om51bWJlcjExOjAxNDpyZXF1ZXN0ZWRTaGFwZTY6b2JqZWN0MTk3OjE6MzE0OmFjdGl2ZVNlc3Npb25zNjpudW1iZXIxMToxMjM6Y29uY3VycmVudEdhbWVJbnN0YW5jZXM2Om51bWJlcjExOjAxMjpzdG9yYWdlQnl0ZXM2Om51bWJlcjExOjAxNTphY2NvdW50RXZpZGVuY2U2OnN0cmluZzE4MTg4OmV5SmhiR3h2ZDA1bGQwZGhiV1Z3YkdGNVFtbHVaR2x1WjNNaU9uUnlkV1VzSW1Gc2JHOTNUbVYzU1c1emRHRnVZMlZUZEdGeWRITWlPblJ5ZFdVc0ltRnNiRzkzVUhWaWJHbGpTbTlwYmlJNmRISjFaU3dpWVhWMGFHOXlhWFI1UVhaaGFXeGhZbWxzYVhSNUlqb2lRVlpCU1V4QlFreEZJaXdpWVhWMGFHOXlhWFI1VTI5MWNtTmxSWFpwWkdWdVkyVWlPbHQ3SW1OaGJtOXVhV05oYkVWMlpXNTBTbk52YmlJNkludGNJbVYyWlc1MFJHbG5aWE4wWENJNlhDSnphR0V5TlRZNk1HVTROREk1T1Rnek0yUTROVGMxTkdaaE5UZ3paVFF4TlRCbVlUZGtPVEV6TnpRMllqZ3pZV1ZsWXpNMFlUQTFObU0wWTJOaU5UWTJZVEUxTUdNeU5Gd2lMRndpWlhabGJuUkpaRndpT2x3aVpXUmlNMkprTXpNdE9EWmxNUzB6WW1aa0xUbGxZakl0WmpZM1ptWmtZek5qT1RaaVhDSXNYQ0psZG1WdWRGUjVjR1ZjSWpwY0lsUkZUa0ZPVkY5QlZWUklUMUpKVkZsZlEwaEJUa2RGUkZ3aUxGd2liM1YwWW05NFUyVnhkV1Z1WTJWY0lqcGNJakZjSWl4Y0ltOTFkR0p2ZUZOMGNtVmhiVXRsZVZ3aU9sd2lZV05qYjNWdWREcGhkWFJvTFdGMWRHaHZjbWwwZVRwMk1UcDBaVzVoYm5Rdk1qSXlNakl5TWpJdE1qSXlNaTAwTWpJeUxUZ3lNakl0TWpJeU1qSXlNakl5TWpJeVhDSXNYQ0p5WlhGMVpYTjBSR2xuWlhOMFhDSTZYQ0p6YUdFeU5UWTZZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZVndpTEZ3aWNtVnhkV1Z6ZEVsa1hDSTZYQ0l6TXpNek16TXpNeTB6TXpNekxUUXpNek10T0RNek15MHpNek16TXpNek16TXpNek5jSWl4Y0luTmphR1Z0WVZabGNuTnBiMjVjSWpwY0ltRmpZMjkxYm5RdGRHVnVZVzUwTFdGMWRHaHZjbWwwZVMxbGRtVnVkQzkyTVZ3aUxGd2ljMjkxY21ObFJYWnBaR1Z1WTJWY0lqcDdYQ0pqWVc1dmJtbGpZV3hVWlc1aGJuUkpaRndpT2x3aU1qSXlNakl5TWpJdE1qSXlNaTAwTWpJeUxUZ3lNakl0TWpJeU1qSXlNakl5TWpJeVhDSXNYQ0pqY21WaGRHbHZibEpsY1hWbGMzUkpaRndpT2x3aU16TXpNek16TXpNdE16TXpNeTAwTXpNekxUZ3pNek10TXpNek16TXpNek16TXpNelhDSXNYQ0psZG1sa1pXNWpaVVJwWjJWemRGd2lPbHdpYzJoaE1qVTJPamN4TnpRd1pXWm1OVGN4TnpJMFpEWTNabUppTWpWak1HWTROelExTWpZeU16WTFOelJtTnpJME1qbGhPRGcxT1RJMk9EbGpNV0ZqTkRkbE9EQXpZMlZjSWl4Y0ltOXdaWEpoZEdsdmJrbGtYQ0k2WENJek16TXpNek16TXkwek16TXpMVFF6TXpNdE9ETXpNeTB6TXpNek16TXpNek16TXpOY0lpeGNJbkJ5YjNabGJtRnVZMlZMYVc1a1hDSTZYQ0pPUlZkZlIwRk5SVjlTVDFkY0lpeGNJbkpsY1hWbGMzUkVhV2RsYzNSY0lqcGNJbk5vWVRJMU5qcG1NRFpsTldVMU1HSmlaR0U1T1RFM1lqTm1aR0ZrT0dVeU56Y3pOekEyT1RObU5EbGhabU16TXpsbFpXTTNaamMxTkRoaU1XVTFOREV5TlRRMk5qa3dYQ0lzWENKelkyaGxiV0ZXWlhKemFXOXVYQ0k2TVN4Y0luTnZkWEpqWlVkaGJXVlNiM2RKWkZ3aU9sd2lNVGRjSWl4Y0luTnZkWEpqWlVkaGJXVlVaVzVoYm5STFpYbGNJanBjSW5kdmNteGtYQ0lzWENKMFlYSm5aWFJPWVcxbGMzQmhZMlZjSWpwY0luQnliMlJjSW4wc1hDSjBaVzVoYm5SQmRYUm9iM0pwZEhsSFpXNWxjbUYwYVc5dVhDSTZYQ0l5WENJc1hDSjBaVzVoYm5SQmRYUm9iM0pwZEhsVGIzVnlZMlZXWlhKemFXOXVYQ0k2WENJeVhDSXNYQ0owWlc1aGJuUkNhV3hzYVc1blVtVmpaV2x3ZEZ3aU9udGNJbVYyWlc1MFJHbG5aWE4wWENJNlhDSnphR0V5TlRZNllXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlWd2lMRndpWlhabGJuUkpaRndpT2x3aU5XRmpNVFU0TW1JdFlUUXdaQzB6TlRBMUxXRmlOREl0WmpjM05qWTFOMkkwWWpZd1hDSXNYQ0p2ZFhSaWIzaFRkSEpsWVcxTFpYbGNJanBjSW1GalkyOTFiblE2ZEdWdVlXNTBMV1Z1ZEdsMGJHVnRaVzUwT25ZeE9uUmxibUZ1ZEM4eU1qSXlNakl5TWkweU1qSXlMVFF5TWpJdE9ESXlNaTB5TWpJeU1qSXlNakl5TWpKY0lpeGNJblJsYm1GdWRFSnBiR3hwYm1kVFpYRjFaVzVqWlZ3aU9sd2lNVndpZlN4Y0luUmxibUZ1ZEVsa1hDSTZYQ0l5TWpJeU1qSXlNaTB5TWpJeUxUUXlNakl0T0RJeU1pMHlNakl5TWpJeU1qSXlNakpjSW4waUxDSmxkbVZ1ZEVScFoyVnpkQ0k2SW5Ob1lUSTFOam93WlRnME1qazVPRE16WkRnMU56VTBabUUxT0RObE5ERTFNR1poTjJRNU1UTTNORFppT0ROaFpXVmpNelJoTURVMll6UmpZMkkxTmpaaE1UVXdZekkwSWl3aVpYWmxiblJKWkNJNkltVmtZak5pWkRNekxUZzJaVEV0TTJKbVpDMDVaV0l5TFdZMk4yWm1aR016WXprMllpSXNJbTkxZEdKdmVGTmxjWFZsYm1ObElqb2lNU0lzSW05MWRHSnZlRk4wY21WaGJVdGxlU0k2SW1GalkyOTFiblE2WVhWMGFDMWhkWFJvYjNKcGRIazZkakU2ZEdWdVlXNTBMekl5TWpJeU1qSXlMVEl5TWpJdE5ESXlNaTA0TWpJeUxUSXlNakl5TWpJeU1qSXlNaUo5WFN3aVlYVjBhRzl5YVhSNVZIVndiR1VpT25zaVlXTmpiM1Z1ZEVGMWRHaHZjbWwwZVVkbGJtVnlZWFJwYjI0aU9pSXhJaXdpYVhOemRXVnlRWFYwYUVkbGJtVnlZWFJwYjI0aU9pSXhJaXdpYldWdFltVnljMmhwY0VGMWRHaHZjbWwwZVVkbGJtVnlZWFJwYjI0aU9uc2lNakl5TWpJeU1qSXRNakl5TWkwME1qSXlMVGd5TWpJdE1qSXlNakl5TWpJeU1qSXlJam9pTVNKOUxDSndjbWwyWVhSbFVtVmhiRzFIY21GdWRGWmxjbk5wYjI1eklqcGJYU3dpZEdWdVlXNTBRWFYwYUc5eWFYUjVSMlZ1WlhKaGRHbHZiaUk2ZXlJeU1qSXlNakl5TWkweU1qSXlMVFF5TWpJdE9ESXlNaTB5TWpJeU1qSXlNakl5TWpJaU9pSXlJbjBzSW5SbGJtRnVkRUpwYkd4cGJtZERkWFJ2Wm1ZaU9uc2lNakl5TWpJeU1qSXRNakl5TWkwME1qSXlMVGd5TWpJdE1qSXlNakl5TWpJeU1qSXlJanA3SW05MWRHSnZlRk5sY1hWbGJtTmxJam9pTVNJc0ltOTFkR0p2ZUZOMGNtVmhiVXRsZVNJNkltRmpZMjkxYm5RNllYVjBhQzFoZFhSb2IzSnBkSGs2ZGpFNmRHVnVZVzUwTHpJeU1qSXlNakl5TFRJeU1qSXROREl5TWkwNE1qSXlMVEl5TWpJeU1qSXlNakl5TWlJc0luUmxibUZ1ZEVGMWRHaHZjbWwwZVVkbGJtVnlZWFJwYjI0aU9pSXlJaXdpZEdWdVlXNTBRbWxzYkdsdVoxTmxjWFZsYm1ObElqb2lNU0o5Zlgwc0ltSjFibVJzWlZabGNuTnBiMjRpT2lJeUlpd2lZMkZzYkdWeVFXTmpiM1Z1ZEVsa0lqb2lNVEV4TVRFeE1URXRNVEV4TVMwME1URXhMVGd4TVRFdE1URXhNVEV4TVRFeE1URXhJaXdpWTJGc2JHVnlWMjl5YTJ4dllXUWlPaUp6Y0dsbVptVTZMeTltYVhKbGJYVmtMMjV6TDNCeWIyUXZjMkV2WjJGdFpTMXpaWE56YVc5dUxYTmxjblpwWTJVaUxDSmxiblJwZEd4bGJXVnVkRlpsY25OcGIyNGlPaUl4SWl3aVpYWmhiSFZoZEdWa1FYUWlPaUl5TURJMkxURXhMVEF5VkRBd09qQXdPakF3V2lJc0ltVjJZV3gxWVhScGIyNUpaR1Z1ZEdsMGVTSTZJbk5vWVRJMU5qcGtZV1kyTVRVME1qUXdOV0UxTW1Nd09UWTVPVFJpTldSaU9EazVObVJoTkdKaE9XSmlOV0ZoT0dJNFpqVTJZalk0WWpZNE5XSmpOVFU0TlRkallqTTRJaXdpWjJGdFpYQnNZWGxCWkcxcGMzTnBiMjVCYkd4dmQyVmtJanBtWVd4elpTd2laMkZ0WlhCc1lYbEJkbUZwYkdGaWJHVWlPblJ5ZFdVc0ltbHpjM1ZoYm1ObFJtVnVZMlVpT2lJeElpd2lhWE56ZFdWeUlqb2labWx5WlcxMVpDMWhZMk52ZFc1MExYTmxjblpwWTJVaUxDSnRaVzFpWlhKemFHbHdRWFYwYUc5eWFYUjVSMlZ1WlhKaGRHbHZiaUk2SWpFaUxDSnRaVzFpWlhKemFHbHdSWGhwYzNSeklqcG1ZV3h6WlN3aWJXVnRZbVZ5YzJocGNFeHBabVZqZVdOc1pWTjBZWFJsSWpvaVRVbFRVMGxPUnlJc0ltMWxiV0psY25Ob2FYQldaWEp6YVc5dUlqcDdJakl5TWpJeU1qSXlMVEl5TWpJdE5ESXlNaTA0TWpJeUxUSXlNakl5TWpJeU1qSXlNaUk2SWpFaWZTd2liM1YwWW05NFEyaGxZMnR3YjJsdWRITWlPbHQ3SW05MWRHSnZlRk5sY1hWbGJtTmxJam9pTUNJc0ltOTFkR0p2ZUZOMGNtVmhiVXRsZVNJNkltRmpZMjkxYm5RNllYVjBhQzFoZFhSb2IzSnBkSGs2ZGpFNllXTmpiM1Z1ZEM4eE1URXhNVEV4TVMweE1URXhMVFF4TVRFdE9ERXhNUzB4TVRFeE1URXhNVEV4TVRFaWZTeDdJbTkxZEdKdmVGTmxjWFZsYm1ObElqb2lNQ0lzSW05MWRHSnZlRk4wY21WaGJVdGxlU0k2SW1GalkyOTFiblE2WVhWMGFDMWhkWFJvYjNKcGRIazZkakU2YVhOemRXVnlMMlpwY21WdGRXUXRZV05qYjNWdWRDMXpaWEoyYVdObEluMHNleUp2ZFhSaWIzaFRaWEYxWlc1alpTSTZJakFpTENKdmRYUmliM2hUZEhKbFlXMUxaWGtpT2lKaFkyTnZkVzUwT21GMWRHZ3RZWFYwYUc5eWFYUjVPbll4T20xbGJXSmxjbk5vYVhBdk1URXhNVEV4TVRFdE1URXhNUzAwTVRFeExUZ3hNVEV0TVRFeE1URXhNVEV4TVRFeEx6SXlNakl5TWpJeUxUSXlNakl0TkRJeU1pMDRNakl5TFRJeU1qSXlNakl5TWpJeU1pSjlMSHNpYjNWMFltOTRVMlZ4ZFdWdVkyVWlPaUl4SWl3aWIzVjBZbTk0VTNSeVpXRnRTMlY1SWpvaVlXTmpiM1Z1ZERwaGRYUm9MV0YxZEdodmNtbDBlVHAyTVRwMFpXNWhiblF2TWpJeU1qSXlNakl0TWpJeU1pMDBNakl5TFRneU1qSXRNakl5TWpJeU1qSXlNakl5SWl3aWMyOTFjbU5sUlhabGJuUkVhV2RsYzNRaU9pSnphR0V5TlRZNk1HVTROREk1T1Rnek0yUTROVGMxTkdaaE5UZ3paVFF4TlRCbVlUZGtPVEV6TnpRMllqZ3pZV1ZsWXpNMFlUQTFObU0wWTJOaU5UWTJZVEUxTUdNeU5DSXNJbk52ZFhKalpVVjJaVzUwU1dRaU9pSmxaR0l6WW1Rek15MDRObVV4TFROaVptUXRPV1ZpTWkxbU5qZG1abVJqTTJNNU5tSWlmVjBzSW5CeWIzWnBjMmx2Ym1sdVoxTjBZWFIxY3lJNmJuVnNiQ3dpY1hWdmRHRnpJanA3SW0xaGVFRmpkR2wyWlZObGMzTnBiMjV6SWpvaU15SXNJbTFoZUVOdmJtTjFjbkpsYm5SSFlXMWxTVzV6ZEdGdVkyVnpJam9pTWlJc0ltMWhlRk4wYjNKaFoyVkNlWFJsY3lJNklqUXdPVFlpZlN3aWNtVnhkV1Z6ZEVsa0lqb2lNek16TXpNek16TXRNek16TXkwME16TXpMVGd6TXpNdE16TXpNek16TXpNek16TXpJaXdpY205c1pYTWlPbHRkTENKelkyaGxiV0VpT2lKaFkyTnZkVzUwTFdGMWRHZ3RaWFpwWkdWdVkyVXRZblZ1Wkd4bEwzWXhJaXdpYzI1aGNITm9iM1JKWkdWdWRHbDBlU0k2SW5Ob1lUSTFOanBoTm1RNFpqQmpPVFUzTlRGak1EZGtOekV4T1RsbVpHRTJaakZqWWpVNE16Z3lZMlprT0RNME5XTTJNVGxsWVdJeE0yRTNNV0UxTTJNeU1tVTVZVFZqSWl3aWMyOTFjbU5sUzJsdVpDSTZJazVQVGw5UVFVbEVYMFJGVFU4aUxDSnpiM1Z5WTJWU1pXWmxjbVZ1WTJWeklqcDdJbUZrYldsemMybHZibEJ2YVc1MFpYSlRibUZ3YzJodmRFUnBaMlZ6ZENJNkltRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRWlMQ0pqWVd4c1pYSkRiMjF0YVhSUWNtOXZabE5vWVRJMU5pSTZJbUZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0VpTENKallXeHNaWEpEYjI1MFpYaDBTV1FpT2lJek16TXpNek16TXkwek16TXpMVFF6TXpNdE9ETXpNeTB6TXpNek16TXpNek16TXpNaUxDSmpZV3hzWlhKUGNHVnlZWFJwYjI1SlpDSTZJak16TXpNek16TXpMVE16TXpNdE5ETXpNeTA0TXpNekxUTXpNek16TXpNek16TXpNeUlzSW1OaGJHeGxjbEpsWjJsemRISjVVbVZqYjNKa1UyaGhNalUySWpvaVlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlTSXNJbU5oYkd4bGNsUnZhMlZ1Ulhod2FYSmxjMEYwSWpvaU1qQXlOaTB4TVMwd01sUXdNRG93TVRvek1Gb2lMQ0pqWVd4c1pYSlViMnRsYmtwMGFTSTZJak16TXpNek16TXpMVE16TXpNdE5ETXpNeTA0TXpNekxUTXpNek16TXpNek16TXpNeUlzSW1OaGJHeGxjbFJ2YTJWdVUyaGhNalUySWpvaVlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlTSXNJbVZ1ZEdsMGJHVnRaVzUwVTI5MWNtTmxSR2xuWlhOMElqb2ljMmhoTWpVMk9tRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRWlMQ0puWVcxbFUyVnpjMmx2Yms5M2JtVnlVSEp2YjJaRWFXZGxjM1FpT2lKemFHRXlOVFk2WVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVNJc0luQmhhV1JTWldObGFYQjBWbUZzYVdSVmJuUnBiQ0k2Ym5Wc2JDd2ljSFZpYkdsemFHVmtVRzlzYVdONVUyVjBSR2xuWlhOMElqb2ljMmhoTWpVMk9tRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRWlMQ0p6WTI5d1pVUnBaMlZ6ZENJNkluTm9ZVEkxTmpwaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaElpd2lkMjl5YkdSRFlYQjBkWEpsU1dRaU9pSXpNek16TXpNek15MHpNek16TFRRek16TXRPRE16TXkwek16TXpNek16TXpNek16TWlMQ0ozYjNKc1pFeHBabVZqZVdOc1pVUnBaMlZ6ZENJNkluTm9ZVEkxTmpwaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaFlXRmhZV0ZoWVdGaElpd2lkMjl5YkdSU2IzZFdaWEp6YVc5dUlqb2lNQ0o5TENKemRXSnpZM0pwY0hScGIyNVRkR0YwZFhNaU9tNTFiR3dzSW5SaGNtZGxkQ0k2ZXlKaFkzUnBkbVZYYjNKc1pFVndiMk5vSWpvaU5TSXNJbU5oYm05dWFXTmhiRlpsY25OcGIyNUpaQ0k2SWpNek16TXpNek16TFRNek16TXRORE16TXkwNE16TXpMVE16TXpNek16TXpNek16TXlJc0ltTmhkR0ZzYjJkU1pYWnBjMmx2YmlJNklqY2lMQ0pqYUdGeVlXTjBaWEpEY21WaGRHbHZibEJ2YkdsamVTSTZJbEJTUlZORlJVUkZSRjlQVGt4Wklpd2lZMjl1Ym1WamRGTmpiM0JsUlhod2FYSmxjMEYwSWpvaU1qQXlOaTB4TVMwd01sUXdNRG93TWpvd01Gb2lMQ0psZG1Gc2RXRjBaV1JCZENJNklqSXdNall0TVRFdE1ERlVNak02TlRrNk5EQmFJaXdpWjJGdFpVbHVjM1JoYm1ObFNXUWlPaUkzTnpjM056YzNOeTAzTnpjM0xUUTNOemN0T0RjM055MDNOemMzTnpjM056YzNOemNpTENKd2JHRjVZV0pzWlZOMFlYUmxUbUZ0WlhOd1lXTmxTV1FpT2lJMk5qWTJOalkyTmkwMk5qWTJMVFEyTmpZdE9EWTJOaTAyTmpZMk5qWTJOalkyTmpZaUxDSndiR0Y1WVdKc1pWTjBZWFJsVTJOdmNHVWlPaUpUU0VGU1JVUWlMQ0p3YjJsdWRHVnlWbVZ5YzJsdmJpSTZJak1pTENKeVpXRnNiVWxrSWpvaVlXRmhZV0ZoWVdFdFlXRmhZUzAwWVdGaExUaGhZV0V0WVdGaFlXRmhZV0ZoWVdGaElpd2ljbVZoYkcxVGJIVm5Jam9pY0hKdlpIVmpkR2x2YmlJc0luUmhjbWRsZEVOc1lYTnpJam9pVUZWQ1RFbERYMUJTVDBSVlExUkpUMDRpTENKMFlYSm5aWFJPWVcxbGMzQmhZMlVpT2lKd2NtOWtJaXdpZEdWdVlXNTBTV1FpT2lJeU1qSXlNakl5TWkweU1qSXlMVFF5TWpJdE9ESXlNaTB5TWpJeU1qSXlNakl5TWpJaUxDSjBaVzVoYm5SVGJIVm5Jam9pZEdWdVlXNTBJaXdpZDI5eWJHUlRiSFZuSWpvaWQyOXliR1FpZlN3aWRHVnVZVzUwUVhWMGFHOXlhWFI1UjJWdVpYSmhkR2x2YmlJNklqSWlMQ0owWlc1aGJuUkNhV3hzYVc1blUyVnhkV1Z1WTJVaU9pSXhJaXdpZEdWdVlXNTBTV1FpT2lJeU1qSXlNakl5TWkweU1qSXlMVFF5TWpJdE9ESXlNaTB5TWpJeU1qSXlNakl5TWpJaUxDSjJZV3hwWkZWdWRHbHNJam9pTWpBeU5pMHhNUzB3TWxRd01Eb3dNVG96TUZvaUxDSjJZWEpwWVc1MElqb2lVRXhCV1VWU1gwRkVUVWxUVTBsUFRpSXNJblpsY21sbWFXVmtRMjl1Ym1WamRGTmpiM0JsVkc5clpXNUlZWE5vSWpvaWMyaGhNalUyT2pJeVpqaGhOR0V4T1RJek5UTXpOR1ZtWkRBek5UaGpPVE0yTTJNeVpUa3pZemM1T1dKa05XUTRORGt6T0RreE9EazVNbUV4TTJFM01EUmlNRFV6TmpJaWZRPT0xMzpjYXBhY2l0eURlbHRhNjpudW1iZXIxMToxMTE6YXVkaXRSZWFzb242OnN0cmluZzExODpjYXBhY2l0eS1hZG1pc3Npb24=","capacityRearmFence":"1","evaluationIdentity":"sha256:daf61542405a52c096994b5db8996da4ba9bb5aa8b8f56b68b685bc55857cb38","expiresAt":"2026-11-02T00:00:15Z","expiresAtMillis":"1793577615000","mutationDigest":"a78250cc70a4da7ce2933e504d1ab4d773746ff4b5a21acd18510d24b412c735","requestId":"33333333-3333-4333-8333-333333333333","reservationFence":"1","reservationId":"b1111111-1111-4111-8111-111111111111","schema":"gs-original-new-capacity-execution/v1","selectedOwnerFence":"1","selectedOwnerId":"owner-1","snapshotIdentity":"sha256:a6d8f0c95751c07d71199fda6f1cb58382cfd8345c619eab13a71a53c22e9a5c","tenantId":"22222222-2222-4222-8222-222222222222","transitionId":"44444444-4444-4444-8444-444444444444"} \ No newline at end of file diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 0dd3a5e051..3c70c956f0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -840,6 +840,9 @@ private Installation verifyInstallation( if (!installed.equals(finalStatus) || finalStatus.paused() || transferOwner != null && clock.millis() >= handoffDeadline) throw unavailable(); + // The final World/incarnation/SQL reads may outlive a short Redis lease. Recheck using + // the same bounded owner and original deadline; never return a stale installation grant. + handoffRedisOwner.requireCurrent(grant); return new Installation( transitionId, worldRequest, evidence, source, incarnation, preparation, grant, installed); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index eb842ab743..a4542e4285 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -800,6 +800,62 @@ void preparedTimelineIncarnationReadReusesPermitWhenBothBackgroundSlotsAreHeld() } } + @Test + void leaseLostDuringFinalStatusReadCannotReturnInstallation() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema schema = newTestSchema(); + try (RedisFixture redis = RedisFixture.open()) { + var status = + org.mockito.Mockito.spy(new CanonicalGameplayRegionRuntimeStatusRepository(schema.dsl())); + var redisOwner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.clientUri(PRINCIPAL, PASSWORD), redis.catalog()); + WorldFixture world = WorldFixture.open(); + var incarnation = new ControlledStableIncarnationSource(); + var evidence = provisionalEvidence(world.request()); + var inventory = mock(CanonicalGameplayBindingInventoryRepository.class); + when(inventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(evidence); + var source = source(world.originalEvidence()); + var installed = new java.util.concurrent.atomic.AtomicBoolean(); + var expired = new java.util.concurrent.atomic.AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + Object result = invocation.callRealMethod(); + installed.set(true); + return result; + }) + .when(status) + .markTimelineInstalled( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.doAnswer( + invocation -> { + Object result = invocation.callRealMethod(); + if (installed.get() && expired.compareAndSet(false, true)) { + // Deterministically model lease expiry while the final blocking SQL read is in + // flight. + String key = + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId()); + assertThat(redis.admin().pexpire(ascii(key), 0L)).isTrue(); + } + return result; + }) + .when(status) + .find(source); + var owner = owner(inventory, status, redisOwner, world, "lease-lost-final-read", incarnation); + assertThatThrownBy(() -> owner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(expired.get()).isTrue(); + assertThat(status.findTimelinePreparation(source).orElseThrow().phase()) + .isEqualTo( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INSTALLED); + } finally { + dropSchema(schema.schema()); + } + } + @Test void installationDeadlineDuringSourceRecheckLeavesPreparedPermission() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); From 4ff7464c83233ff224d52a255070141b3c71050c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:41:39 +1300 Subject: [PATCH 10/51] Align child negative fixtures with shared resolver and locked reconciliation --- ...meplayRegionLeaseOwnerIntegrationTest.java | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 57e6fa5837..cd2cc9e7eb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1318,18 +1318,14 @@ public void executeStart( if (context .sql() .contains("SET phase = 'PREPARED'")) { - java.util.concurrent.CompletableFuture.runAsync( - () -> - assertThatThrownBy( - () -> - repository - .releaseInitialTimelineNoWrite( - preparation, - retained, - NOW)) - .isInstanceOf( - IllegalStateException.class)) - .join(); + // The exact capability is already consumed. A + // second SQL + // reconciliation now waits for this transaction's + // row lock; + // joining it here would deadlock the rollback + // injector. + assertThat(retained.consumeFor(preparation)) + .isFalse(); throw new IllegalStateException( "forced SQL rollback"); } @@ -2123,7 +2119,11 @@ void laterPlacementWithoutPrivateGrantRefusesCompatibilityTakeover() throws Exce .thenAnswer(ignored -> first.original.preparationInputDigest()); when(secondEvidence.operationalRegionAssignments()) .thenAnswer(ignored -> first.original.operationalRegionAssignments()); - var second = new WorldFixture(secondEvidence, secondRequest); + // One retained owner uses one resolver, with both exact World placements routed through it. + var secondResponse = regionResponse(secondRequest, secondEvidence); + when(first.initialClient.readInitialPlayerLocationRegion(secondRequest)) + .thenReturn(secondResponse); + when(first.lifecycleClient.read(secondLifecycle)).thenReturn(secondEvidence); assertThat(secondLifecycle.readRequestId()).isNotEqualTo(original.readRequestId()); try (var entity = EntityReferenceFixture.open(secondRequest.getCharacterUuid())) { assertThatThrownBy( @@ -2137,9 +2137,9 @@ void laterPlacementWithoutPrivateGrantRefusesCompatibilityTakeover() throws Exce first.resolver(), entity.client(), new CanonicalGameplayRegionOwnerCompositionFixture.SecondBinding( - second.request(), + secondRequest, target.playableTarget(), - second.resolver(), + first.resolver(), entity.client(), true))) .isInstanceOf(IllegalStateException.class) From 8aeb5ef22f0e3b297aae0485934fda9cecb83229 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:18:01 +1300 Subject: [PATCH 11/51] Prove forward sealed dispatch receipt primitive without production activation --- ...ransferCapacityCustodyIntegrationTest.java | 60 +++++++++++++++++++ .../transfer-dispatch-receipt-prototype.lua | 59 ++++++++++++++++++ 2 files changed, 119 insertions(+) create mode 100644 services/game-session-service/src/test/resources/redis/transfer-dispatch-receipt-prototype.lua diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 9ac7f40243..e535c3f52c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -42,6 +42,66 @@ class CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest static final GenericContainer REDIS = new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + @Test + void sealedReceiptPrototypeRecoversUnsentButNeverRecreatesLostAppliedFence() throws Exception { + try (var proof = new TransferSqlProof(); + var connection = proof.redis.connect(ByteArrayCodec.INSTANCE)) { + byte[] script; + try (var input = + getClass().getResourceAsStream("/redis/transfer-dispatch-receipt-prototype.lua")) { + assertThat(input).isNotNull(); + script = input.readAllBytes(); + } + var commands = connection.sync(); + byte[][] keys = { + ascii("session:game:capacity-execution:{same}:prototype"), + ascii("session:game:capacity-transfer-receipt:{same}:prototype") + }; + commands.del(keys); + String receiptSha = commands.scriptLoad(script); + String timeSha = + commands.scriptLoad( + "local t=redis.call('TIME'); return tonumber(t[1])*1000+math.floor(tonumber(t[2])/1000)"); + java.util.function.LongSupplier redisNow = + () -> commands.evalsha(timeSha, io.lettuce.core.ScriptOutputType.INTEGER); + long cutoff = redisNow.getAsLong() + 150; + String id = UUID.randomUUID().toString(); + String digest = "sha256:" + "1".repeat(64); + String incarnation = "sha256:" + "2".repeat(64); + java.util.function.Function invoke = + action -> + commands.evalsha( + receiptSha, + io.lettuce.core.ScriptOutputType.INTEGER, + keys, + ascii(action), + ascii("exact-execution-binding"), + ascii(digest), + ascii(id), + ascii(incarnation), + ascii(Long.toString(cutoff)), + ascii(Long.toString(redisNow.getAsLong() + 5000))); + assertThat(invoke.apply("PREPARE")).isEqualTo(1); + assertThat(commands.exists(keys[0])).isZero(); + while (redisNow.getAsLong() <= cutoff) Thread.sleep(10); + assertThat(invoke.apply("OBSERVE")).isEqualTo(2); + // No in-memory one-use permission survives here: exact retained receipt is the only input. + assertThat(invoke.apply("APPLY")).isEqualTo(5); + String applied = new String(commands.hget(keys[0], ascii("state")), StandardCharsets.UTF_8); + assertThat(applied).isEqualTo("FENCED_INDETERMINATE"); + assertThat(invoke.apply("APPLY")).isEqualTo(8); + // Even after key loss, delayed application/preparation cannot recreate either authority. + commands.del(keys[0]); + assertThat(invoke.apply("APPLY")).isEqualTo(-1); + assertThat(invoke.apply("PREPARE")).isEqualTo(-1); + assertThat(commands.exists(keys[0])).isZero(); + commands.del(keys[1]); + assertThat(invoke.apply("APPLY")).isEqualTo(-1); + assertThat(invoke.apply("PREPARE")).isEqualTo(-1); + assertThat(commands.exists(keys)).isZero(); + } + } + @Override PostgreSQLContainer postgresContainer() { return POSTGRES; diff --git a/services/game-session-service/src/test/resources/redis/transfer-dispatch-receipt-prototype.lua b/services/game-session-service/src/test/resources/redis/transfer-dispatch-receipt-prototype.lua new file mode 100644 index 0000000000..e0fcfee2f3 --- /dev/null +++ b/services/game-session-service/src/test/resources/redis/transfer-dispatch-receipt-prototype.lua @@ -0,0 +1,59 @@ +-- Forward-only transfer dispatch receipt prototype. Not registered or wired to production. +-- PREPARE never touches the execution key. Its immutable cutoff must elapse before SQL seals. +-- Only the exact sealed receipt may APPLY; APPLIED is read-only and cannot recreate a lost fence. +if #KEYS ~= 2 or #ARGV ~= 7 then return -2 end +local action, binding, digest, dispatch, incarnation = ARGV[1],ARGV[2],ARGV[3],ARGV[4],ARGV[5] +local prepareUntil, mutateUntil = tonumber(ARGV[6]),tonumber(ARGV[7]) +if type(binding)~='string' or #binding==0 or #binding>524288 + or not prepareUntil or not mutateUntil or prepareUntil~=math.floor(prepareUntil) + or mutateUntil~=math.floor(mutateUntil) or prepareUntil<=0 or mutateUntil<=0 + or mutateUntil>9007199254740991 then return -2 end +if #digest~=71 or string.sub(digest,1,7)~='sha256:' or not string.match(string.sub(digest,8),'^[0-9a-f]+$') + or #incarnation~=71 or string.sub(incarnation,1,7)~='sha256:' + or not string.match(string.sub(incarnation,8),'^[0-9a-f]+$') + or #dispatch~=36 or not string.match(dispatch,'^[0-9a-f%-]+$') then return -2 end +local time=redis.call('TIME') +local seconds,micros=tonumber(time[1]),tonumber(time[2]) +if not seconds or not micros or seconds<=0 or micros<0 or micros>=1000000 + or seconds>math.floor((9007199254740991-999)/1000) then return -1 end +local now=seconds*1000+math.floor(micros/1000) +local kind=redis.call('TYPE',KEYS[2]).ok +if kind=='none' then + if action~='PREPARE' or now>=prepareUntil or prepareUntil-now>5000 then return -1 end + redis.call('HSET',KEYS[2],'digest',digest,'dispatch',dispatch,'incarnation',incarnation, + 'prepareUntil',ARGV[6],'state','PREPARED') + return 1 +end +if kind~='hash' or redis.call('PTTL',KEYS[2])~=-1 or redis.call('HLEN',KEYS[2])~=5 + or redis.call('HGET',KEYS[2],'digest')~=digest or redis.call('HGET',KEYS[2],'dispatch')~=dispatch + or redis.call('HGET',KEYS[2],'incarnation')~=incarnation + or redis.call('HGET',KEYS[2],'prepareUntil')~=ARGV[6] then return -1 end +local state=redis.call('HGET',KEYS[2],'state') +if state~='PREPARED' and state~='APPLIED' then return -1 end +if action=='PREPARE' then + if now>=prepareUntil then return -1 end + return state=='PREPARED' and 1 or -1 +end +if action=='OBSERVE' then + if now=mutateUntil then return -1 end +if target~='none' then + if target~='hash' or redis.call('PTTL',KEYS[1])~=-1 or redis.call('HLEN',KEYS[1])~=3 + or redis.call('HGET',KEYS[1],'binding')~=binding or redis.call('HGET',KEYS[1],'digest')~=digest + or redis.call('HGET',KEYS[1],'state')~='AUTHORIZED' then return -1 end +end +redis.call('HSET',KEYS[1],'binding',binding,'digest',digest,'state','FENCED_INDETERMINATE','fenceDispatchId',dispatch) +redis.call('HSET',KEYS[2],'state','APPLIED') +return 5 From 62998a6d6f71b769c84f43d7ea7731dfbe1d12f0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:01:59 +1300 Subject: [PATCH 12/51] Seal transfer preparation and issue effectful dispatch once --- .../game-session-service/runtime-and-data.md | 4 + ...m-architecture-redis-reset-and-recovery.md | 1 + .../player-access-and-session.md | 4 + ...playOriginalNewCapacityExecutionOwner.java | 27 ++ ...ayOriginalNewFinalAdmissionRedisOwner.java | 182 +++++++++++ ...GameplayRegionOwnerTransferRepository.java | 214 ++++++++++++- ...FinalAdmissionRedisScriptContribution.java | 13 +- ...14__seal_transfer_dispatch_preparation.sql | 144 +++++++++ .../game-session-region-transfer-receipt.lua | 171 ++++++++++ .../game-session-region-transfer-receipt.json | 103 ++++++ ...ransferCapacityCustodyIntegrationTest.java | 300 ++++++++++++++---- 11 files changed, 1091 insertions(+), 72 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.14__seal_transfer_dispatch_preparation.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-region-transfer-receipt.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-region-transfer-receipt.json 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 0643d118be..e531b96f89 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -32,6 +32,10 @@ After the ordinary timeline/incarnation qualification and lost-completion checks The protected receiver has a separate `REGION_OWNER_TRANSFER` purpose and signed schema. Its actual SQL source binds the frozen transfer, original execution, immutable tenant-tag assignment and complete protected deployment/registry/ACL/configuration/storage/AOF identity. Nonce, signature, exact carrier, time and two-source-read checks apply to each observation. The transfer observation shares the admitted handoff deadline across the source reads, attestor call and verification. When the caller reaches that deadline, the outstanding attestor call retains its background permit until the worker exits. Before and after fencing, and around a complete streamed physical verification before owner installation, fresh purpose-correct observations must agree with the transfer's retained incarnation. The final inventory readback uses one authenticated, non-reconnecting Redis connection across its pages. The frozen transfer commits at most one dispatch identity for the exact execution across owner generations before sending FENCE. The mutation records that identity in its deny marker. The submitting owner can retain exact readback after an acknowledged command. An interrupted caller can retain an exact matching deny marker, and ambiguous submission without that marker stays held. Later handoffs verify an existing receipt without submitting FENCE. Completed observations supply readback only. Historical SQL receipts alone cannot qualify a missing marker or a changed, unavailable, reset, restored or rolled-back store. Verification never recreates a previously retained missing fence. An inventory which cannot be completely re-read within the operation deadline remains frozen rather than dropping the currentness requirement. Normal handoff does not authorize adoption across storage loss; the owning reset/recovery qualification remains required. +New forward-only transfer dispatches additionally retain a permanent `session:game:capacity-transfer-receipt:{tenantGameplayTag}:` preparation receipt. Its exact execution digest, dispatch, storage incarnation and winning preparation nonce are bound before any fencing effect. SQL issues at most sixteen unique preparation nonces under the immutable dispatch; each issuer receives one owner-local submission capability and uses a non-reconnecting connection once. A retry can issue a different nonce, never replay an earlier submission. SQL seals only the actual observed winning nonce already in its append-only issuance history. Preparation does not change the execution target and has no clock-wait or Redis time-continuity assumption. + +After descriptor, principal and connection preflight, SQL durably issues the sealed dispatch's APPLY permission once. Only its acknowledged issuer may send APPLY. Every reconstructed or repeated caller is read-only: retained APPLIED evidence must match the exact current target, and cannot recreate a missing target. A missing, malformed or restored PREPARED receipt after issuance remains held, even with an unchanged storage incarnation. Loss of the SQL issuance acknowledgement, or process loss after issuance but before submission, remains an unknown-effect liveness boundary rather than permission to apply again. An interrupted acknowledged application can recover its retained APPLIED receipt and exact physical outcome. Historical UUID-only dispatches are not upgraded into this protocol. These receipts do not prove storage continuity, an original execution outcome, closure, capacity release or runtime activation. + An observed `COMMITTED` hash is not a transfer exemption: the existing positive continuation must verify the complete serving/session/index outcome, persist any missing final SQL receipt and retain immutable `COMMITTED` evidence before that item is handled. Missing positive proof blocks transfer. Existing exact `CLOSED` evidence likewise follows the existing independent closure-retention path. Neither terminal record is overwritten. The acquire/install/revalidate path installs the successor and immutable transfer completion in one transaction. A nonempty transfer requires its current fencing capability and complete locked inventory check. The SQL completion guard requires each captured item’s complete receipt for the current verification round, including items whose execution became terminal after capture. A terminal-only transfer requires an empty retained inventory and proof that no unresolved predecessor execution remains. The original attempts remain fenced and non-admitting. A completed transfer supports a separately phase-bound signed currentness read only while its immutable successor still matches the actual current region source; completed observations cannot enroll items, change receipts or authorize another installation. If confirmation fails after SQL commits, the same process can use its retained live grant to recheck the exact completed successor and its retained physical fences, or the exact terminal-only completion and empty inventory, before completing installation. A lost or expired grant leaves this continuation held. A process using the same stable instance ID may start a separate normal handoff only when fresh-token atomic acquisition establishes that the scoped lease is absent. That handoff revalidates the current source, protected incarnation and timeline, and completes the normal census, fencing and guarded installation under its new grant. The earlier completion remains immutable. A fully retained committed original can supply the exact topology for a first handoff. Game Session verifies its retained capacity outcome and current predecessor, then requires the existing installed timeline and a fresh successor grant. The committed original supplies no provisional admission authority. An exact retained first-NEW Account-aborted original remains part of the transfer inventory, whether abort preceded capture or completed while the transfer was frozen. Its topology lookup verifies the retained definitive abort and existing immutable mapping without restoring provisional admission authority. First negative closure still requires the complete physical candidate/index proof; already-retained CLOSED replay uses its exact permanent tombstone. Unknown history remains fenced and indeterminate, never discarded because Account or SQL records an abort. diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index b0b93b40f5..0e52bb364e 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -232,6 +232,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `session:game:index:account:` | Coordination | **Reset-sensitive with mandatory account-wide reconciliation** | Account-wide lookup is unavailable while the global index is dropped; narrow parents do not rebuild the untagged key, and account-wide access remains fenced until the complete owner-defined recovery result is consumed. | This is the one retained untagged global account exception: every member is a complete tenant-qualified `accountIndexMember`, so the key is not a tenant-local selector. Its physical layout and member contract are owned by [Global Account Active-Binding Index](./system-architecture-session-behavior.md#global-account-active-binding-index); narrower resets preserve unrelated tenants and cluster reset rebuilds the complete key. | | `session:game:account-admission:{tenantGameplayTag}::` | Coordination | **Reset-sensitive; missing or replaced state denies admission** | Loss, deletion, or storage replacement affecting the exact account/tenant/namespace slot keeps the affected scope closed. Absence is never implicit OPEN, and a retained historical CLOSED receipt does not prove current installation or authorize recreation as OPEN. | This persistent tenant-tagged hash is checked in the same slot as the tenant-local final binding CAS. Game Session must validate current protected incarnation and exact current owner/barrier state under the [Session account-intent protocol](./system-architecture-session-behavior.md#global-account-active-binding-index); reset alone proves neither installation nor account-wide coverage. | | `session:game:capacity-execution:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory original-attempt reconciliation** | Region and tenant resets preserve this family. A cluster reset requires the [Coordination reset qualification](#coordination-reset-model). Loss of an exact execution or denying record leaves its outcome indeterminate and keeps the Account reservation held. | Game Session retains the exact attempt, evidence and precharged capacity for unresolved attempts in its durable owner boundary. Prove current storage custody and reconcile the complete affected inventory before reopening. Never recreate a prior outcome from absence or historical authorization. See [original NEW capacity execution evidence](./microservices/game-session-service/runtime-and-data.md#original-new-capacity-execution-evidence). | +| `session:game:capacity-transfer-receipt:{tenantGameplayTag}:` | Coordination | **Reset-sensitive retained dispatch evidence** | Region and tenant resets preserve this family. Cluster reset requires the existing Coordination reset qualification. Missing or rolled-back preparation/application evidence never grants another APPLY permission. | Game Session retains bounded nonce issuance, the winning seal and single-use APPLY issuance in SQL. After issuance, recover only by observing an exact APPLIED receipt and current target; absent or restored PREPARED evidence stays held. Historical dispatches cannot be adopted. See [normal-handoff fencing](./microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing). | | `session:game:index:account-tenant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-qualified account lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant-scoped resume, takeover, and bounded revocation remain fenced until Game Session rebuilds it and the matching session/index obligations are acknowledged. Each index member remains an active `sessionId` value under the owner-defined schema. Reconciliation is inventory-led: it derives the exact expected active `sessionId` set from authoritative durable `GameplayBindingInventory` rows; each row's complete `bindingRef` and tenant/game/session identity supply `gameInstanceId` and directly address its canonical session record. Before deriving or writing a member or accepting readback, it exact-compares the row's canonical binding-owner `accountId` with the key's ``; a missing, malformed, or mismatched owner is rejected or quarantined and keeps the affected account/index scope fenced. It independently validates the exact session record, including controller identity `{tenantId, playableStateNamespaceId, characterId}`, server-derived `playableStateScope`, `gameInstanceId`, `bindingGeneration`, and lifecycle, then reads back the expected `sessionId` set before acknowledging the matching index/session obligations. Reconciliation never infers `gameInstanceId` from a bare member and does not use wildcard scans or invent a separate resolver. This consumes the existing owner-defined schema and producers; it does not change them. | Tenant-scoped and part of the shard-local session CAS. Reconciliation is limited to the gameplay tag and validates the canonical session record rather than treating index membership as authoritative. | | `session:game:index:tenant:{tenantGameplayTag}` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-wide active-session lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant revocation, inspection, and repair remain fenced until Game Session rebuilds or reconciles and reads back the tenant index. | Tenant-scoped and shard-local. Reconciliation must not use the global account index as a substitute or admit a binding from tenant-local key presence alone. | | `session:game:index:realm-grant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the lifecycle-bound private/playtest grant lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Reset tooling enumerates the complete expected tuple set from the exact Account v1 inventory, obtains every key through the shared `grant/v1` lifecycle-qualified realm-grant index builder, and keeps realm admission and grant-driven revocation fenced until Game Session rebuilds or reconciles and reads back those exact entries under current Account grant authority. | `grantScopeId` is the exact canonical scope ID for the complete Account-owned tuple. Reset and reconciliation never concatenate world/realm selectors or other tuple fields independently. The entries are tenant-scoped, shard-local bounded lookup evidence; Account state remains authoritative, and stale, wrong-lifecycle, or cross-tenant entries are removed. Public-production and unscoped bindings have no entry. | 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 19cc932070..b8b83f8d5e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -1,5 +1,9 @@ # Player Access and Session +## Bounded region-transfer dispatch recovery qualification + +The private forward-only dispatch correction retains at most sixteen acknowledged PostgreSQL preparation nonces, seals only the winning nonce actually observed in Redis, and durably issues APPLY once. Reconstructed owners observe only after issuance; receipt loss, restored PREPARED state, missing execution targets, historical UUID-only rows, and uncertain SQL commit acknowledgements do not authorize replay. The 27-case physical PostgreSQL/Redis class passes, including missing-effect and restored-receipt refusal; two subsequently added commit-ack-loss and competing-owner cases also pass. Final static checks, current-parent integration, combined-tree qualification and publication remain pending. These controlled fixtures do not establish deployed storage continuity, runtime activation, or a guarantee of recovery after every pre-send failure. The canonical protocol is documented in [Game Session runtime](../../architecture/microservices/game-session-service/runtime-and-data.md). + ## Target-State Authority This is a non-normative implementation tracker for player access and session. Canonical target-state authentication, admission, session, and reconnection contracts remain authoritative in [design/architecture](../../architecture/README.md) and the linked design sources below; this tracker owns current implementation status, proof evidence, gaps, and handoffs, and does not redefine those contracts. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 4f8e2e270f..c42981761b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -792,6 +792,33 @@ TransferFence fenceForTransfer( if (budget == null) return within(deadline, owner -> owner.fenceForTransfer(item, dispatch, deadline)); budget.check(); + if (dispatch.hasReceipt(item)) { + var execution = item.execution(); + Record retained = find(sql(), execution); + if (retained == null) throw unavailable(); + exact(retained, execution); + CanonicalGameplayCapacityEvidenceBudget.requireCharge( + sql(), execution, item.assignment().tenantGameplayTag()); + var finalOwner = scopedFinalOwner(); + if (!dispatch.sealed()) { + var prepared = + finalOwner.prepareTransferReceipt( + execution, item.candidate(), item.assignment(), dispatch, deadline); + dispatch.seal(prepared); + } + long result = + finalOwner.applyTransferReceipt( + execution, item.candidate(), item.assignment(), dispatch, deadline); + if (result == CAPACITY_EXECUTION_COMMITTED_OBSERVED) { + retainCommittedBeforeCleanup(execution.request(), execution.reservation(), deadline); + } else if (result == CAPACITY_EXECUTION_CLOSED_OBSERVED) { + if ("CLOSED".equals(retained.get("status", String.class))) + readExact(execution.request(), execution.reservation(), false); + else closeOriginalAttempt(execution.request(), execution.reservation()); + } else if (result != CAPACITY_EXECUTION_FENCED_INDETERMINATE + && result != CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED) throw unavailable(); + return readTransferFence(item, deadline); + } UUID dispatchId = dispatch.takeSubmission(item); if (dispatchId == null) { // A prior one-use dispatch may have observed a terminal hash before SQL retention. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index f136024b78..ac73766c1a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -405,6 +405,188 @@ long closeCapacityExecutionOnce( } /** Normal-handoff future exclusion only. A result is not an execution outcome. */ + PreparedTransferReceipt prepareTransferReceipt( + OriginalNewCapacityExecution execution, + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayRegionOwnerTransferRepository.FenceDispatch dispatch, + long deadline) { + ReceiptResult observed = + receiptAction("PREPARE", execution, candidate, assignment, dispatch, deadline); + if (observed.code() != 1 || observed.applied()) throw unavailable(); + return new PreparedTransferReceipt( + execution.digest(), + dispatch.receiptId(), + observed.nonce(), + dispatch.incarnationDigest(), + observed.applied(), + deadline, + clock); + } + + long applyTransferReceipt( + OriginalNewCapacityExecution execution, + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayRegionOwnerTransferRepository.FenceDispatch dispatch, + long deadline) { + if (!dispatch.sealed()) throw unavailable(); + ReceiptResult result = + receiptAction("APPLY_ONCE", execution, candidate, assignment, dispatch, deadline); + if (!result.applied()) throw unavailable(); + return result.code(); + } + + private ReceiptResult receiptAction( + String action, + OriginalNewCapacityExecution execution, + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayRegionOwnerTransferRepository.FenceDispatch dispatch, + long deadline) { + requireNoAmbientTransaction(); + if (scopedConnection == null) + return withinConnectionBudget( + deadline, + owner -> + owner.receiptAction(action, execution, candidate, assignment, dispatch, deadline)); + requireAssignment(assignment, candidate); + requireExecutionBinding(candidate, execution); + RedisScriptDescriptor descriptor = catalog.require("game-session.region-transfer-receipt.v1"); + if (!"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !"redis/lua/game-session-region-transfer-receipt.lua".equals(descriptor.resourcePath()) + || !List.of( + key("capacityExecution", "session:game:capacity-execution:"), + key("transferReceipt", "session:game:capacity-transfer-receipt:")) + .equals(descriptor.keys()) + || !List.of( + argument("action"), + argument("capacityExecutionBytes"), + argument("executionDigest"), + argument("dispatchId"), + argument("incarnationDigest"), + argument("preparationNonce"), + argument("absoluteDeadlineMillis"), + argument("tenantGameplayTag"), + argument("tenantId")) + .equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET) throw unavailable(); + byte[] script = scriptSource(descriptor); + StatefulRedisConnection connection = null; + try { + commandWaitMillis(); + connection = scopedConnection.get(); + var commands = requireCommands(connection); + requirePrincipal(awaitCommand(commands::aclWhoami)); + String sha = awaitCommand(() -> commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + String suffix = + "{" + assignment.tenantGameplayTag() + "}:" + execution.request().admissionAttemptId(); + if (connection.getOptions() == null || connection.getOptions().isAutoReconnect()) + throw unavailable(); + String actualAction = action; + UUID nonce; + if ("PREPARE".equals(action)) { + var submission = dispatch.issuePreparation(); + nonce = submission.takeSubmission(dispatch.receiptItem(), dispatch.receiptId()); + } else { + nonce = dispatch.sealedNonce(); + actualAction = dispatch.claimApply() ? "APPLY" : "OBSERVE"; + } + final String submittedAction = actualAction; + Object result = + awaitCommand( + () -> + commands.evalsha( + sha, + ScriptOutputType.MULTI, + new byte[][] { + ascii("session:game:capacity-execution:" + suffix), + ascii("session:game:capacity-transfer-receipt:" + suffix) + }, + ascii(submittedAction), + execution.canonicalBytes(), + ascii(execution.digest()), + ascii(dispatch.receiptId().toString()), + ascii(dispatch.incarnationDigest()), + ascii(nonce.toString()), + ascii(Long.toString(Math.min(deadline, operationDeadlineMillis))), + ascii(assignment.tenantGameplayTag()), + ascii(assignment.tenantId().toString()))); + if (!(result instanceof List values) + || values.size() != 3 + || !(values.get(0) instanceof Long code) + || !(values.get(1) instanceof byte[] nonceBytes) + || !(values.get(2) instanceof byte[] stateBytes)) throw unavailable(); + String returnedNonce = new String(nonceBytes, StandardCharsets.US_ASCII); + UUID winner; + try { + winner = UUID.fromString(returnedNonce); + } catch (IllegalArgumentException invalid) { + throw unavailable(); + } + if (!winner.toString().equals(returnedNonce)) throw unavailable(); + String state = new String(stateBytes, StandardCharsets.US_ASCII); + if (!"PREPARED".equals(state) && !"APPLIED".equals(state)) throw unavailable(); + if (!"PREPARE".equals(action) && !winner.equals(nonce)) throw unavailable(); + return new ReceiptResult(code, winner, "APPLIED".equals(state)); + } finally { + wipe(script); + if (connection != null) + scopedClose.accept( + CanonicalGameplayOriginalNewCapacityExecutionBudget.startRedisClose(connection)); + } + } + + private record ReceiptResult(long code, UUID nonce, boolean applied) {} + + static final class PreparedTransferReceipt { + private final String executionDigest; + private final UUID dispatchId; + private final UUID nonce; + private final String incarnation; + private final boolean applied; + private final long deadline; + private final Clock clock; + + private PreparedTransferReceipt( + String executionDigest, + UUID dispatchId, + UUID nonce, + String incarnation, + boolean applied, + long deadline, + Clock clock) { + this.executionDigest = executionDigest; + this.dispatchId = dispatchId; + this.nonce = nonce; + this.incarnation = incarnation; + this.applied = applied; + this.deadline = deadline; + this.clock = clock; + } + + void requireExact(OriginalNewCapacityExecution execution, UUID id, String expectedIncarnation) { + if (!execution.digest().equals(executionDigest) + || !dispatchId.equals(id) + || !incarnation.equals(expectedIncarnation) + || clock.millis() >= deadline) throw unavailable(); + } + + UUID nonce() { + return nonce; + } + + boolean applied() { + return applied; + } + } + long fenceCapacityExecutionOnce( OriginalNewCapacityExecution execution, CanonicalGameplayOriginalNewCandidate candidate, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index dbc2161754..bc19755718 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -416,38 +416,141 @@ FenceDispatch fenceDispatch( String incarnation = transfer.get("incarnation_digest", String.class); if (incarnation != null && !incarnation.equals(before.incarnationDigest())) throw unavailable(); - Record dispatched = + Record prior = tx.fetchOne( - "SELECT fence_dispatch_incarnation FROM " + "SELECT * FROM " + ITEM + " WHERE execution_digest=? AND fence_dispatch_id IS NOT NULL", item.execution().digest()); - if (dispatched != null - && !before - .incarnationDigest() - .equals(dispatched.get("fence_dispatch_incarnation"))) throw unavailable(); - if (dispatched != null - || exists( - tx, - "SELECT 1 FROM " - + ITEM - + " WHERE execution_digest=? AND fence_readback IS NOT NULL", - item.execution().digest())) return new FenceDispatch(item, null); + if (prior != null) { + if (!before.incarnationDigest().equals(prior.get("fence_dispatch_incarnation"))) + throw unavailable(); + if (prior.get("fence_prepare_ids", UUID[].class) == null + || !item.transferId().equals(prior.get("transfer_id", UUID.class)) + || item.ordinal() != prior.get("target_ordinal", Long.class) + || prior.get("fence_readback", byte[].class) != null) + return new FenceDispatch(item, null); + return new FenceDispatch( + item, + prior.get("fence_dispatch_id", UUID.class), + before.incarnationDigest(), + prior.get("fence_prepare_seal", UUID.class), + this); + } + if (exists( + tx, + "SELECT 1 FROM " + + ITEM + + " WHERE execution_digest=? AND fence_readback IS NOT NULL", + item.execution().digest())) return new FenceDispatch(item, null); if (clock.millis() >= before.expiresAtEpochMillis()) throw unavailable(); UUID dispatchId = UUID.randomUUID(); if (tx.execute( "UPDATE " + ITEM - + " SET fence_dispatch_id=?,fence_dispatch_incarnation=?" - + " WHERE transfer_id=? AND target_ordinal=?" - + " AND execution_digest=? AND fence_readback IS NULL AND fence_dispatch_id IS NULL", + + " SET fence_dispatch_id=?,fence_dispatch_incarnation=?,fence_prepare_ids=ARRAY[]::uuid[] WHERE transfer_id=? AND target_ordinal=? AND execution_digest=? AND fence_readback IS NULL AND fence_dispatch_id IS NULL", dispatchId, before.incarnationDigest(), item.transferId(), item.ordinal(), item.execution().digest()) != 1) throw unavailable(); - return new FenceDispatch(item, dispatchId); + return new FenceDispatch(item, dispatchId, before.incarnationDigest(), null, this); + }); + } + + private PreparationSubmission issuePreparation(FenceDispatch dispatch) { + return sql() + .transactionResult( + configuration -> { + var tx = DSL.using(configuration); + current(tx, dispatch.item.transferId(), true); + Record row = lockedDispatch(tx, dispatch); + UUID[] issued = row.get("fence_prepare_ids", UUID[].class); + if (issued == null + || issued.length >= 16 + || row.get("fence_prepare_seal", UUID.class) != null + || row.get("fence_readback", byte[].class) != null) throw unavailable(); + UUID nonce = UUID.randomUUID(); + if (tx.execute( + "UPDATE " + + ITEM + + " SET fence_prepare_ids=array_append(fence_prepare_ids,?::uuid) WHERE transfer_id=? AND target_ordinal=? AND fence_prepare_seal IS NULL", + nonce, + dispatch.item.transferId(), + dispatch.item.ordinal()) + != 1) throw unavailable(); + // Only this acknowledged transaction creator gets the non-reconstructible one-use + // capability. + return new PreparationSubmission(dispatch.item, dispatch.id, nonce); + }); + } + + private Record lockedDispatch(DSLContext tx, FenceDispatch dispatch) { + Record row = + tx.fetchOne( + "SELECT * FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=? FOR UPDATE", + dispatch.item.transferId(), + dispatch.item.ordinal()); + if (row == null + || !dispatch.id.equals(row.get("fence_dispatch_id", UUID.class)) + || !dispatch.incarnation.equals(row.get("fence_dispatch_incarnation", String.class))) + throw unavailable(); + return row; + } + + private void sealDispatch( + FenceDispatch dispatch, + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.PreparedTransferReceipt receipt) { + receipt.requireExact(dispatch.item.execution(), dispatch.id, dispatch.incarnation); + sql() + .transaction( + configuration -> { + var tx = DSL.using(configuration); + current(tx, dispatch.item.transferId(), true); + Record row = lockedDispatch(tx, dispatch); + UUID[] issued = row.get("fence_prepare_ids", UUID[].class); + if (issued == null || !Arrays.asList(issued).contains(receipt.nonce())) + throw unavailable(); + UUID sealed = row.get("fence_prepare_seal", UUID.class); + if (sealed != null) { + if (!sealed.equals(receipt.nonce())) throw unavailable(); + return; + } + if (receipt.applied() || row.get("fence_readback", byte[].class) != null) + throw unavailable(); + if (tx.execute( + "UPDATE " + + ITEM + + " SET fence_prepare_seal=? WHERE transfer_id=? AND target_ordinal=? AND fence_prepare_seal IS NULL", + receipt.nonce(), + dispatch.item.transferId(), + dispatch.item.ordinal()) + != 1) throw unavailable(); + }); + dispatch.sealedNonce = receipt.nonce(); + } + + private boolean claimApply(FenceDispatch dispatch) { + return sql() + .transactionResult( + configuration -> { + var tx = DSL.using(configuration); + current(tx, dispatch.item.transferId(), true); + Record row = lockedDispatch(tx, dispatch); + if (!dispatch.sealedNonce().equals(row.get("fence_prepare_seal", UUID.class))) + throw unavailable(); + if (Boolean.TRUE.equals(row.get("fence_apply_issued", Boolean.class))) return false; + if (tx.execute( + "UPDATE " + + ITEM + + " SET fence_apply_issued=true WHERE transfer_id=? AND target_ordinal=? AND NOT fence_apply_issued", + dispatch.item.transferId(), + dispatch.item.ordinal()) + != 1) throw unavailable(); + // Only the acknowledged issuer may submit APPLY. Every reconstructed owner observes + // only. + return true; }); } @@ -1185,14 +1288,91 @@ record Item( CanonicalGameplayOriginalNewCandidate candidate, CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) {} + static final class PreparationSubmission { + private final Item item; + private final UUID dispatch; + private final UUID nonce; + private boolean consumed; + + private PreparationSubmission(Item item, UUID dispatch, UUID nonce) { + this.item = item; + this.dispatch = dispatch; + this.nonce = nonce; + } + + synchronized UUID takeSubmission(Item expected, UUID expectedDispatch) { + if (consumed || item != expected || !dispatch.equals(expectedDispatch)) throw unavailable(); + consumed = true; + return nonce; + } + } + static final class FenceDispatch { private final Item item; private final UUID id; + private final String incarnation; + private final CanonicalGameplayRegionOwnerTransferRepository repository; + private UUID sealedNonce; private boolean submitted; private FenceDispatch(Item item, UUID id) { + this(item, id, null, null, null); + } + + private FenceDispatch( + Item item, + UUID id, + String incarnation, + UUID sealedNonce, + CanonicalGameplayRegionOwnerTransferRepository repository) { this.item = item; this.id = id; + this.incarnation = incarnation; + this.sealedNonce = sealedNonce; + this.repository = repository; + } + + boolean hasReceipt(Item expected) { + if (item != expected) throw unavailable(); + return repository != null && id != null; + } + + UUID receiptId() { + return id; + } + + Item receiptItem() { + return item; + } + + String incarnationDigest() { + return incarnation; + } + + boolean sealed() { + return sealedNonce != null; + } + + UUID sealedNonce() { + if (sealedNonce == null) throw unavailable(); + return sealedNonce; + } + + PreparationSubmission issuePreparation() { + if (repository == null || sealed()) throw unavailable(); + return repository.issuePreparation(this); + } + + void seal(CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.PreparedTransferReceipt proof) { + if (repository == null) throw unavailable(); + repository.sealDispatch(this, proof); + } + + synchronized boolean claimApply() { + if (repository == null || !sealed()) throw unavailable(); + if (submitted) return false; + submitted = true; + return repository.claimApply(this); } synchronized UUID takeSubmission(Item expected) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution.java index 891c1a6e50..a88ff03d54 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution.java @@ -40,7 +40,18 @@ public Collection descriptors() { if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { throw unavailable(); } - return List.of(descriptor); + try (InputStream receiptInput = + getClass() + .getResourceAsStream("/redis/scripts/game-session-region-transfer-receipt.json")) { + if (receiptInput == null) throw unavailable(); + byte[] receiptBytes = receiptInput.readNBytes(16 * 1024 + 1); + if (receiptBytes.length == 0 || receiptBytes.length > 16 * 1024) throw unavailable(); + RedisScriptDescriptor receipt = JSON.readValue(receiptBytes, RedisScriptDescriptor.class); + if (!ownerId().equals(receipt.owner()) + || !"game-session.region-transfer-receipt.v1".equals(receipt.scriptId())) + throw unavailable(); + return List.of(descriptor, receipt); + } } catch (IOException | RuntimeException failure) { throw unavailable(); } diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.14__seal_transfer_dispatch_preparation.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.14__seal_transfer_dispatch_preparation.sql new file mode 100644 index 0000000000..161c370b8d --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.14__seal_transfer_dispatch_preparation.sql @@ -0,0 +1,144 @@ +-- Historical UUID-only dispatches remain unknown-effect read-only recovery. +-- Each issued nonce permits one PREPARE submission; only its observed winning receipt may be sealed. +-- [jooq ignore start] +ALTER TABLE game_session_region_owner_transfer_item + ADD COLUMN fence_prepare_ids UUID[], + ADD COLUMN fence_prepare_seal UUID, + ADD COLUMN fence_apply_issued BOOLEAN NOT NULL DEFAULT false, + ADD CONSTRAINT gs_region_dispatch_prepare_tuple CHECK ( + (fence_prepare_ids IS NULL AND fence_prepare_seal IS NULL AND NOT fence_apply_issued) + OR (fence_prepare_ids IS NOT NULL AND fence_dispatch_id IS NOT NULL AND cardinality(fence_prepare_ids) BETWEEN 0 AND 16 + AND (fence_prepare_seal IS NULL OR fence_prepare_seal=ANY(fence_prepare_ids)) + AND (NOT fence_apply_issued OR fence_prepare_seal IS NOT NULL))); + +CREATE FUNCTION preserve_gs_region_dispatch_preparation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE parent game_session_region_owner_transfer%ROWTYPE; nonce UUID; +BEGIN + IF TG_OP='INSERT' THEN + IF NEW.fence_prepare_ids IS NOT NULL OR NEW.fence_prepare_seal IS NOT NULL THEN + RAISE EXCEPTION 'Preparation requires retained dispatch custody' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.fence_prepare_ids,NEW.fence_prepare_seal) + IS NOT DISTINCT FROM ROW(OLD.fence_prepare_ids,OLD.fence_prepare_seal) THEN + IF NEW.fence_readback IS NOT NULL AND NEW.fence_prepare_ids IS NOT NULL + AND NEW.fence_prepare_seal IS NULL THEN + RAISE EXCEPTION 'Preparation must be sealed before retained effect' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR OLD.fence_readback IS NOT NULL OR OLD.fence_prepare_seal IS NOT NULL + OR (OLD.fence_dispatch_id IS NOT NULL AND OLD.fence_prepare_ids IS NULL) + OR NEW.fence_prepare_ids IS NULL OR NEW.fence_dispatch_id IS NULL + OR array_position(NEW.fence_prepare_ids,NULL) IS NOT NULL + OR cardinality(NEW.fence_prepare_ids)>16 + OR (SELECT count(DISTINCT x) FROM unnest(NEW.fence_prepare_ids) x)<>cardinality(NEW.fence_prepare_ids) THEN + RAISE EXCEPTION 'Historical or sealed dispatch cannot be rearmed' USING ERRCODE='23514'; + END IF; + FOREACH nonce IN ARRAY NEW.fence_prepare_ids LOOP + IF nonce='00000000-0000-0000-0000-000000000000'::uuid THEN + RAISE EXCEPTION 'Preparation nonce must be nonzero' USING ERRCODE='23514'; + END IF; + END LOOP; + IF OLD.fence_prepare_ids IS NULL THEN + IF cardinality(NEW.fence_prepare_ids)<>0 OR NEW.fence_prepare_seal IS NOT NULL THEN + RAISE EXCEPTION 'Dispatch starts with no preparation submission' USING ERRCODE='23514'; + END IF; + ELSIF NEW.fence_prepare_seal IS NOT NULL THEN + IF NEW.fence_prepare_ids IS DISTINCT FROM OLD.fence_prepare_ids + OR NOT (NEW.fence_prepare_seal=ANY(OLD.fence_prepare_ids)) THEN + RAISE EXCEPTION 'Only an issued observed nonce can be sealed' USING ERRCODE='23514'; + END IF; + ELSIF cardinality(NEW.fence_prepare_ids)<>cardinality(OLD.fence_prepare_ids)+1 + OR (cardinality(OLD.fence_prepare_ids)>0 AND + NEW.fence_prepare_ids[1:cardinality(OLD.fence_prepare_ids)] IS DISTINCT FROM OLD.fence_prepare_ids) THEN + RAISE EXCEPTION 'Preparation history is append-only and bounded' USING ERRCODE='23514'; + END IF; + SELECT * INTO STRICT parent FROM game_session_region_owner_transfer + WHERE transfer_id=NEW.transfer_id FOR UPDATE; + IF parent.state <> 'FROZEN' OR NEW.fence_readback IS NOT NULL THEN + RAISE EXCEPTION 'Dispatch preparation requires frozen unsettled transfer' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER gs_region_dispatch_prepare_guard BEFORE INSERT OR UPDATE + ON game_session_region_owner_transfer_item + FOR EACH ROW EXECUTE FUNCTION preserve_gs_region_dispatch_preparation(); +CREATE FUNCTION preserve_gs_region_dispatch_apply() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE parent game_session_region_owner_transfer%ROWTYPE; +BEGIN + IF TG_OP='INSERT' THEN + IF NEW.fence_apply_issued THEN + RAISE EXCEPTION 'Apply requires acknowledged issuance' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + IF OLD.fence_apply_issued AND NOT NEW.fence_apply_issued THEN + RAISE EXCEPTION 'Apply issuance cannot be reset' USING ERRCODE='23514'; + END IF; + IF NOT OLD.fence_apply_issued AND NEW.fence_apply_issued THEN + IF current_setting('transaction_isolation') <> 'read committed' + OR OLD.fence_prepare_seal IS NULL OR OLD.fence_readback IS NOT NULL + OR ROW(NEW.fence_prepare_ids,NEW.fence_prepare_seal,NEW.fence_dispatch_id) + IS DISTINCT FROM ROW(OLD.fence_prepare_ids,OLD.fence_prepare_seal,OLD.fence_dispatch_id) THEN + RAISE EXCEPTION 'Apply requires exact sealed preparation' USING ERRCODE='23514'; + END IF; + SELECT * INTO STRICT parent FROM game_session_region_owner_transfer + WHERE transfer_id=NEW.transfer_id FOR UPDATE; + IF parent.state <> 'FROZEN' THEN + RAISE EXCEPTION 'Apply requires frozen transfer' USING ERRCODE='23514'; + END IF; + END IF; + IF NEW.fence_readback IS NOT NULL AND NEW.fence_prepare_ids IS NOT NULL AND NOT NEW.fence_apply_issued THEN + RAISE EXCEPTION 'Effect retention requires issued apply' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER gs_region_dispatch_apply_guard BEFORE INSERT OR UPDATE + ON game_session_region_owner_transfer_item + FOR EACH ROW EXECUTE FUNCTION preserve_gs_region_dispatch_apply(); +-- [jooq ignore stop] + +-- Runtime-family catalog registration +-- [jooq ignore start] +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1065.0.13' + ) AND ($needle$; + replacement := $replacement$WHERE version='1065.0.13' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.14__seal_transfer_dispatch_preparation.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.14' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.13'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.14'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.13','V1065.0.13__repair_frozen_required_member_projection.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.14'',''V1065.0.14__seal_transfer_dispatch_preparation.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-transfer-receipt.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-transfer-receipt.lua new file mode 100644 index 0000000000..3ff0b84ecb --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-transfer-receipt.lua @@ -0,0 +1,171 @@ +-- Registered forward-only transfer receipt. Historical UUID-only dispatch is not upgraded. +-- Final original-NEW controller boundary. All seven keys share the persisted tenant slot. +-- FINAL checks both OPEN barriers and replaces only the exact non-admitting session candidate +-- and capacity outcome. FENCE denies future execution without asserting historical non-execution; +-- it writes only the capacity outcome. All three installed tenant indexes remain exact. +local admissionPlaceholder = '__ORIGINAL_NEW_ADMISSION_AT_MS__' +local continuityPlaceholder = '__ORIGINAL_NEW_CONTINUITY_EXPIRES_AT_MS__' +local accountNames = {'schema', 'accountId', 'tenantId', 'playableStateNamespaceId', + 'tenantGameplayTag', 'ownerOperationId', 'ownerFenceEpoch', 'incarnationDigest', 'state'} +local issuerNames = {'schema', 'issuerId', 'tenantId', 'playableStateNamespaceId', + 'tenantGameplayTag', 'state', 'admissionEpoch', 'ownerOperationId', 'initializerOperationId', + 'initializerEpoch', 'initializerDigest', 'payloadDigest', 'payload'} +local issuerMetadataNames = {'schema', 'issuerId', 'tenantId', 'playableStateNamespaceId', + 'tenantGameplayTag', 'state', 'admissionEpoch', 'ownerOperationId', 'initializerOperationId', + 'initializerEpoch', 'initializerDigest', 'payloadDigest'} +local sessionNames = {'schemaVersion', 'admissionState', 'originalCandidate', 'bindingGeneration', + 'accountIndexState', 'issuerIndexState', 'regionBridgeState', 'admissionAt', 'authTokenHash', + 'authTokenIssuedAt', 'authTokenExpiresAt', 'tokenGeneration', 'issuanceFence', 'rebindHandle', + 'continuityBindingExpiresAt', 'membershipBaseline', 'authorityTuple', 'outboxCheckpoints', + 'canonicalSessionDurationMillis', 'capacityExecutionDigest'} +-- Runtime IDs are opaque Unicode text, not ASCII identifiers. Count valid scalar values. +local function ownerIdentity(value) + if type(value) ~= 'string' or #value == 0 or #value > 480 + or string.byte(value, 1) <= 32 or string.byte(value, #value) <= 32 then return false end + local i, count = 1, 0 + while i <= #value do + local first = string.byte(value, i) + local width, cp + if first < 128 then width, cp = 1, first + elseif first >= 194 and first <= 223 then width, cp = 2, first - 192 + elseif first >= 224 and first <= 239 then width, cp = 3, first - 224 + elseif first >= 240 and first <= 244 then width, cp = 4, first - 240 + else return false end + if i + width - 1 > #value then return false end + for offset = 1, width - 1 do + local byte = string.byte(value, i + offset) + if byte < 128 or byte > 191 then return false end + cp = cp * 64 + byte - 128 + end + if cp == 0 or (width == 3 and cp < 2048) or (width == 4 and cp < 65536) + or (cp >= 55296 and cp <= 57343) or cp > 1114111 then return false end + count = count + 1 + if count > 120 then return false end + i = i + width + end + return true +end +local function uuid(value) + return type(value) == 'string' and #value == 36 and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' + 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$') ~= nil +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 exactNumber(value) + if not positive(value) or #value > 16 then return nil end + local number = tonumber(value) + if not number or number > 9007199254740991 or string.format('%.0f', number) ~= value then return nil end + return number +end +local function objectWithFields(value, fields) + if type(value) ~= 'table' then return false end + local count = 0 + for key, item in pairs(value) do + count = count + 1 + local found = false + for _, name in ipairs(fields) do if key == name then found = true end end + if not found or item == cjson.null then return false end + end + if count ~= #fields then return false end + for _, name in ipairs(fields) do if value[name] == nil then return false end end + return true +end +local function equal(left, right, depth) + if depth > 64 or type(left) ~= type(right) then return false end + if type(left) ~= 'table' then return left == right end + local countLeft, countRight = 0, 0 + for key, value in pairs(left) do + countLeft = countLeft + 1 + if not equal(value, right[key], depth + 1) then return false end + end + for _ in pairs(right) do countRight = countRight + 1 end + return countLeft == countRight +end +local function decode(bytes, maximum) + if type(bytes) ~= 'string' or #bytes == 0 or #bytes > maximum then return nil end + local ok, value = pcall(cjson.decode, bytes) + if not ok or type(value) ~= 'table' then return nil end + return value +end +if #KEYS ~= 2 or #ARGV ~= 9 then return -2 end +local action, binding, digest, dispatch, incarnation = ARGV[1],ARGV[2],ARGV[3],ARGV[4],ARGV[5] +local nonce, mutateUntil = ARGV[6],tonumber(ARGV[7]) +if type(binding)~='string' or #binding==0 or #binding>1048576 + or not uuid(nonce) or not mutateUntil or mutateUntil~=math.floor(mutateUntil) + or mutateUntil<=0 or mutateUntil>9007199254740991 then return {-2,'',''} end +if #digest~=71 or string.sub(digest,1,7)~='sha256:' or not string.match(string.sub(digest,8),'^[0-9a-f]+$') + or #incarnation~=71 or string.sub(incarnation,1,7)~='sha256:' + or not string.match(string.sub(incarnation,8),'^[0-9a-f]+$') + or #dispatch~=36 or not string.match(dispatch,'^[0-9a-f%-]+$') then return -2 end +local time=redis.call('TIME') +local seconds,micros=tonumber(time[1]),tonumber(time[2]) +if not seconds or not micros or seconds<=0 or micros<0 or micros>=1000000 + or seconds>math.floor((9007199254740991-999)/1000) then return -1 end +local now=seconds*1000+math.floor(micros/1000) +local capacity = decode(binding, 1048576) +if not capacity or capacity.schema ~= 'gs-original-new-capacity-execution/v1' + or not uuid(capacity.admissionAttemptId) or not uuid(capacity.tenantId) + or capacity.tenantId ~= ARGV[9] or not uuid(dispatch) + or not string.match(ARGV[8], '^g[1-9][0-9]*%-[0-9a-f]+$') or #ARGV[8]>44 then return -2 end +local slot='{'..ARGV[8]..'}' +if KEYS[1]~='session:game:capacity-execution:'..slot..':'..capacity.admissionAttemptId + or KEYS[2]~='session:game:capacity-transfer-receipt:'..slot..':'..capacity.admissionAttemptId then return -2 end +local kind=redis.call('TYPE',KEYS[2]).ok +if kind=='none' then + if action~='PREPARE' or now>=mutateUntil then return {-1,'',''} end + -- A nonce has exactly one transport submission. No clock wait or replay permission. + redis.call('HSET',KEYS[2],'digest',digest,'dispatch',dispatch,'incarnation',incarnation, + 'nonce',nonce,'state','PREPARED') + return {1,nonce,'PREPARED'} +end +if kind~='hash' or redis.call('PTTL',KEYS[2])~=-1 or redis.call('HLEN',KEYS[2])~=5 + or redis.call('HGET',KEYS[2],'digest')~=digest or redis.call('HGET',KEYS[2],'dispatch')~=dispatch + or redis.call('HGET',KEYS[2],'incarnation')~=incarnation then return {-1,'',''} end +local state=redis.call('HGET',KEYS[2],'state') +local winner=redis.call('HGET',KEYS[2],'nonce') +if not uuid(winner) or (state~='PREPARED' and state~='APPLIED') then return {-1,'',''} end +if action=='PREPARE' then + if now>=mutateUntil then return {-1,'',''} end + return {1,winner,state} +end +if winner~=nonce then return {-1,'',''} end +if action~='APPLY' and action~='OBSERVE' then return {-2,'',''} end +local target=redis.call('TYPE',KEYS[1]).ok +local function exactOutcome() + if target~='hash' or redis.call('PTTL',KEYS[1])~=-1 + or redis.call('HGET',KEYS[1],'binding')~=binding or redis.call('HGET',KEYS[1],'digest')~=digest then return -1 end + local phase,fields=redis.call('HGET',KEYS[1],'state'),redis.call('HLEN',KEYS[1]) + if phase=='FENCED_INDETERMINATE' and fields==4 + and redis.call('HGET',KEYS[1],'fenceDispatchId')==dispatch then return 8 end + if phase=='CLOSED' and fields==3 then return 7 end + if phase=='COMMITTED' and fields==6 then + local sha=redis.call('HGET',KEYS[1],'sessionSha1') + local at=exactNumber(redis.call('HGET',KEYS[1],'admissionAt')) + local untilTime=exactNumber(redis.call('HGET',KEYS[1],'continuityExpiresAt')) + if type(sha)=='string' and #sha==40 and string.match(sha,'^[0-9a-f]+$') + and at and untilTime and untilTime>at and untilTime-at<=300000 then return 9 end + end + return -1 +end +if state=='APPLIED' then return {exactOutcome(),winner,state} end +-- Once SQL has issued APPLY, later callers may only observe. A restored PREPARED +-- receipt is not authority to reapply, even with the same nonce/incarnation. +if action=='OBSERVE' then return {-1,winner,state} end +if now>=mutateUntil then return -1 end +local prior=exactOutcome() +if prior==7 or prior==9 then + redis.call('HSET',KEYS[2],'state','APPLIED') + return {prior,winner,'APPLIED'} +end +if now>=mutateUntil then return -1 end +if target~='none' then + if target~='hash' or redis.call('PTTL',KEYS[1])~=-1 or redis.call('HLEN',KEYS[1])~=3 + or redis.call('HGET',KEYS[1],'binding')~=binding or redis.call('HGET',KEYS[1],'digest')~=digest + or redis.call('HGET',KEYS[1],'state')~='AUTHORIZED' then return -1 end +end +redis.call('HSET',KEYS[1],'binding',binding,'digest',digest,'state','FENCED_INDETERMINATE','fenceDispatchId',dispatch) +redis.call('HSET',KEYS[2],'state','APPLIED') +return {5,winner,'APPLIED'} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-transfer-receipt.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-transfer-receipt.json new file mode 100644 index 0000000000..72cfbcf2c1 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-transfer-receipt.json @@ -0,0 +1,103 @@ +{ + "scriptId": "game-session.region-transfer-receipt.v1", + "resourcePath": "redis/lua/game-session-region-transfer-receipt.lua", + "sha256": "e5dfd05a0865fe6a6c6651e3da9ba8215f70f5eef8b39fef6686670f86914fc8", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "capacityExecution", + "ownedPrefix": "session:game:capacity-execution:", + "hashTagDeclaration": "REQUIRED" + }, + { + "name": "transferReceipt", + "ownedPrefix": "session:game:capacity-transfer-receipt:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + { + "name": "action" + }, + { + "name": "capacityExecutionBytes" + }, + { + "name": "executionDigest" + }, + { + "name": "dispatchId" + }, + { + "name": "incarnationDigest" + }, + { + "name": "preparationNonce" + }, + { + "name": "absoluteDeadlineMillis" + }, + { + "name": "tenantGameplayTag" + }, + { + "name": "tenantId" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "PREPARED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "PREPARATION_OBSERVED", + "category": "SUCCESS", + "effect": "NON_MUTATING" + }, + { + "code": "FENCED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "EXACT_REPLAY", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "TERMINAL_RECEIPT_SEALED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "NOT_READY", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "REFUSED", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID_ARGUMENTS", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "tailLossBehavior": "Each durable issued nonce permits one PREPARE submission on a non-reconnecting connection. SQL seals only the actual observed issued winning nonce and issues APPLY once. Every later attempt is read-only OBSERVE. Missing, malformed or restored PREPARED receipts after issuance stay held; retained APPLIED requires exact current target evidence and cannot recreate a missing target. Historical UUID-only dispatches remain held. Protected-incarnation checks remain mandatory; no same-epoch storage continuity is inferred.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + { + "callerVersion": "v1", + "payloadVersion": "none" + } + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index e535c3f52c..a75073afeb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -43,62 +43,254 @@ class CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); @Test - void sealedReceiptPrototypeRecoversUnsentButNeverRecreatesLostAppliedFence() throws Exception { + void restoredPreparedReceiptCannotReapplyAfterDurableIssuance() throws Exception { try (var proof = new TransferSqlProof(); var connection = proof.redis.connect(ByteArrayCodec.INSTANCE)) { - byte[] script; - try (var input = - getClass().getResourceAsStream("/redis/transfer-dispatch-receipt-prototype.lua")) { - assertThat(input).isNotNull(); - script = input.readAllBytes(); - } + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + long deadline = transferDeadline(); + proof.transfers.within( + deadline, + budget -> { + var before = proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), deadline); + var dispatch = proof.transfers.fenceDispatch(item, before); + proof + .capacity(proof.sql) + .forTransferBudget(budget) + .fenceForTransfer(item, dispatch, deadline); + return null; + }); + byte[] receipt = + ascii( + "session:game:capacity-transfer-receipt:{" + + item.assignment().tenantGameplayTag() + + "}:" + + item.execution().request().admissionAttemptId()); var commands = connection.sync(); - byte[][] keys = { - ascii("session:game:capacity-execution:{same}:prototype"), - ascii("session:game:capacity-transfer-receipt:{same}:prototype") - }; - commands.del(keys); - String receiptSha = commands.scriptLoad(script); - String timeSha = - commands.scriptLoad( - "local t=redis.call('TIME'); return tonumber(t[1])*1000+math.floor(tonumber(t[2])/1000)"); - java.util.function.LongSupplier redisNow = - () -> commands.evalsha(timeSha, io.lettuce.core.ScriptOutputType.INTEGER); - long cutoff = redisNow.getAsLong() + 150; - String id = UUID.randomUUID().toString(); - String digest = "sha256:" + "1".repeat(64); - String incarnation = "sha256:" + "2".repeat(64); - java.util.function.Function invoke = - action -> - commands.evalsha( - receiptSha, - io.lettuce.core.ScriptOutputType.INTEGER, - keys, - ascii(action), - ascii("exact-execution-binding"), - ascii(digest), - ascii(id), - ascii(incarnation), - ascii(Long.toString(cutoff)), - ascii(Long.toString(redisNow.getAsLong() + 5000))); - assertThat(invoke.apply("PREPARE")).isEqualTo(1); - assertThat(commands.exists(keys[0])).isZero(); - while (redisNow.getAsLong() <= cutoff) Thread.sleep(10); - assertThat(invoke.apply("OBSERVE")).isEqualTo(2); - // No in-memory one-use permission survives here: exact retained receipt is the only input. - assertThat(invoke.apply("APPLY")).isEqualTo(5); - String applied = new String(commands.hget(keys[0], ascii("state")), StandardCharsets.UTF_8); - assertThat(applied).isEqualTo("FENCED_INDETERMINATE"); - assertThat(invoke.apply("APPLY")).isEqualTo(8); - // Even after key loss, delayed application/preparation cannot recreate either authority. - commands.del(keys[0]); - assertThat(invoke.apply("APPLY")).isEqualTo(-1); - assertThat(invoke.apply("PREPARE")).isEqualTo(-1); - assertThat(commands.exists(keys[0])).isZero(); - commands.del(keys[1]); - assertThat(invoke.apply("APPLY")).isEqualTo(-1); - assertThat(invoke.apply("PREPARE")).isEqualTo(-1); - assertThat(commands.exists(keys)).isZero(); + assertThat(new String(commands.hget(receipt, ascii("state")), StandardCharsets.US_ASCII)) + .isEqualTo("APPLIED"); + // Simulate same-incarnation rollback, not a detectable reset. It must never grant APPLY + // again. + commands.hset(receipt, ascii("state"), ascii("PREPARED")); + proof.losePhysicalExecution(item.execution()); + String retained = proof.itemImage(id); + proof.recreateTransferOwners(); + assertThatThrownBy(() -> proof.fence(item)).isInstanceOf(IllegalStateException.class); + assertThat(proof.physicalExecutionExists(item.execution())).isFalse(); + assertThat(proof.itemImage(id)).isEqualTo(retained); + assertThatThrownBy( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer_item SET fence_apply_issued=false WHERE transfer_id=?", + id)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + + @Test + void preparationSubmissionIsOneUseAndHistoryIsBounded() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + long deadline = transferDeadline(); + proof.transfers.within( + deadline, + budget -> { + var before = proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), deadline); + var dispatch = proof.transfers.fenceDispatch(item, before); + var submission = dispatch.issuePreparation(); + assertThat(submission.takeSubmission(item, dispatch.receiptId())).isNotNull(); + assertThatThrownBy(() -> submission.takeSubmission(item, dispatch.receiptId())) + .isInstanceOf(IllegalStateException.class); + for (int index = 1; index < 16; index++) dispatch.issuePreparation(); + assertThatThrownBy(dispatch::issuePreparation) + .isInstanceOf(IllegalStateException.class); + return null; + }); + assertThat(proof.physicalExecutionExists(item.execution())).isFalse(); + } + } + + @Test + void lostApplyIssuanceCommitAcknowledgementNeverDispatchesOrRearms() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + var failed = new AtomicBoolean(); + var delegate = proof.sql.configuration().connectionProvider(); + var connections = + java.util.Collections.synchronizedMap( + new java.util.IdentityHashMap()); + var provider = + new org.jooq.ConnectionProvider() { + public java.sql.Connection acquire() { + var actual = delegate.acquire(); + var proxy = + (java.sql.Connection) + java.lang.reflect.Proxy.newProxyInstance( + java.sql.Connection.class.getClassLoader(), + new Class[] {java.sql.Connection.class}, + (object, method, args) -> { + Object result; + try { + result = method.invoke(actual, args); + } catch (java.lang.reflect.InvocationTargetException error) { + throw error.getCause(); + } + if (method.getName().equals("commit") + && !failed.get() + && Boolean.TRUE.equals( + proof + .sql + .fetchOne( + "SELECT fence_apply_issued FROM game_session_region_owner_transfer_item WHERE transfer_id=?", + id) + .get(0, Boolean.class)) + && failed.compareAndSet(false, true)) { + throw new java.sql.SQLException( + "Controlled lost APPLY issuance commit acknowledgement"); + } + return result; + }); + connections.put(proxy, actual); + return proxy; + } + + public void release(java.sql.Connection connection) { + delegate.release(connections.remove(connection)); + } + }; + var broken = + new CanonicalGameplayRegionOwnerTransferRepository( + DSL.using(proof.sql.configuration().derive(provider)), proof.clock, proof.tags); + long deadline = transferDeadline(); + assertThatThrownBy( + () -> + broken.within( + deadline, + budget -> { + var before = + proof.receiver.observeForRegionOwnerTransfer( + id, item.ordinal(), deadline); + var dispatch = broken.fenceDispatch(item, before); + return proof + .capacity(proof.sql) + .forTransferBudget(budget) + .fenceForTransfer(item, dispatch, deadline); + })) + .isInstanceOf(RuntimeException.class); + assertThat(failed).isTrue(); + assertThat( + proof + .sql + .fetchOne( + "SELECT fence_apply_issued FROM game_session_region_owner_transfer_item WHERE transfer_id=?", + id) + .get(0, Boolean.class)) + .isTrue(); + assertThat(proof.physicalExecutionExists(item.execution())).isFalse(); + String retained = proof.itemImage(id); + proof.recreateTransferOwners(); + assertThatThrownBy(() -> proof.fence(item)).isInstanceOf(IllegalStateException.class); + assertThat(proof.itemImage(id)).isEqualTo(retained); + assertThat(proof.physicalExecutionExists(item.execution())).isFalse(); + } + } + + @Test + void competingOwnersIssueApplyExactlyOnce() throws Exception { + var issued = new java.util.concurrent.atomic.AtomicInteger(); + var listener = + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + if (context.sql() != null + && context.sql().contains("SET fence_apply_issued=true") + && context.rows() == 1) issued.incrementAndGet(); + } + }; + try (var proof = new TransferSqlProof(listener)) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + var ready = new java.util.concurrent.CountDownLatch(2); + var start = new java.util.concurrent.CountDownLatch(1); + try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { + java.util.concurrent.Callable race = + () -> { + ready.countDown(); + if (!start.await(10, java.util.concurrent.TimeUnit.SECONDS)) + throw new AssertionError("race start timed out"); + try { + proof.fence(item); + return true; + } catch (IllegalStateException held) { + return false; + } + }; + var first = executor.submit(race); + var second = executor.submit(race); + assertThat(ready.await(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + start.countDown(); + boolean firstCompleted = first.get(15, java.util.concurrent.TimeUnit.SECONDS); + boolean secondCompleted = second.get(15, java.util.concurrent.TimeUnit.SECONDS); + assertThat(firstCompleted || secondCompleted).isTrue(); + } + assertThat(issued.get()).isEqualTo(1); + assertThat(proof.physicalExecutionExists(item.execution())).isTrue(); + assertThat(proof.itemImage(id)).contains("\"fence_apply_issued\": true"); + } + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void sealedDispatchRestartRecoversNeverSentButPreservesAppliedThenLost(boolean appliedThenLost) + throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + long deadline = transferDeadline(); + proof.transfers.within( + deadline, + budget -> { + var before = proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), deadline); + var dispatch = proof.transfers.fenceDispatch(item, before); + if (appliedThenLost) { + proof + .capacity(proof.sql) + .forTransferBudget(budget) + .fenceForTransfer(item, dispatch, deadline); + assertThat(proof.physicalExecutionExists(item.execution())).isTrue(); + proof.losePhysicalExecution(item.execution()); + } + return null; + }); + String retained = proof.itemImage(id); + proof.recreateTransferOwners(); + if (appliedThenLost) { + assertThatThrownBy(() -> proof.fence(item)).isInstanceOf(IllegalStateException.class); + assertThat(proof.physicalExecutionExists(item.execution())).isFalse(); + assertThat(proof.itemImage(id)).isEqualTo(retained); + } else { + proof.fence(item); + assertThat(proof.physicalExecutionExists(item.execution())).isTrue(); + assertThat(proof.itemImage(id)).doesNotContain("\"fence_readback\": null"); + } + assertThat(proof.currentOwner()).isEqualTo(proof.prior); } } @@ -979,7 +1171,7 @@ void lostFenceDispatchReplyRecoversOnlyItsPhysicalWitnessAndCannotRecreateIt() t var before = proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), deadline); var dispatch = proof.transfers.fenceDispatch(item, before); var competing = proof.transfers.fenceDispatch(item, before); - assertThat(competing.takeSubmission(item)).isNull(); + assertThat(competing.hasReceipt(item)).isTrue(); var owner = proof.capacity(proof.sql).forTransferBudget(budget); owner.fenceForTransfer(item, dispatch, deadline); return null; From f69d5b20950d1c905e1286ea3fdd2f87cb45280a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:04:03 +1300 Subject: [PATCH 13/51] Format combined lease recovery callback --- .../repository/CanonicalGameplayRegionLeaseOwner.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index d4dd89dfa6..341ee75059 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -440,7 +440,8 @@ private Installation installForTransition( initializationPreparation, clock.instant(), proof -> { - retainNoWriteProof(initializationPreparation, retained, proof); + retainNoWriteProof( + initializationPreparation, retained, proof); recoverNoWrite(initializationPreparation, retained); })); }); From 457e6c4385058a256325698de5ed0e201d59085c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:04:41 +1300 Subject: [PATCH 14/51] Keep initialization proof callback bound to retained preparation --- .../repository/CanonicalGameplayRegionLeaseOwner.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 341ee75059..23193cc2f7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -449,8 +449,8 @@ private Installation installForTransition( session.initialize( permit.orElse(null), proof -> { - retainNoWriteProof(claimedPreparation, retained, proof); - recoverNoWrite(claimedPreparation, retained); + retainNoWriteProof(initializationPreparation, retained, proof); + recoverNoWrite(initializationPreparation, retained); }); } finally { releaseNoWriteRecovery(preparation.operationId(), retained); From bfadf81cbd5473d3c6f2d5b018d3df314d0c200a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:11:22 +1300 Subject: [PATCH 15/51] Guard nullable SQL snapshots in physical test listeners --- .../CanonicalGameplayRegionLeaseOwnerIntegrationTest.java | 6 +++--- ...ameplayRegionTransferCapacityCustodyIntegrationTest.java | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index bcd2424b2d..e41d454cb5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1512,9 +1512,9 @@ private void assertKnownNoWriteRecovery(int mode) throws Exception { @Override public void executeStart( org.jooq.ExecuteContext context) { - if (context - .sql() - .contains("SET phase = 'PREPARED'")) { + String statement = context.sql(); + if (statement != null + && statement.contains("SET phase = 'PREPARED'")) { // The exact capability is already consumed. A // second SQL // reconciliation now waits for this transaction's diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index a75073afeb..d066d5ada0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -213,8 +213,9 @@ void competingOwnersIssueApplyExactlyOnce() throws Exception { new DefaultExecuteListener() { @Override public void executeEnd(ExecuteContext context) { - if (context.sql() != null - && context.sql().contains("SET fence_apply_issued=true") + String statement = context.sql(); + if (statement != null + && statement.contains("SET fence_apply_issued=true") && context.rows() == 1) issued.incrementAndGet(); } }; From 17ea5c2be3cc2c2dcc6d1f9e43b03790bfa76079 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:17:11 +1300 Subject: [PATCH 16/51] Format nullable SQL test guard --- .../CanonicalGameplayRegionLeaseOwnerIntegrationTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index e41d454cb5..c4ec6471ca 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1514,7 +1514,8 @@ public void executeStart( org.jooq.ExecuteContext context) { String statement = context.sql(); if (statement != null - && statement.contains("SET phase = 'PREPARED'")) { + && statement.contains( + "SET phase = 'PREPARED'")) { // The exact capability is already consumed. A // second SQL // reconciliation now waits for this transaction's From 272094b163a54ad2888efb8cb7c9145099b1968b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:19:21 +1300 Subject: [PATCH 17/51] Require retained row in lost acknowledgement proof --- ...lGameplayRegionTransferCapacityCustodyIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index d066d5ada0..49926f5189 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -151,7 +151,7 @@ public java.sql.Connection acquire() { && Boolean.TRUE.equals( proof .sql - .fetchOne( + .fetchSingle( "SELECT fence_apply_issued FROM game_session_region_owner_transfer_item WHERE transfer_id=?", id) .get(0, Boolean.class)) @@ -192,7 +192,7 @@ public void release(java.sql.Connection connection) { assertThat( proof .sql - .fetchOne( + .fetchSingle( "SELECT fence_apply_issued FROM game_session_region_owner_transfer_item WHERE transfer_id=?", id) .get(0, Boolean.class)) From 5d12174e2d58913e435ac0d03c9ae30df1193687 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:11:52 +1300 Subject: [PATCH 18/51] Include transfer receipt resources in cross-service proof jar --- services/game-session-service/build.gradle.kts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index a0c3d0815a..119a013590 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -219,6 +219,8 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("redis/scripts/game-session-original-new-candidate-close.json") include("redis/lua/game-session-original-new-final-admission.lua") include("redis/scripts/game-session-original-new-final-admission.json") + include("redis/lua/game-session-region-transfer-receipt.lua") + include("redis/scripts/game-session-region-transfer-receipt.json") } from("src/main/resources") { include("redis/lua/game-session-region-lease-acquire.lua") From e66507464e2a438c4a4b7a3223cf3202b6bc5f60 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:48:28 +1300 Subject: [PATCH 19/51] Update runtime catalog receipt epoch fixture --- ...ameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 0393f8a0d2..643613aa5a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(22); + assertThat(catalog.catalogEpoch()).isEqualTo(23); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -779,7 +779,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(22); + assertThat(original.catalog().catalogEpoch()).isEqualTo(23); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> From db22640dd5186db244ff9d1d409d3ecc5ca5ef08 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 07:21:17 +1300 Subject: [PATCH 20/51] Retain initialization claim custody across caller deadlines --- .../CanonicalGameplayRegionLeaseOwner.java | 69 ++- ...anonicalGameplayRegionLeaseRedisOwner.java | 86 +++- ...meplayRegionLeaseOwnerIntegrationTest.java | 446 ++++++++++++++++++ 3 files changed, 566 insertions(+), 35 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 23193cc2f7..328d77e00f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -45,6 +45,7 @@ final class CanonicalGameplayRegionLeaseOwner { static final class RetainedNoWriteRecovery { private boolean inUse; + private int retainedWorkers; CanonicalGameplayRegionLeaseRedisOwner.InitializationNoWriteProof proof; CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; } @@ -57,7 +58,7 @@ RetainedNoWriteRecovery reserveNoWriteRecovery(UUID operation) { retained = new RetainedNoWriteRecovery(); noWriteRecoveries.put(operation, retained); } - if (retained.inUse) throw unavailable(); + if (retained.inUse || retained.retainedWorkers != 0) throw unavailable(); retained.inUse = true; return retained; } @@ -66,18 +67,39 @@ RetainedNoWriteRecovery reserveNoWriteRecovery(UUID operation) { void releaseNoWriteRecovery(UUID operation, RetainedNoWriteRecovery retained) { synchronized (noWriteRecoveries) { retained.inUse = false; - if (retained.proof == null) { + if (retained.proof == null && retained.retainedWorkers == 0) { noWriteRecoveries.remove(operation, retained); } } } + java.util.concurrent.CompletableFuture retainNoWriteWorker( + UUID operation, RetainedNoWriteRecovery retained) { + var lifetime = new java.util.concurrent.CompletableFuture(); + synchronized (noWriteRecoveries) { + if (noWriteRecoveries.get(operation) != retained || !retained.inUse) throw unavailable(); + retained.retainedWorkers++; + } + lifetime.whenComplete( + (ignored, failure) -> { + synchronized (noWriteRecoveries) { + retained.retainedWorkers--; + if (!retained.inUse && retained.retainedWorkers == 0 && retained.proof == null) { + noWriteRecoveries.remove(operation, retained); + } + } + }); + return lifetime; + } + void retainNoWriteProof( CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, RetainedNoWriteRecovery retained, CanonicalGameplayRegionLeaseRedisOwner.InitializationNoWriteProof proof) { - retained.preparation = Objects.requireNonNull(preparation, "preparation"); - retained.proof = Objects.requireNonNull(proof, "proof"); + synchronized (noWriteRecoveries) { + retained.preparation = Objects.requireNonNull(preparation, "preparation"); + retained.proof = Objects.requireNonNull(proof, "proof"); + } } /** Cleanup has no admission authority and remains possible after the binding was aborted. */ @@ -89,7 +111,7 @@ void recoverRetainedNoWriteForTransition(UUID transitionId) { if (retained.proof != null && retained.preparation != null && retained.preparation.transitionId().equals(transitionId)) { - if (retained.inUse) throw unavailable(); + if (retained.inUse || retained.retainedWorkers != 0) throw unavailable(); retained.inUse = true; selected = retained; break; @@ -444,7 +466,18 @@ private Installation installForTransition( initializationPreparation, retained, proof); recoverNoWrite(initializationPreparation, retained); })); - }); + }, + abandoned -> + abandoned.ifPresent( + unused -> { + retainNoWriteProof( + initializationPreparation, + retained, + CanonicalGameplayRegionLeaseRedisOwner + .revokeUndispatchedInitialization(unused)); + recoverNoWrite(initializationPreparation, retained); + }), + retainNoWriteWorker(initializationPreparation.operationId(), retained)); grant = session.initialize( permit.orElse(null), @@ -1400,10 +1433,14 @@ private T readInstallationInventory( long handoffDeadline, CanonicalGameplayOriginalNewCapacityExecutionBudget retainedBudget, java.util.function.Function read) { - if (transferOwner == null) return read.apply(bindingInventory); - return retainedBudget == null - ? bindingInventory.withinTransferRead(clock, handoffDeadline, read) - : bindingInventory.withinTransferRead(retainedBudget, read); + if (retainedBudget != null) { + // Do not wrap the ordinary caller's already-budgeted provider: the companion + // must own its connections independently until its retained lifetime ends. + return this.bindingInventory.withinTransferRead(retainedBudget, read); + } + return transferOwner == null + ? read.apply(bindingInventory) + : bindingInventory.withinTransferRead(clock, handoffDeadline, read); } private T withTransferStatusRepository( @@ -1422,10 +1459,14 @@ private T withTransferStatusRepository( long handoffDeadline, CanonicalGameplayOriginalNewCapacityExecutionBudget retainedBudget, java.util.function.Function operation) { - if (transferOwner == null) return operation.apply(statusRepository); - return retainedBudget == null - ? transferOwner.withStatusRepository(handoffDeadline, operation) - : transferOwner.withStatusRepository(retainedBudget, operation); + if (retainedBudget != null) { + return transferOwner == null + ? operation.apply(this.statusRepository.forBudget(retainedBudget)) + : transferOwner.withStatusRepository(retainedBudget, operation); + } + return transferOwner == null + ? operation.apply(statusRepository) + : transferOwner.withStatusRepository(handoffDeadline, operation); } private ResolvedBridgeSource resolveExactBridgeSource( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index c554e5574d..49aac7b1a0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -547,23 +547,40 @@ private PreparedTimelineInitialization( */ T runWithinRetainedPermit( Function operation) { + return runWithinRetainedPermit(operation, ignored -> {}, new CompletableFuture<>()); + } + + T runWithinRetainedPermit( + Function operation, + java.util.function.Consumer undelivered, + CompletableFuture workLifetime) { Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(undelivered, "undelivered"); + Objects.requireNonNull(workLifetime, "workLifetime"); CanonicalGameplayOriginalNewCapacityExecutionBudget retainedBudget; - CompletableFuture workLifetime = new CompletableFuture<>(); - synchronized (this) { - requireNoAmbientTransaction(); - if (closed || initialized || retainedWorkInFlight) throw unavailable(); - retainedWorkInFlight = true; - retainedBudget = budget; - if (retainedBudget != null) { - retainedBudget.retainUntilCompletion(workLifetime); - workLifetime.whenComplete( - (ignored, failure) -> { - synchronized (PreparedTimelineInitialization.this) { - retainedWorkInFlight = false; - } - }); + boolean ownsRetainedWork = false; + try { + synchronized (this) { + requireNoAmbientTransaction(); + if (closed || initialized || retainedWorkInFlight) { + workLifetime.complete(null); + throw unavailable(); + } + retainedWorkInFlight = true; + ownsRetainedWork = true; + retainedBudget = budget; + if (retainedBudget != null) { + retainedBudget.retainUntilCompletion(workLifetime); + } + } + } catch (RuntimeException | Error startupFailure) { + if (ownsRetainedWork) { + synchronized (this) { + retainedWorkInFlight = false; + } } + workLifetime.complete(null); + throw startupFailure; } if (retainedBudget == null) { @@ -573,10 +590,12 @@ T runWithinRetainedPermit( synchronized (this) { retainedWorkInFlight = false; } + workLifetime.complete(null); } } CompletableFuture result = new CompletableFuture<>(); + CompletableFuture delivered = new CompletableFuture<>(); AtomicReference workerReference = new AtomicReference<>(); Context.CancellationListener listener = ignored -> { @@ -613,23 +632,41 @@ T runWithinRetainedPermit( } catch (RuntimeException | Error cleanupFailure) { if (failure == null) failure = cleanupFailure; else if (failure != cleanupFailure) failure.addSuppressed(cleanupFailure); - } finally { + } + // The worker owns any produced capability until the caller acknowledges + // delivery. Timeout/cancellation never silently discards an issued claim. + if (failure == null) result.complete(value); + else result.completeExceptionally(failure); + if (!delivered.join() && value != null) { try { - if (previous != null) workerContext.detach(previous); - } finally { - workLifetime.complete(null); + undelivered.accept(value); + } catch (RuntimeException | Error recoveryFailure) { + if (failure == null) failure = recoveryFailure; + else if (failure != recoveryFailure) + failure.addSuppressed(recoveryFailure); + } + } + try { + if (previous != null) workerContext.detach(previous); + } finally { + synchronized (PreparedTimelineInitialization.this) { + retainedWorkInFlight = false; } + workLifetime.complete(null); } } - if (failure == null) result.complete(value); - else result.completeExceptionally(failure); }); workerReference.set(worker); caller.addListener(listener, Runnable::run); listenerRegistered = true; worker.start(); workerStarted = true; - return result.get(retainedBudget.remainingNanos(), TimeUnit.NANOSECONDS); + T value = result.get(retainedBudget.remainingNanos(), TimeUnit.NANOSECONDS); + delivered.complete(true); + // SQL cleanup already completed before result publication; only context detachment and + // retained-state notification remain. Initialization must not race that notification. + workLifetime.join(); + return value; } catch (InterruptedException interrupted) { if (worker != null) worker.interrupt(); retainedBudget.cancel(); @@ -644,6 +681,9 @@ T runWithinRetainedPermit( worker.interrupt(); retainedBudget.cancel(); } else { + synchronized (this) { + retainedWorkInFlight = false; + } workLifetime.complete(null); } throw expired instanceof RuntimeException runtime ? runtime : unavailable(); @@ -652,10 +692,14 @@ T runWithinRetainedPermit( worker.interrupt(); retainedBudget.cancel(); } else { + synchronized (this) { + retainedWorkInFlight = false; + } workLifetime.complete(null); } throw unavailable(startupFailure); } finally { + delivered.complete(false); if (listenerRegistered) caller.removeListener(listener); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index c4ec6471ca..48156fa7ef 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -715,6 +715,452 @@ void boundedTimelineCreationRejectsExpiryAndCapsNewLease() throws Exception { } } + @Test + void cancelledCallerRecoversAlreadyCommittedUndeliveredInitializationPermit() throws Exception { + assertCancelledCompanionClaimRecovered(false, false); + } + + @Test + void cancelledCallerRetainsReservationUntilLateAcknowledgedClaimFinishes() throws Exception { + assertCancelledCompanionClaimRecovered(true, false); + } + + @Test + void deadlineExpiryRecoversCommittedUndeliveredInitializationPermit() throws Exception { + assertCancelledCompanionClaimRecovered(false, true); + } + + private void assertCancelledCompanionClaimRecovered( + boolean claimAfterCancellation, boolean deadlineOnly) throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try { + try (RedisFixture redis = RedisFixture.open()) { + var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var redisOwner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.clientUri(PRINCIPAL, PASSWORD), redis.catalog()); + WorldFixture world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var bindingEvidence = provisionalEvidence(world.request()); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + statusRepository.prepareInitialTimeline( + bindingEvidence, + world.request(), + world.resolver().resolve(world.request()), + source, + incarnation, + redisOwner.requireTimelineAbsent(source, incarnation), + NOW); + long deadline = System.currentTimeMillis() + (deadlineOnly ? 2_000L : 10_000L); + var deadlineBoundRedisOwner = redisOwner.forHandoffDeadline(Clock.systemUTC(), deadline); + RuntimeIdentity identity = + new RuntimeIdentity( + "game-session-service", + "overlapping-timeline-preparation", + "localhost", + NOW, + "controlled-test", + "controlled-sha", + "controlled-image"); + var bindingInventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + + var owner = + ownerWithLiveClock( + bindingInventory, + statusRepository, + redisOwner, + world, + "cancelled-companion-claim", + incarnationSource); + var retained = owner.reserveNoWriteRecovery(preparation.operationId()); + var lifetime = owner.retainNoWriteWorker(preparation.operationId(), retained); + var entered = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + var outcome = new java.util.concurrent.CompletableFuture(); + try (var context = io.grpc.Context.current().withCancellation(); + var session = + deadlineBoundRedisOwner.prepareTimelineInitialization( + preparation, Duration.ofSeconds(30), identity)) { + Thread caller = + Thread.ofVirtual() + .start( + () -> + context.run( + () -> { + try { + session.runWithinRetainedPermit( + budget -> { + var permit = + claimAfterCancellation + ? java.util.Optional + . + empty() + : statusRepository.beginInitialTimeline( + preparation, NOW); + entered.countDown(); + // Deliberately model a provider callback that cannot be + // interrupted. The + // late path returns only a real acknowledged PostgreSQL + // claim, never a guess. + boolean released = false; + long stop = + System.nanoTime() + + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + while (!released && System.nanoTime() < stop) { + try { + released = + release.await( + 100, + java.util.concurrent.TimeUnit.MILLISECONDS); + } catch (InterruptedException ignored) { + /* physical late-provider fixture */ + } + } + if (!released) + throw new AssertionError( + "test release was not signalled"); + return claimAfterCancellation + ? statusRepository.beginInitialTimeline( + preparation, NOW) + : permit; + }, + abandoned -> + abandoned.ifPresent( + permit -> { + owner.retainNoWriteProof( + preparation, + retained, + CanonicalGameplayRegionLeaseRedisOwner + .revokeUndispatchedInitialization(permit)); + owner.recoverNoWrite(preparation, retained); + }), + lifetime); + outcome.complete( + new AssertionError("cancelled caller received a permit")); + } catch (Throwable failure) { + outcome.complete(failure); + } finally { + owner.releaseNoWriteRecovery(preparation.operationId(), retained); + } + })); + assertThat(entered.await(5, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + if (!deadlineOnly) context.cancel(new IllegalStateException("test caller cancellation")); + assertThat(outcome.get(5, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(IllegalStateException.class); + caller.join(5000); + assertThat(caller.isAlive()).isFalse(); + assertThat(lifetime.isDone()).isFalse(); + assertThatThrownBy(() -> owner.reserveNoWriteRecovery(preparation.operationId())) + .isInstanceOf(IllegalStateException.class); + release.countDown(); + lifetime.get(5, java.util.concurrent.TimeUnit.SECONDS); + assertThat( + testSchema + .dsl() + .fetchValue( + "SELECT phase FROM game_session_region_timeline_preparation WHERE initialization_operation_id = ?", + preparation.operationId())) + .isEqualTo("PREPARED"); + var next = owner.reserveNoWriteRecovery(preparation.operationId()); + owner.releaseNoWriteRecovery(preparation.operationId(), next); + } finally { + release.countDown(); + } + } + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void successfulDeliveryCanInitializeWhileCompletionCallbackIsDelayed() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try { + try (RedisFixture redis = RedisFixture.open()) { + var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var redisOwner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.clientUri(PRINCIPAL, PASSWORD), redis.catalog()); + WorldFixture world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var bindingEvidence = provisionalEvidence(world.request()); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + statusRepository.prepareInitialTimeline( + bindingEvidence, + world.request(), + world.resolver().resolve(world.request()), + source, + incarnation, + redisOwner.requireTimelineAbsent(source, incarnation), + NOW); + long deadline = System.currentTimeMillis() + 10_000L; + var deadlineBoundRedisOwner = redisOwner.forHandoffDeadline(Clock.systemUTC(), deadline); + RuntimeIdentity identity = + new RuntimeIdentity( + "game-session-service", + "overlapping-timeline-preparation", + "localhost", + NOW, + "controlled-test", + "controlled-sha", + "controlled-image"); + var bindingInventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + + var callbackEntered = new java.util.concurrent.CountDownLatch(1); + var callbackRelease = new java.util.concurrent.CountDownLatch(1); + var lifetime = new java.util.concurrent.CompletableFuture(); + lifetime.whenComplete( + (ignored, failure) -> { + callbackEntered.countDown(); + try { + if (!callbackRelease.await(5, java.util.concurrent.TimeUnit.SECONDS)) + throw new AssertionError("completion callback was not released"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + }); + try (var session = + deadlineBoundRedisOwner.prepareTimelineInitialization( + preparation, Duration.ofSeconds(30), identity)) { + var claim = + session.runWithinRetainedPermit( + budget -> + statusRepository.forBudget(budget).beginInitialTimeline(preparation, NOW), + ignored -> { + throw new AssertionError("successfully delivered claim was abandoned"); + }, + lifetime); + assertThat(callbackEntered.await(5, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + assertThat(session.initialize(claim.orElseThrow())).isNotNull(); + } finally { + callbackRelease.countDown(); + } + } + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void ordinaryCompanionInventoryConnectionOutlivesCancelledOuterWorker() throws Exception { + assertOrdinaryCompanionOwnsConnections(true); + } + + @Test + void ordinaryCompanionStatusConnectionOutlivesCancelledOuterWorker() throws Exception { + assertOrdinaryCompanionOwnsConnections(false); + } + + private void assertOrdinaryCompanionOwnsConnections(boolean inventoryRead) throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try { + try (RedisFixture redis = RedisFixture.open()) { + var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var redisOwner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.clientUri(PRINCIPAL, PASSWORD), redis.catalog()); + WorldFixture world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var bindingEvidence = provisionalEvidence(world.request()); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + statusRepository.prepareInitialTimeline( + bindingEvidence, + world.request(), + world.resolver().resolve(world.request()), + source, + incarnation, + redisOwner.requireTimelineAbsent(source, incarnation), + NOW); + long deadline = System.currentTimeMillis() + 10_000L; + var deadlineBoundRedisOwner = redisOwner.forHandoffDeadline(Clock.systemUTC(), deadline); + RuntimeIdentity identity = + new RuntimeIdentity( + "game-session-service", + "overlapping-timeline-preparation", + "localhost", + NOW, + "controlled-test", + "controlled-sha", + "controlled-image"); + var bindingInventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + + var entered = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + var releasedConnection = new java.util.concurrent.CountDownLatch(1); + var block = new java.util.concurrent.atomic.AtomicBoolean(true); + var originalProvider = testSchema.dsl().configuration().connectionProvider(); + var originals = + java.util.Collections.synchronizedMap( + new java.util.IdentityHashMap()); + var instrumentedProvider = + new org.jooq.ConnectionProvider() { + @Override + public Connection acquire() { + Connection raw = originalProvider.acquire(); + Connection proxy = + (Connection) + java.lang.reflect.Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (ignored, method, arguments) -> { + try { + Object value = method.invoke(raw, arguments); + if (value instanceof java.sql.PreparedStatement statement) { + return java.lang.reflect.Proxy.newProxyInstance( + java.sql.PreparedStatement.class.getClassLoader(), + new Class[] {java.sql.PreparedStatement.class}, + (unused, statementMethod, statementArguments) -> { + if (statementMethod.getName().startsWith("execute") + && block.compareAndSet(true, false)) { + entered.countDown(); + boolean done = false; + long stop = + System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (!done && System.nanoTime() < stop) { + try { + done = release.await(100, TimeUnit.MILLISECONDS); + } catch (InterruptedException ignoredInterrupt) { + /* blocked provider fixture */ + } + } + if (!done) + throw new AssertionError( + "SQL fixture release not signalled"); + } + try { + return statementMethod.invoke( + statement, statementArguments); + } catch ( + java.lang.reflect.InvocationTargetException error) { + throw error.getCause(); + } + }); + } + return value; + } catch (java.lang.reflect.InvocationTargetException error) { + throw error.getCause(); + } + }); + originals.put(proxy, raw); + return proxy; + } + + @Override + public void release(Connection connection) { + releasedConnection.countDown(); + originalProvider.release(originals.remove(connection)); + } + }; + var instrumentedDsl = + DSL.using(testSchema.dsl().configuration().derive(instrumentedProvider)); + var inventory = new CanonicalGameplayBindingInventoryRepository(instrumentedDsl); + var status = new CanonicalGameplayRegionRuntimeStatusRepository(instrumentedDsl); + var owner = + ownerWithLiveClock( + inventory, + status, + redisOwner, + world, + "ordinary-companion-connection", + incarnationSource); + var method = + CanonicalGameplayRegionLeaseOwner.class.getDeclaredMethod( + inventoryRead ? "readInstallationInventory" : "withTransferStatusRepository", + inventoryRead + ? CanonicalGameplayBindingInventoryRepository.class + : CanonicalGameplayRegionRuntimeStatusRepository.class, + CanonicalGameplayRegionOwnerTransferCoordinator.class, + long.class, + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, + java.util.function.Function.class); + method.setAccessible(true); + var lifetime = new java.util.concurrent.CompletableFuture(); + var outcome = new java.util.concurrent.CompletableFuture(); + try (var context = io.grpc.Context.current().withCancellation(); + var session = + deadlineBoundRedisOwner.prepareTimelineInitialization( + preparation, Duration.ofSeconds(30), identity)) { + Thread caller = + Thread.ofVirtual() + .start( + () -> + context.run( + () -> { + try { + CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + Clock.systemUTC(), + deadline, + outer -> + session.runWithinRetainedPermit( + retainedBudget -> { + java.util.function.Function read = + inventoryRead + ? (java.util.function.Function< + CanonicalGameplayBindingInventoryRepository, + Object>) + repository -> repository.readSnapshot() + : (java.util.function.Function< + CanonicalGameplayRegionRuntimeStatusRepository, + Object>) + repository -> repository.find(source); + try { + return method.invoke( + owner, + inventoryRead + ? inventory.forBudget(outer) + : status.forBudget(outer), + null, + deadline, + retainedBudget, + read); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException(failure); + } + }, + ignored -> {}, + lifetime)); + outcome.complete( + new AssertionError("cancelled outer worker completed")); + } catch (Throwable failure) { + outcome.complete(failure); + } + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + context.cancel(new IllegalStateException("cancel outer installation")); + assertThat(outcome.get(5, TimeUnit.SECONDS)).isInstanceOf(IllegalStateException.class); + caller.join(5000); + assertThat(caller.isAlive()).isFalse(); + assertThat(lifetime.isDone()).isFalse(); + assertThat(releasedConnection.await(300, TimeUnit.MILLISECONDS)).isFalse(); + release.countDown(); + lifetime.get(5, TimeUnit.SECONDS); + assertThat(releasedConnection.await(5, TimeUnit.SECONDS)).isTrue(); + } finally { + release.countDown(); + } + } + } finally { + dropSchema(testSchema.schema()); + } + } + @Test void preparedTimelineIncarnationReadReusesPermitWhenBothBackgroundSlotsAreHeld() throws Exception { From 461b8a6d7bd9ea69c0c4657ec7cf3fd248f04991 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:48:28 +1300 Subject: [PATCH 21/51] Update runtime catalog receipt epoch fixture --- ...ameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 0393f8a0d2..643613aa5a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(22); + assertThat(catalog.catalogEpoch()).isEqualTo(23); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -779,7 +779,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(22); + assertThat(original.catalog().catalogEpoch()).isEqualTo(23); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> From a52b23b42b6482432602924def4bc22e0a070594 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 07:32:00 +1300 Subject: [PATCH 22/51] Separate initialization readiness from lifetime observers --- ...anonicalGameplayRegionLeaseRedisOwner.java | 6 ++++- ...meplayRegionLeaseOwnerIntegrationTest.java | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index 49aac7b1a0..b9f96f4d47 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -596,6 +596,7 @@ T runWithinRetainedPermit( CompletableFuture result = new CompletableFuture<>(); CompletableFuture delivered = new CompletableFuture<>(); + CompletableFuture readyForInitialization = new CompletableFuture<>(); AtomicReference workerReference = new AtomicReference<>(); Context.CancellationListener listener = ignored -> { @@ -652,6 +653,9 @@ else if (failure != recoveryFailure) synchronized (PreparedTimelineInitialization.this) { retainedWorkInFlight = false; } + // Keep readiness separate from externally registered lifetime callbacks: + // a joining caller may otherwise help execute a blocked callback. + readyForInitialization.complete(null); workLifetime.complete(null); } } @@ -665,7 +669,7 @@ else if (failure != recoveryFailure) delivered.complete(true); // SQL cleanup already completed before result publication; only context detachment and // retained-state notification remain. Initialization must not race that notification. - workLifetime.join(); + readyForInitialization.join(); return value; } catch (InterruptedException interrupted) { if (worker != null) worker.interrupt(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 48156fa7ef..2b6d159b70 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1317,6 +1317,17 @@ void installationDeadlineDuringSourceRecheckLeavesPreparedPermission() throws Ex var inventory = mock(CanonicalGameplayBindingInventoryRepository.class); when(inventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(evidence); when(inventory.forBudget(org.mockito.ArgumentMatchers.any())).thenReturn(inventory); + org.mockito.Mockito.doAnswer( + invocation -> { + java.util.function.Function + read = invocation.getArgument(1); + return read.apply(inventory); + }) + .when(inventory) + .withinTransferRead( + org.mockito.ArgumentMatchers.any( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class), + org.mockito.ArgumentMatchers.any()); var source = source(world.originalEvidence()); var incarnation = incarnationSource.readCurrent( @@ -1394,6 +1405,17 @@ void installationReleasesDefinitiveRedisExpiryAndFreshOwnerRetries() throws Exce var inventory = mock(CanonicalGameplayBindingInventoryRepository.class); when(inventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(evidence); when(inventory.forBudget(org.mockito.ArgumentMatchers.any())).thenReturn(inventory); + org.mockito.Mockito.doAnswer( + invocation -> { + java.util.function.Function + read = invocation.getArgument(1); + return read.apply(inventory); + }) + .when(inventory) + .withinTransferRead( + org.mockito.ArgumentMatchers.any( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class), + org.mockito.ArgumentMatchers.any()); var source = source(world.originalEvidence()); var incarnation = incarnationSource.readCurrent( From 9ddacc02ce9d2e7c3c50e5298a39cadcf764ef77 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 07:38:10 +1300 Subject: [PATCH 23/51] Remove unused initialization fixture locals --- .../CanonicalGameplayRegionLeaseOwnerIntegrationTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 2b6d159b70..e5f97b9e63 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -915,7 +915,6 @@ void successfulDeliveryCanInitializeWhileCompletionCallbackIsDelayed() throws Ex "controlled-test", "controlled-sha", "controlled-image"); - var bindingInventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); var callbackEntered = new java.util.concurrent.CountDownLatch(1); var callbackRelease = new java.util.concurrent.CountDownLatch(1); @@ -999,7 +998,6 @@ private void assertOrdinaryCompanionOwnsConnections(boolean inventoryRead) throw "controlled-test", "controlled-sha", "controlled-image"); - var bindingInventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); var entered = new java.util.concurrent.CountDownLatch(1); var release = new java.util.concurrent.CountDownLatch(1); From 7479aa8c8bef12090c5c44415f489ecab8380583 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 08:21:11 +1300 Subject: [PATCH 24/51] Bound retained recovery caller wait without abandoning SQL custody --- ...layOriginalNewCapacityExecutionBudget.java | 18 ++- .../CanonicalGameplayRegionLeaseOwner.java | 35 ++++- ...meplayRegionLeaseOwnerIntegrationTest.java | 120 ++++++++++++++++++ 3 files changed, 166 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudget.java index 3d2d9b0039..adc3ffe47b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudget.java @@ -66,6 +66,7 @@ final class CanonicalGameplayOriginalNewCapacityExecutionBudget { private final long absoluteDeadlineMillis; private final AtomicBoolean cancelled = new AtomicBoolean(); private final CompletableFuture result = new CompletableFuture<>(); + private final CompletableFuture workerLifetime = new CompletableFuture<>(); private final Object resources = new Object(); private final Object lifecycle = new Object(); private final Map connections = new IdentityHashMap<>(); @@ -178,10 +179,14 @@ private static T run( if (failure == null) failure = cleanupFailure; else if (failure != cleanupFailure) failure.addSuppressed(cleanupFailure); } - budget.caller.detach(previous); - synchronized (budget.lifecycle) { - budget.workerDone = true; - budget.releaseIfFinished(); + try { + budget.caller.detach(previous); + } finally { + synchronized (budget.lifecycle) { + budget.workerDone = true; + budget.releaseIfFinished(); + } + budget.workerLifetime.complete(null); } } if (failure != null) budget.result.completeExceptionally(failure); @@ -278,6 +283,11 @@ void retainUntilAsyncClose(CompletableFuture closeAttempt) { }); } + /** Actual worker exit, including SQL resource cleanup; never the caller timeout. */ + CompletableFuture workerLifetime() { + return workerLifetime; + } + /** Keeps this operation's permits until borrowed work has actually exited. */ void retainUntilCompletion(CompletableFuture work) { Objects.requireNonNull(work); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 328d77e00f..0710572b4a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -104,6 +104,10 @@ void retainNoWriteProof( /** Cleanup has no admission authority and remains possible after the binding was aborted. */ void recoverRetainedNoWriteForTransition(UUID transitionId) { + recoverRetainedNoWriteForTransition(transitionId, Long.MAX_VALUE); + } + + private void recoverRetainedNoWriteForTransition(UUID transitionId, long absoluteDeadlineMillis) { Objects.requireNonNull(transitionId, "transitionId"); RetainedNoWriteRecovery selected = null; synchronized (noWriteRecoveries) { @@ -119,10 +123,35 @@ void recoverRetainedNoWriteForTransition(UUID transitionId) { } } if (selected == null) return; + var recovery = selected; + var workerOwnsRecovery = new java.util.concurrent.atomic.AtomicBoolean(); try { - recoverNoWrite(selected.preparation, selected); + // Retry cleanup observes the caller's deadline. Its reservation follows the actual + // SQL worker, not the caller-facing timeout or completion of the SQL callback alone. + CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + clock, + absoluteDeadlineMillis, + cleanup -> { + if (!workerOwnsRecovery.compareAndSet(false, true)) throw unavailable(); + cleanup + .workerLifetime() + .whenComplete( + (ignored, failure) -> + releaseNoWriteRecovery(recovery.preparation.operationId(), recovery)); + this.statusRepository + .forBudget(cleanup) + .releaseInitialTimelineNoWrite( + recovery.preparation, recovery.proof, clock.instant()); + synchronized (noWriteRecoveries) { + recovery.proof = null; + } + return null; + }); } finally { - releaseNoWriteRecovery(selected.preparation.operationId(), selected); + // If the callback never acquired custody, prevent a late start and release safely. + if (workerOwnsRecovery.compareAndSet(false, true)) { + releaseNoWriteRecovery(recovery.preparation.operationId(), recovery); + } } } @@ -220,7 +249,7 @@ Installation installForTransition( CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, long absoluteDeadlineMillis) { requireNoAmbientTransaction(); - recoverRetainedNoWriteForTransition(transitionId); + recoverRetainedNoWriteForTransition(transitionId, absoluteDeadlineMillis); if (!deadlineBoundInstallation || transferOwner != null) { return installForTransition( existingRegionInstallation, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index e5f97b9e63..e29dc643f1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -715,6 +715,126 @@ void boundedTimelineCreationRejectsExpiryAndCapsNewLease() throws Exception { } } + @Test + void callerDeadlineDoesNotReleaseRetainedRecoveryBeforeActualSqlWorkerExit() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema schema = newTestSchema(); + try (RedisFixture redis = RedisFixture.open()) { + var status = new CanonicalGameplayRegionRuntimeStatusRepository(schema.dsl()); + var redisOwner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.clientUri(PRINCIPAL, PASSWORD), redis.catalog()); + var world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var evidence = provisionalEvidence(world.request()); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + status.prepareInitialTimeline( + evidence, + world.request(), + world.resolver().resolve(world.request()), + source, + incarnation, + redisOwner.requireTimelineAbsent(source, incarnation), + NOW); + var permit = status.beginInitialTimeline(preparation, NOW).orElseThrow(); + var proof = CanonicalGameplayRegionLeaseRedisOwner.revokeUndispatchedInitialization(permit); + var entered = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + var exited = new java.util.concurrent.CountDownLatch(1); + var controlled = mock(CanonicalGameplayRegionRuntimeStatusRepository.class); + when(controlled.forBudget(org.mockito.ArgumentMatchers.any())).thenReturn(controlled); + org.mockito.Mockito.doAnswer( + invocation -> { + entered.countDown(); + long stop = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + boolean released = false; + while (!released && System.nanoTime() < stop) { + try { + released = release.await(50, java.util.concurrent.TimeUnit.MILLISECONDS); + } catch (InterruptedException ignored) { + /* model a SQL driver still executing */ + } + } + if (!released) throw new AssertionError("SQL release missing"); + try { + status.releaseInitialTimelineNoWrite(preparation, proof, NOW); + return null; + } finally { + exited.countDown(); + } + }) + .when(controlled) + .releaseInitialTimelineNoWrite( + org.mockito.ArgumentMatchers.eq(preparation), + org.mockito.ArgumentMatchers.same(proof), + org.mockito.ArgumentMatchers.any()); + var owner = + ownerWithLiveClock( + new CanonicalGameplayBindingInventoryRepository(schema.dsl()), + controlled, + redisOwner, + world, + "bounded-recovery", + incarnationSource); + var retained = owner.reserveNoWriteRecovery(preparation.operationId()); + owner.retainNoWriteProof(preparation, retained, proof); + owner.releaseNoWriteRecovery(preparation.operationId(), retained); + var scheduler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); + try (var context = + io.grpc.Context.current() + .withDeadlineAfter(500, java.util.concurrent.TimeUnit.MILLISECONDS, scheduler)) { + var outcome = new java.util.concurrent.CompletableFuture(); + Thread caller = + Thread.ofVirtual() + .start( + () -> + context.run( + () -> { + try { + owner.recoverRetainedNoWriteForTransition(TRANSITION_ID); + outcome.complete(new AssertionError("caller ignored deadline")); + } catch (Throwable failure) { + outcome.complete(failure); + } + })); + assertThat(entered.await(5, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + assertThat(outcome.get(2, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(IllegalStateException.class); + caller.join(2000); + assertThat(caller.isAlive()).isFalse(); + assertThat(exited.getCount()).isEqualTo(1L); + assertThatThrownBy(() -> owner.reserveNoWriteRecovery(preparation.operationId())) + .isInstanceOf(IllegalStateException.class); + release.countDown(); + assertThat(exited.await(5, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + org.awaitility.Awaitility.await() + .atMost(java.time.Duration.ofSeconds(5)) + .untilAsserted( + () -> { + var next = owner.reserveNoWriteRecovery(preparation.operationId()); + owner.releaseNoWriteRecovery(preparation.operationId(), next); + }); + assertThat( + schema + .dsl() + .fetchSingle( + "SELECT phase FROM game_session_region_timeline_preparation WHERE initialization_operation_id = ?", + preparation.operationId()) + .get(0, String.class)) + .isEqualTo("PREPARED"); + } finally { + release.countDown(); + scheduler.shutdownNow(); + } + } finally { + dropSchema(schema.schema()); + } + } + @Test void cancelledCallerRecoversAlreadyCommittedUndeliveredInitializationPermit() throws Exception { assertCancelledCompanionClaimRecovered(false, false); From 7e26223598c28d55be64ae1873d2c91c5d07bc93 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:14:15 +1300 Subject: [PATCH 25/51] Stabilize stalled transfer observation deadline test --- ...nOwnerTransferObservationReceiverTest.java | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java index 4f2f943580..8a246cf1fa 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java @@ -517,12 +517,23 @@ void stalledChannelReturnsByDeadlineAndRetainsBackgroundAdmission() throws Excep })); try { assertThat(peerEntered.await(2, TimeUnit.SECONDS)).isTrue(); - long started = System.nanoTime(); - assertThatThrownBy(() -> fixture.observe(NOW + 500L)) - .isInstanceOf( - CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); - assertThat(entered.getCount()).isZero(); - assertThat(System.nanoTime() - started).isLessThan(TimeUnit.SECONDS.toNanos(2)); + long deadline = NOW + 2_000L; + var stopped = new java.util.concurrent.CompletableFuture(); + Thread.ofVirtual() + .start(() -> { + try { + assertThatThrownBy(() -> fixture.observe(deadline)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException + .class); + stopped.complete(null); + } catch (Throwable failure) { + stopped.completeExceptionally(failure); + } + }); + assertThat(entered.await(2, TimeUnit.SECONDS)).isTrue(); + fixture.now.set(deadline); + stopped.get(3, TimeUnit.SECONDS); var denied = new Fixture(); assertThatThrownBy(() -> denied.observe(NOW + 500L)) .isInstanceOf( @@ -547,7 +558,8 @@ void stalledChannelReturnsByDeadlineAndRetainsBackgroundAdmission() throws Excep private static void awaitRelease(CountDownLatch release) { try { - if (!release.await(3, TimeUnit.SECONDS)) { + // The stalled worker must not self-release before the caller's 3-second watchdog. + if (!release.await(8, TimeUnit.SECONDS)) { throw new IllegalStateException("Controlled observation was not released"); } } catch (InterruptedException interrupted) { From 20bef13c4b742ad7836ace35e9dc7fa2be7d2517 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 20 Nov 2026 23:00:59 +1300 Subject: [PATCH 26/51] Make Region handoff integration tests deterministic --- ...onHandoffLeaseDeadlineIntegrationTest.java | 17 +++++--- ...meplayRegionLeaseOwnerIntegrationTest.java | 40 +++++++++++++------ 2 files changed, 39 insertions(+), 18 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java index 235c05dbd6..08eecc8961 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java @@ -276,7 +276,8 @@ void blockedTransferPreinstallRegionStatusReadKeepsCurrentOwner() throws Excepti bridge(); var original = regionBinding.installation(); String schema = fixture.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); - java.util.concurrent.CompletableFuture handoff = null; + record HandoffResult(boolean failedClosed, long elapsedNanos) {} + java.util.concurrent.CompletableFuture handoff = null; try (var lock = java.sql.DriverManager.getConnection( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { @@ -293,11 +294,12 @@ void blockedTransferPreinstallRegionStatusReadKeepsCurrentOwner() throws Excepti handoff = java.util.concurrent.CompletableFuture.supplyAsync(() -> { + long started = System.nanoTime(); try { actualTransferHandoff(); - return false; + return new HandoffResult(false, System.nanoTime() - started); } catch (IllegalStateException unavailable) { - return true; + return new HandoffResult(true, System.nanoTime() - started); } catch (Exception failure) { throw new IllegalStateException(failure); } @@ -316,12 +318,15 @@ void blockedTransferPreinstallRegionStatusReadKeepsCurrentOwner() throws Excepti != null; if (!statusReadBlocked) Thread.sleep(20L); } - boolean failedClosed = handoff.get(7, java.util.concurrent.TimeUnit.SECONDS); + var result = handoff.get(7, java.util.concurrent.TimeUnit.SECONDS); assertThat(statusReadBlocked).as("handoff reached the blocked region status read").isTrue(); - assertThat(failedClosed).as("bounded status read fails closed").isTrue(); + assertThat(result.failedClosed()).as("bounded status read fails closed").isTrue(); + assertThat(java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(result.elapsedNanos())) + .as("five-second handoff cap plus 750 ms scheduling allowance") + .isLessThanOrEqualTo(5750); } finally { if (handoff != null && !handoff.isDone()) { - assertThat(handoff.get(7, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + assertThat(handoff.get(7, java.util.concurrent.TimeUnit.SECONDS).failedClosed()).isTrue(); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index ee8a9c086e..d5fb631a29 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1011,8 +1011,21 @@ private void assertCancelledCompanionClaimRecovered( "SELECT phase FROM game_session_region_timeline_preparation WHERE initialization_operation_id = ?", preparation.operationId())) .isEqualTo("PREPARED"); - var next = owner.reserveNoWriteRecovery(preparation.operationId()); - owner.releaseNoWriteRecovery(preparation.operationId(), next); + org.awaitility.Awaitility.await() + .atMost(java.time.Duration.ofSeconds(5)) + .untilAsserted(() -> { + CanonicalGameplayRegionLeaseOwner.RetainedNoWriteRecovery next; + try { + next = owner.reserveNoWriteRecovery(preparation.operationId()); + } catch (IllegalStateException busy) { + if (!"Canonical Game Session region owner requires current exact assignment and lease evidence" + .equals(busy.getMessage())) { + throw busy; + } + throw new AssertionError("Reservation cleanup callback is still pending", busy); + } + owner.releaseNoWriteRecovery(preparation.operationId(), next); + }); } finally { release.countDown(); } @@ -1063,16 +1076,17 @@ void successfulDeliveryCanInitializeWhileCompletionCallbackIsDelayed() throws Ex var callbackEntered = new java.util.concurrent.CountDownLatch(1); var callbackRelease = new java.util.concurrent.CountDownLatch(1); var lifetime = new java.util.concurrent.CompletableFuture(); - lifetime.whenComplete((ignored, failure) -> { - callbackEntered.countDown(); - try { - if (!callbackRelease.await(5, java.util.concurrent.TimeUnit.SECONDS)) - throw new AssertionError("completion callback was not released"); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new AssertionError(interrupted); - } - }); + var callback = + lifetime.whenComplete((ignored, failure) -> { + callbackEntered.countDown(); + try { + if (!callbackRelease.await(5, java.util.concurrent.TimeUnit.SECONDS)) + throw new AssertionError("completion callback was not released"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + }); try (var session = deadlineBoundRedisOwner.prepareTimelineInitialization( preparation, Duration.ofSeconds(30), identity)) { @@ -1086,9 +1100,11 @@ void successfulDeliveryCanInitializeWhileCompletionCallbackIsDelayed() throws Ex lifetime); assertThat(callbackEntered.await(5, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); assertThat(session.initialize(claim.orElseThrow())).isNotNull(); + assertThat(callback.isDone()).isFalse(); } finally { callbackRelease.countDown(); } + callback.get(5, java.util.concurrent.TimeUnit.SECONDS); } } finally { dropSchema(testSchema.schema()); From d754162e546f0e3546195f4fe7142393b30d3b4e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 16:05:00 +1300 Subject: [PATCH 27/51] Apply exact Spotless formatting to #3445 integration fixtures --- ...meplayRegionLeaseOwnerIntegrationTest.java | 3 ++- ...untimeStatusRepositoryIntegrationTest.java | 20 +++++++++---------- ...tatusRepositoryIntegrationTestSupport.java | 3 ++- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index f699480386..ff54230268 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -173,7 +173,8 @@ record ReadOutcome(Throwable failure, long elapsedNanos) {} CompletableFuture.supplyAsync(() -> { long startedAt = System.nanoTime(); Throwable failure = - catchThrowable(() -> owner.readInstallationIncarnation(transferOwner, deadline, source)); + catchThrowable( + () -> owner.readInstallationIncarnation(transferOwner, deadline, source)); return new ReadOutcome(failure, System.nanoTime() - startedAt); }); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 905be23485..63541f13f1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -278,16 +278,16 @@ public void executeStart(ExecuteContext context) { }; var failingRepository = new CanonicalGameplayRegionRuntimeStatusRepository( - DSL.using(dsl.configuration().derive(new DefaultExecuteListenerProvider(failOwnerRead)))); - assertThatThrownBy( - () -> - installAfterBarrier( - failingRepository, - prior, - SECOND_LEASE_CORRELATION, - "instance-failure", - new CountDownLatch(1), - new CountDownLatch(0))) + DSL.using( + dsl.configuration().derive(new DefaultExecuteListenerProvider(failOwnerRead)))); + assertThatThrownBy(() -> + installAfterBarrier( + failingRepository, + prior, + SECOND_LEASE_CORRELATION, + "instance-failure", + new CountDownLatch(1), + new CountDownLatch(0))) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical Game Session region ownership is unavailable") .hasRootCauseMessage("Injected owner-row database failure"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java index 1c43101807..ea950f9530 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java @@ -1045,7 +1045,8 @@ CanonicalGameplayRegionRuntimeStatus installAfterBarrier( Instant.parse("2026-10-26T00:00:02Z")); } catch (IllegalStateException failure) { if (failure.getCause() - instanceof CanonicalGameplayRegionRuntimeStatusRepository.ExistingOwnerReplacementRefused) { + instanceof + CanonicalGameplayRegionRuntimeStatusRepository.ExistingOwnerReplacementRefused) { return null; } throw failure; From 185d81eab66e37df06280e4072282c4bb9c5c5ab Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 21:29:19 +1300 Subject: [PATCH 28/51] Reuse the retained Redis connection for committed transfer readback --- ...calGameplayOriginalNewCapacityExecutionOwner.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index d54436af4e..fbfb2e10e6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -1022,10 +1022,12 @@ private String requireCandidateAndIndexes( + "\",\"bindingGeneration\":\"" + candidate.transition().bindingGeneration() + "\"}"; - StatefulRedisConnection connection = connectForRead(); + var retainedConnection = transferReadConnection; + StatefulRedisConnection connection = + retainedConnection == null ? connectForRead() : retainedConnection; try { var commands = connection.async(); - principal(commands); + if (retainedConnection == null) principal(commands); byte[] session = bytes(CanonicalGameplaySessionRedisKeys.session(assignment, binding.bindingRef())); byte[] character = @@ -1073,8 +1075,10 @@ private String requireCandidateAndIndexes( if (actual != null) Arrays.fill(actual, (byte) 0); } } finally { - budget.awaitAsyncClose( - CanonicalGameplayOriginalNewCapacityExecutionBudget.startRedisClose(connection)); + if (retainedConnection == null) { + budget.awaitAsyncClose( + CanonicalGameplayOriginalNewCapacityExecutionBudget.startRedisClose(connection)); + } } } From 392708ca9df84fefac56796942b48969d44004a1 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 23 Nov 2026 01:37:50 +1300 Subject: [PATCH 29/51] Prove a recreated region owner observes its applied receipt before retaining the fence --- ...ransferCapacityCustodyIntegrationTest.java | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 40febaa0fd..b2c86334fa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -314,6 +314,129 @@ void sealedDispatchRestartRecoversNeverSentButPreservesAppliedThenLost(boolean a } } + @Test + void recreatedOwnerObservesAppliedReceiptBeforeRetainingItsExactFence() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + long deadline = transferDeadline(); + var item = + proof.transfers.within(deadline, ignored -> proof.transfers.capture(id).getFirst()); + proof.transfers.within( + deadline, + budget -> { + var before = proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), deadline); + var dispatch = proof.transfers.fenceDispatch(item, before); + proof + .capacity(proof.sql) + .forTransferBudget(budget) + .fenceForTransfer(item, dispatch, deadline); + return null; + }); + assertThat(proof.itemImage(id)) + .contains("\"fence_apply_issued\": true", "\"fence_readback\": null"); + proof.recreateTransferOwners(); + var completed = new java.util.concurrent.CompletableFuture(); + var commands = new java.util.concurrent.atomic.AtomicInteger(); + var observedRedis = org.mockito.Mockito.mock(io.lettuce.core.RedisClient.class); + org.mockito.Mockito.when(observedRedis.connect(ByteArrayCodec.INSTANCE)) + .thenAnswer(ignored -> + observingReceiptConnection( + proof.redis.connect(ByteArrayCodec.INSTANCE), completed, commands)); + var recovered = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + proof.sql, observedRedis, proof.scripts, proof.clock, proof.tags); + long recoveryDeadline = transferDeadline(); + proof.transfers.within( + recoveryDeadline, + budget -> { + var before = + proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), recoveryDeadline); + var dispatch = proof.transfers.fenceDispatch(item, before); + var actual = + recovered + .forTransferBudget(budget) + .fenceForTransfer(item, dispatch, recoveryDeadline); + var after = + proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), recoveryDeadline); + proof.transfers.retainFence(item, actual, before, after); + return null; + }); + assertThat(completed.get(2, java.util.concurrent.TimeUnit.SECONDS)) + .isEqualTo(ReceiptAction.OBSERVE); + assertThat(commands.get()).isEqualTo(1); + assertThat(proof.itemImage(id)).doesNotContain("\"fence_readback\": null"); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + } + } + + private enum ReceiptAction { + PREPARE, + APPLY, + OBSERVE + } + + @SuppressWarnings("unchecked") + private static io.lettuce.core.api.StatefulRedisConnection + observingReceiptConnection( + io.lettuce.core.api.StatefulRedisConnection real, + java.util.concurrent.CompletableFuture completed, + java.util.concurrent.atomic.AtomicInteger commands) { + var actual = real.async(); + var observed = + java.lang.reflect.Proxy.newProxyInstance( + io.lettuce.core.api.async.RedisAsyncCommands.class.getClassLoader(), + new Class[] {io.lettuce.core.api.async.RedisAsyncCommands.class}, + (proxy, method, arguments) -> { + if (!"evalsha".equals(method.getName()) + || arguments.length != 4 + || !(arguments[3] instanceof byte[][] values) + || values.length != 9) return invokeRedis(actual, method, arguments); + // Do not stringify, retain, or render any argument; classify only the action. + ReceiptAction action = null; + for (var candidate : ReceiptAction.values()) { + if (java.util.Arrays.equals(values[0], ascii(candidate.name()))) action = candidate; + } + if (action == null || commands.incrementAndGet() != 1) { + throw new AssertionError("Unexpected transfer receipt action or replay"); + } + ReceiptAction observedAction = action; + var result = (io.lettuce.core.RedisFuture) invokeRedis(actual, method, arguments); + result.whenComplete((value, failure) -> { + if (failure == null + && value instanceof List row + && row.size() == 3 + && Long.valueOf( + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner + .CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED) + .equals(row.get(0)) + && row.get(2) instanceof byte[] state + && java.util.Arrays.equals(ascii("APPLIED"), state)) { + completed.complete(observedAction); + } else { + completed.completeExceptionally( + new AssertionError("Redis did not complete the exact terminal observation")); + } + }); + return result; + }); + return (io.lettuce.core.api.StatefulRedisConnection) + java.lang.reflect.Proxy.newProxyInstance( + io.lettuce.core.api.StatefulRedisConnection.class.getClassLoader(), + new Class[] {io.lettuce.core.api.StatefulRedisConnection.class}, + (proxy, method, arguments) -> + "async".equals(method.getName()) ? observed : invokeRedis(real, method, arguments)); + } + + private static Object invokeRedis(Object receiver, java.lang.reflect.Method method, Object[] args) + throws Throwable { + try { + return method.invoke(receiver, args); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + } + @Override PostgreSQLContainer postgresContainer() { return POSTGRES; From 79525cdb7c042dea9c1d83808d0748ed9b0becbd Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 23 Nov 2026 03:30:20 +1300 Subject: [PATCH 30/51] Import the capacity execution type in region serialization integration tests --- ...onicalGameplayRegionTransferSerializationIntegrationTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java index 9199804937..634a36ffff 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java @@ -15,6 +15,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; import org.jooq.ExecuteContext; From 4656639e0d8a40003428e10182772ca00de9c721 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 23 Nov 2026 05:32:05 +1300 Subject: [PATCH 31/51] Keep transfer PREPARE fixture in the admitted operation budget --- ...ayRegionTransferCapacityCustodyIntegrationTest.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index b2c86334fa..c1aca9dad4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -277,7 +277,15 @@ void sealedDispatchRestartRecoversNeverSentButPreservesAppliedThenLost(boolean a } else { var finalOwner = new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( - proof.redis, proof.scripts, proof.clock, proof.tags); + proof.redis, + proof.scripts, + proof.clock, + proof.tags.withCapacityExecutionDsl(budget.sql(proof.sql)), + () -> + CanonicalGameplayOriginalNewCapacityExecutionOwner.connectForRead( + proof.redis, budget), + budget::remainingMillis, + budget::awaitAsyncClose); var prepared = finalOwner.prepareTransferReceipt( item.execution(), item.candidate(), item.assignment(), dispatch, deadline); From 29353777af51569802eb51145691bba4033e5472 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 23 Nov 2026 08:45:18 +1300 Subject: [PATCH 32/51] Strengthen region handoff and retained custody test proofs --- ...CapacityRetentionOwnerIntegrationTest.java | 5 +- ...onHandoffLeaseDeadlineIntegrationTest.java | 27 ++++++-- ...meplayRegionLeaseOwnerIntegrationTest.java | 24 ++++++- ...GameplayRegionOwnerCompositionFixture.java | 10 +++ ...ransferCapacityCustodyIntegrationTest.java | 35 ++++++++--- ...nTransferSerializationIntegrationTest.java | 63 ++++++++++++++++--- ...eFamilyCatalogPostgresIntegrationTest.java | 12 ++-- ...riginalNewCapacityExecutionBudgetTest.java | 58 ++++++++++++----- ...nOwnerTransferObservationReceiverTest.java | 2 + 9 files changed, 191 insertions(+), 45 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java index 308a6dab29..e87b214f56 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java @@ -59,12 +59,13 @@ void transferFenceRejectsChangedCandidateDigestBeforeSubmittingRedis() throws Ex String retained = sqlImage(); Map physical = physicalImage(); + var noRedis = org.mockito.Mockito.mock(io.lettuce.core.RedisClient.class); assertThatThrownBy(() -> - new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( - ownerClient, catalog, CLOCK, tags) + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner(noRedis, catalog, CLOCK, tags) .fenceCapacityExecutionOnce( changed, source.candidate(), assignment, UUID.randomUUID(), deadline())) .isInstanceOf(IllegalStateException.class); + org.mockito.Mockito.verifyNoInteractions(noRedis); assertThat(admin.type(ascii(capacityKey(assignment)))).isEqualTo("none"); assertThat(sqlImage()).isEqualTo(retained); assertThat(physicalImage()).isEqualTo(physical); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java index 120ec42d37..305e97458e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java @@ -166,11 +166,21 @@ void retainedTransferObservationDoesNotWaitOnInventoryClock() throws Exception { + " WHERE singleton_id=1 FOR UPDATE") .close(); } - try { - var observation = receiver.observeForRegionOwnerTransfer(transferId, 0, deadline()); - assertThat(observation.regionOwnerTransferContext().controlState()).isEqualTo("FROZEN"); - } finally { - blocker.rollback(); + var worker = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor(); + try (AutoCloseable shutdown = + () -> { + worker.shutdownNow(); + assertThat(worker.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS)) + .as("bounded SQL observation caller termination") + .isTrue(); + }) { + var pending = + worker.submit(() -> receiver.observeForRegionOwnerTransfer(transferId, 0, deadline())); + try (AutoCloseable cancel = () -> pending.cancel(true); + AutoCloseable rollback = blocker::rollback) { + var observation = pending.get(5, java.util.concurrent.TimeUnit.SECONDS); + assertThat(observation.regionOwnerTransferContext().controlState()).isEqualTo("FROZEN"); + } } } } @@ -1015,6 +1025,11 @@ private void delayedPredecessorAfterHandoff(boolean installAction) throws Except assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); assertThat(CLOCK.millis()).isLessThan(frozenDeadline); var fencedPhysical = physicalImage(); + var successorLeaseKey = ascii(successor.grant.key()); + var successorLeaseToken = admin.get(successorLeaseKey); + assertThat(successorLeaseToken).isNotEmpty(); + long successorLeaseExpiry = admin.pexpiretime(successorLeaseKey); + assertThat(successorLeaseExpiry).isGreaterThan(CLOCK.millis()); release.countDown(); assertThat(redisReply.get(2, java.util.concurrent.TimeUnit.SECONDS)).isEqualTo(-1L); assertThat(dispatchedAt.get()).isPositive().isLessThan(frozenDeadline); @@ -1024,6 +1039,8 @@ private void delayedPredecessorAfterHandoff(boolean installAction) throws Except .hasCauseInstanceOf(IllegalStateException.class); assertThat(calls.get()).isOne(); assertThat(physicalImage()).isEqualTo(fencedPhysical); + assertThat(admin.get(successorLeaseKey)).containsExactly(successorLeaseToken); + assertThat(admin.pexpiretime(successorLeaseKey)).isEqualTo(successorLeaseExpiry); assertThat(admin.get(ascii(installation.sessionKey()))) .containsExactly(source.candidate().canonicalBytes()); assertThat( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 5d01349bbf..3db1a872e0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1016,11 +1016,12 @@ private void assertCancelledCompanionClaimRecovered( var recoveredClaim = new AtomicReference< CanonicalGameplayRegionRuntimeStatusRepository.InitialInitializationPermit>(); + Thread caller = null; try (var context = io.grpc.Context.current().withCancellation(); var session = deadlineBoundRedisOwner.prepareTimelineInitialization( preparation, Duration.ofSeconds(30), identity)) { - Thread caller = + caller = Thread.ofVirtual() .start(() -> context.run(() -> { @@ -1119,6 +1120,15 @@ private void assertCancelledCompanionClaimRecovered( }); } finally { release.countDown(); + if (caller != null) { + caller.join(5000); + assertThat(caller.isAlive()) + .as("retained caller exited before fixture teardown") + .isFalse(); + } + if (entered.getCount() == 0L) { + lifetime.get(5, TimeUnit.SECONDS); + } } } } finally { @@ -1341,11 +1351,12 @@ public void release(Connection connection) { method.setAccessible(true); var lifetime = new java.util.concurrent.CompletableFuture(); var outcome = new java.util.concurrent.CompletableFuture(); + Thread caller = null; try (var context = io.grpc.Context.current().withCancellation(); var session = deadlineBoundRedisOwner.prepareTimelineInitialization( preparation, Duration.ofSeconds(30), identity)) { - Thread caller = + caller = Thread.ofVirtual() .start(() -> context.run(() -> { @@ -1399,6 +1410,15 @@ public void release(Connection connection) { assertThat(releasedConnection.await(5, TimeUnit.SECONDS)).isTrue(); } finally { release.countDown(); + if (caller != null) { + caller.join(5000); + assertThat(caller.isAlive()) + .as("retained caller exited before fixture teardown") + .isFalse(); + } + if (entered.getCount() == 0L) { + lifetime.get(5, TimeUnit.SECONDS); + } } } } finally { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index b5d463e1f6..ce588287fb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -1299,6 +1299,7 @@ private static TwoBindingProof installAndBridgeInternal( runtimeIdentity, Duration.ofSeconds(30), Clock.systemUTC()); + var beforeFenceSequence = regionFenceSequence(dsl); var beforeTakeover = snapshotRegionOwnerSqlState( dsl, identity.tenantId(), identity.gameInstanceId(), identity.regionId()); @@ -1307,6 +1308,7 @@ private static TwoBindingProof installAndBridgeInternal( throw new AssertionError("Compatibility takeover unexpectedly succeeded"); } catch (IllegalStateException expected) { if (redis.admin().get(redisKey) != null + || !beforeFenceSequence.equals(regionFenceSequence(dsl)) || !beforeTakeover.equals( snapshotRegionOwnerSqlState( dsl, identity.tenantId(), identity.gameInstanceId(), identity.regionId()))) { @@ -1526,6 +1528,12 @@ public T run( }; } + private static Long regionFenceSequence(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchSingle("SELECT last_value FROM game_session_region_executor_fence_seq") + .get(0, Long.class)); + } + private static CompatibilityTakeoverProof refuseCompatibilityTakeoverAfterAcknowledgement( DSLContext dsl, RegionRedis redis, @@ -1584,6 +1592,7 @@ private static CompatibilityTakeoverProof refuseCompatibilityTakeoverAfterAcknow acknowledged.transitionId())); var beforePhysical = snapshotRegionBridgeRedisState(redis, acknowledgedRow, acknowledged.runtimeEntityId()); + var beforeFenceSequence = regionFenceSequence(dsl); String refusalMessage = null; try { replacementOwner.installForTransition(acknowledged.transitionId(), worldRequest); @@ -1596,6 +1605,7 @@ private static CompatibilityTakeoverProof refuseCompatibilityTakeoverAfterAcknow .orElseThrow(); if (refusalMessage == null || redis.admin().get(leaseKey) != null + || !beforeFenceSequence.equals(regionFenceSequence(dsl)) || !beforeRegion.equals( snapshotRegionOwnerSqlState( dsl, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index c1aca9dad4..6b06699ac0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -85,7 +85,15 @@ void restoredPreparedReceiptCannotReapplyAfterDurableIssuance() throws Exception proof.sql.execute( "UPDATE game_session_region_owner_transfer_item SET fence_apply_issued=false WHERE transfer_id=?", id)) - .isInstanceOf(org.jooq.exception.DataAccessException.class); + .rootCause() + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()).contains("Apply issuance cannot be reset"); + }); + assertThat(proof.itemImage(id)).isEqualTo(retained); + assertThat(proof.itemImage(id)).contains("\"fence_apply_issued\": true"); } } @@ -1106,15 +1114,26 @@ void standaloneTransferObservationCancelsBlockedSqlAtItsExplicitDeadline() throw try (var statement = lock.createStatement()) { statement.execute("LOCK TABLE game_session_region_owner_transfer IN ACCESS EXCLUSIVE MODE"); } - try { + var worker = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor(); + try (AutoCloseable shutdown = + () -> { + worker.shutdownNow(); + assertThat(worker.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS)) + .as("bounded SQL observation caller termination") + .isTrue(); + }) { long start = System.nanoTime(); - assertThatThrownBy(() -> + var pending = + worker.submit(() -> proof.receiver.observeForRegionOwnerTransfer( - id, captured.getFirst().ordinal(), proof.clock.millis() + 500L)) - .isInstanceOf(ObservationUnavailableException.class); - assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofSeconds(3)); - } finally { - lock.rollback(); + id, captured.getFirst().ordinal(), proof.clock.millis() + 500L)); + try (AutoCloseable cancel = () -> pending.cancel(true); + AutoCloseable rollback = lock::rollback) { + assertThatThrownBy(() -> pending.get(3, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(ObservationUnavailableException.class); + assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofSeconds(3)); + } } assertThat( proof diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java index 634a36ffff..d62ee5c623 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java @@ -788,22 +788,44 @@ void frozenContinuationWaitsBeforeRegionWhileAcknowledgedBridgeOwnsInventory() t gate.arm(); Future replay = executor.submit(proof::replayBridge); gate.awaitLock(); + var continuationLocks = new java.util.concurrent.CopyOnWriteArrayList(); + var observer = + new ExecuteListener() { + @Override + public void executeStart(ExecuteContext context) { + String query = context.sql(); + if (query != null && query.endsWith("FOR UPDATE")) { + if (query.contains("game_session_canonical_binding_inventory_clock")) { + continuationLocks.add("inventory"); + } else if (query.contains("game_session_region_runtime_status")) { + continuationLocks.add("region"); + } + } + } + }; + var continuationRepository = + proof.transfers( + DSL.using( + proof.sql.configuration().derive(new DefaultExecuteListenerProvider(observer)))); Future continuation = executor.submit(() -> - proof.transfers.within( + continuationRepository.within( transferDeadline(), ignored -> { - proof.transfers.requireFrozenOriginal(original, proof.scope, proof.prior); + continuationRepository.requireFrozenOriginal( + original, proof.scope, proof.prior); return null; })); try { assertDatabaseWaitsFor(proof.sql, gate.backendPid()); assertThat(continuation.isDone()).isFalse(); + assertThat(continuationLocks).containsExactly("inventory"); } finally { gate.release(); } replay.get(10, TimeUnit.SECONDS); continuation.get(10, TimeUnit.SECONDS); + assertThat(continuationLocks).containsExactly("inventory", "region"); assertThat(proof.transferImage(id)).isEqualTo(before); assertThat(proof.executionState(proof.execution)).isEqualTo("INSTALL_DISPATCHED"); assertThat(proof.currentOwner()).isEqualTo(proof.prior); @@ -811,7 +833,7 @@ void frozenContinuationWaitsBeforeRegionWhileAcknowledgedBridgeOwnsInventory() t } @Test - void competingTransferCreatorsAndLostBeginReplyKeepOneOriginalIntent() throws Exception { + void competingTransferCreatorsKeepOneOriginalIntent() throws Exception { try (var proof = new TransferSqlProof(); ExecutorService executor = Executors.newFixedThreadPool(2)) { proof.seedUndeliveredDispatch(proof.execution); @@ -825,14 +847,39 @@ void competingTransferCreatorsAndLostBeginReplyKeepOneOriginalIntent() throws Ex start.countDown(); UUID retained = first.get(10, TimeUnit.SECONDS); assertThat(second.get(10, TimeUnit.SECONDS)).isEqualTo(retained); - String original = proof.transferImage(retained); + assertThat( + proof + .sql + .fetchSingle("SELECT count(*) FROM game_session_region_owner_transfer") + .get(0, Long.class)) + .isEqualTo(1L); + } + } + + @Test + void lostCreateReplyKeepsOneOriginalIntent() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + assertThat( + proof + .sql + .fetchSingle("SELECT count(*) FROM game_session_region_owner_transfer") + .get(0, Long.class)) + .isZero(); assertThatThrownBy( () -> { - other.within(transferDeadline(), ignored -> other.begin(proof.scope, proof.prior)); - throw new IllegalStateException( - "Controlled lost begin reply after committed readback"); + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.begin(proof.scope, proof.prior)); + throw new IllegalStateException("Controlled lost reply after transfer creation"); }) - .hasMessage("Controlled lost begin reply after committed readback"); + .hasMessage("Controlled lost reply after transfer creation"); + var retained = + proof + .sql + .fetchSingle("SELECT transfer_id FROM game_session_region_owner_transfer") + .get(0, UUID.class); + assertThat(retained).isNotNull(); + String original = proof.transferImage(retained); var recreated = proof.transfers(proof.sql); UUID replayed = recreated.within( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 0800059da8..94f8f3eab2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -205,7 +205,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1065.0.10", "catalog-installation:1065.0.11", "catalog-installation:1065.0.12", - "catalog-installation:1065.0.13") + "catalog-installation:1065.0.13", + "catalog-installation:1065.0.14") .noneMatch(identity -> identity.contains(":1057:") || identity.contains(":1058:") @@ -228,7 +229,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1065.0.10:") || identity.contains(":1065.0.11:") || identity.contains(":1065.0.12:") - || identity.contains(":1065.0.13:")); + || identity.contains(":1065.0.13:") + || identity.contains(":1065.0.14:")); assertThat( f.dsl .fetchSingle( @@ -920,7 +922,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.10", "1065.0.11", "1065.0.12", - "1065.0.13")) { + "1065.0.13", + "1065.0.14")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -970,7 +973,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.10", "1065.0.11", "1065.0.12", - "1065.0.13")) { + "1065.0.13", + "1065.0.14")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java index a5e060a05c..e41b387d76 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java @@ -684,20 +684,33 @@ void actualTransferCommittedReadBoundsAcquisitionAndCannotExecuteAfterItsDeadlin UUID transitionId = UUID.randomUUID(); when(candidate.bindingDecisionId()).thenReturn(transitionId); long started = System.nanoTime(); - try { - assertThatThrownBy(() -> + var caller = Executors.newVirtualThreadPerTaskExecutor(); + var pending = new AtomicReference>(); + try (AutoCloseable cleanup = + () -> { + release.countDown(); + var submitted = pending.get(); + if (submitted != null) submitted.cancel(true); + caller.shutdownNow(); + assertThat(caller.awaitTermination(5, TimeUnit.SECONDS)) + .as("bounded acquisition caller termination") + .isTrue(); + verify(provider, timeout(2000)).release(connection); + verifyNoInteractions(connection); + }) { + var read = + caller.submit(() -> inventory.withinTransferRead( CLOCK, CLOCK.millis() + 1000, - scoped -> scoped.readRegionTransferCommittedSource(transitionId, candidate))) - .isInstanceOf(IllegalStateException.class); + scoped -> scoped.readRegionTransferCommittedSource(transitionId, candidate))); + pending.set(read); + assertThatThrownBy(() -> read.get(3, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class); assertThat(entered.await(1, TimeUnit.SECONDS)).isTrue(); assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2500); verifyNoInteractions(connection); - } finally { - release.countDown(); - verify(provider, timeout(2000)).release(connection); - verifyNoInteractions(connection); } } @@ -754,18 +767,31 @@ void handoffStatusReadBoundsAcquisitionAndCannotExecuteAfterItsDeadline() throws "d".repeat(64), "sha256:" + "e".repeat(64)); - try { - assertThatThrownBy(() -> + var caller = Executors.newVirtualThreadPerTaskExecutor(); + var pending = new AtomicReference>(); + try (AutoCloseable cleanup = + () -> { + release.countDown(); + var submitted = pending.get(); + if (submitted != null) submitted.cancel(true); + caller.shutdownNow(); + assertThat(caller.awaitTermination(5, TimeUnit.SECONDS)) + .as("bounded acquisition caller termination") + .isTrue(); + verify(provider, timeout(2000)).release(connection); + verifyNoInteractions(connection); + }) { + var read = + caller.submit(() -> transfer.withStatusRepository( CLOCK.millis() + 1000, - statusRepository -> statusRepository.findTimelinePreparation(regionSource))) - .isInstanceOf(IllegalStateException.class); + statusRepository -> statusRepository.findTimelinePreparation(regionSource))); + pending.set(read); + assertThatThrownBy(() -> read.get(3, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class); assertThat(entered.await(1, TimeUnit.SECONDS)).isTrue(); verifyNoInteractions(connection); - } finally { - release.countDown(); - verify(provider, timeout(2000)).release(connection); - verifyNoInteractions(connection); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java index 8a246cf1fa..d346436532 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java @@ -841,6 +841,8 @@ private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observ long deadline) { return CanonicalGameplayProtectedIncarnationReceiver.forRegionOwnerTransfer( (transferId, ordinal) -> { + assertThat(transferId).isEqualTo(original.transferId()); + assertThat(ordinal).isEqualTo(original.targetOrdinal()); sourceReads.incrementAndGet(); onSourceRead.run(); if (sourceUnavailable) { From c4a6c6567c8f606c9b1c3601f3cf6a17552d98a8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 23 Nov 2026 12:36:40 +1300 Subject: [PATCH 33/51] Exercise current receipt recovery for both terminal capacity outcomes --- ...ransferCapacityCustodyIntegrationTest.java | 154 +++++++++++++++++- 1 file changed, 148 insertions(+), 6 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 6b06699ac0..92bb5a375c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -358,7 +358,11 @@ void recreatedOwnerObservesAppliedReceiptBeforeRetainingItsExactFence() throws E org.mockito.Mockito.when(observedRedis.connect(ByteArrayCodec.INSTANCE)) .thenAnswer(ignored -> observingReceiptConnection( - proof.redis.connect(ByteArrayCodec.INSTANCE), completed, commands)); + proof.redis.connect(ByteArrayCodec.INSTANCE), + completed, + commands, + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner + .CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED)); var recovered = new CanonicalGameplayOriginalNewCapacityExecutionOwner( proof.sql, observedRedis, proof.scripts, proof.clock, proof.tags); @@ -397,7 +401,8 @@ private enum ReceiptAction { observingReceiptConnection( io.lettuce.core.api.StatefulRedisConnection real, java.util.concurrent.CompletableFuture completed, - java.util.concurrent.atomic.AtomicInteger commands) { + java.util.concurrent.atomic.AtomicInteger commands, + long expectedCode) { var actual = real.async(); var observed = java.lang.reflect.Proxy.newProxyInstance( @@ -422,10 +427,7 @@ private enum ReceiptAction { if (failure == null && value instanceof List row && row.size() == 3 - && Long.valueOf( - CanonicalGameplayOriginalNewFinalAdmissionRedisOwner - .CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED) - .equals(row.get(0)) + && Long.valueOf(expectedCode).equals(row.get(0)) && row.get(2) instanceof byte[] state && java.util.Arrays.equals(ascii("APPLIED"), state)) { completed.complete(observedAction); @@ -1430,6 +1432,146 @@ void interruptedFenceRetentionRecoversExactTerminalProofWithoutDispatchingAgain( } } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {true, false}) + void interruptedForwardReceiptRecoversExactTerminalProofWithoutReapplying(boolean committed) + throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), proof.clock); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + proof + .capacity(proof.sql) + .authorize( + proof.admission, template, account, issuer, proof.execution, transferDeadline()); + var finalOwner = + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + proof.redis, proof.scripts, proof.clock, proof.tags); + var assignment = proof.tags.assignmentForTransition(proof.execution.transitionId()); + if (!committed) { + finalOwner.closeCapacityExecutionOnce( + proof.execution, proof.admission.candidate(), assignment, transferDeadline()); + } + try (var physicalCommit = + committed + ? new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + proof.redis, proof.scripts, proof.clock, proof.tags) + .finalizeOriginalNewOnce( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline()) + : null) { + UUID id = proof.begin(); + long deadline = transferDeadline(); + var item = + proof.transfers.within(deadline, ignored -> proof.transfers.capture(id).getFirst()); + long terminalCode = + committed + ? CanonicalGameplayOriginalNewFinalAdmissionRedisOwner + .CAPACITY_EXECUTION_COMMITTED_OBSERVED + : CanonicalGameplayOriginalNewFinalAdmissionRedisOwner + .CAPACITY_EXECUTION_CLOSED_OBSERVED; + proof.transfers.within( + deadline, + budget -> { + var before = + proof.receiver.observeForRegionOwnerTransfer(id, item.ordinal(), deadline); + var dispatch = proof.transfers.fenceDispatch(item, before); + var scoped = + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + proof.redis, + proof.scripts, + proof.clock, + proof.tags.withCapacityExecutionDsl(budget.sql(proof.sql)), + () -> + CanonicalGameplayOriginalNewCapacityExecutionOwner.connectForRead( + proof.redis, budget), + budget::remainingMillis, + budget::awaitAsyncClose); + var prepared = + scoped.prepareTransferReceipt( + item.execution(), item.candidate(), item.assignment(), dispatch, deadline); + dispatch.seal(prepared); + assertThat( + scoped.applyTransferReceipt( + item.execution(), + item.candidate(), + item.assignment(), + dispatch, + deadline)) + .isEqualTo(terminalCode); + // End after the actual terminal receipt, before the receiving owner retains SQL. + return null; + }); + assertThat(proof.executionState(proof.execution)).isEqualTo("AUTHORIZED"); + assertThat(proof.itemImage(id)) + .contains("\"fence_apply_issued\": true", "\"fence_readback\": null"); + UUID retainedDispatch = + proof + .sql + .fetchSingle( + "SELECT fence_dispatch_id FROM game_session_region_owner_transfer_item WHERE" + + " transfer_id=?", + id) + .get("fence_dispatch_id", UUID.class); + assertThat(retainedDispatch).isNotNull(); + proof.recreateTransferOwners(); + var completed = new java.util.concurrent.CompletableFuture(); + var commands = new java.util.concurrent.atomic.AtomicInteger(); + var observedRedis = org.mockito.Mockito.mock(io.lettuce.core.RedisClient.class); + org.mockito.Mockito.when(observedRedis.connect(ByteArrayCodec.INSTANCE)) + .thenAnswer(ignored -> + observingReceiptConnection( + proof.redis.connect(ByteArrayCodec.INSTANCE), + completed, + commands, + terminalCode)); + var recovered = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + proof.sql, observedRedis, proof.scripts, proof.clock, proof.tags); + long recoveryDeadline = transferDeadline(); + proof.transfers.within( + recoveryDeadline, + budget -> { + var before = + proof.receiver.observeForRegionOwnerTransfer( + id, item.ordinal(), recoveryDeadline); + var dispatch = proof.transfers.fenceDispatch(item, before); + var actual = + recovered + .forTransferBudget(budget) + .fenceForTransfer(item, dispatch, recoveryDeadline); + var after = + proof.receiver.observeForRegionOwnerTransfer( + id, item.ordinal(), recoveryDeadline); + proof.transfers.retainFence(item, actual, before, after); + return null; + }); + assertThat(completed.get(2, java.util.concurrent.TimeUnit.SECONDS)) + .isEqualTo(ReceiptAction.OBSERVE); + assertThat(commands.get()).isEqualTo(1); + assertThat(proof.itemImage(id)) + .contains(retainedDispatch.toString()) + .doesNotContain("\"fence_readback\": null"); + assertThat(proof.executionState(proof.execution)) + .isEqualTo(committed ? "COMMITTED" : "CLOSED"); + proof.verifyPage(id); + boolean verified = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(verified).isTrue(); + assertThat(proof.install(id).executorFence()).isGreaterThan(proof.prior.executorFence()); + } + } + } + @Test void recreatedRepositoryRetainsLostFenceReplyAndImmutableOriginalReceiptsAndCompletion() throws Exception { From 59f68f430110b763488eb768a10cfcc7ae6c7ca1 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 23 Nov 2026 17:25:35 +1300 Subject: [PATCH 34/51] Correct region owner integration fixture setup and detached cleanup expectations --- ...meplayRegionLeaseOwnerIntegrationTest.java | 33 +++++++++---------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 8b93b825cf..a99aad98ea 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -770,7 +770,7 @@ void boundedTimelineCreationRejectsExpiryAndCapsNewLease() throws Exception { } @Test - void callerDeadlineDoesNotReleaseRetainedRecoveryBeforeActualSqlWorkerExit() throws Exception { + void detachedRecoveryRetainsOwnershipUntilSqlExitsAfterCallerCancellation() throws Exception { assertDeadlineDoesNotReleaseRetainedRecoveryBeforeActualSqlWorkerExit(false); } @@ -847,13 +847,8 @@ private void assertDeadlineDoesNotReleaseRetainedRecoveryBeforeActualSqlWorkerEx var retained = owner.reserveNoWriteRecovery(preparation.operationId()); owner.retainNoWriteProof(preparation, retained, proof); owner.releaseNoWriteRecovery(preparation.operationId(), retained); - var scheduler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); Thread caller = null; - try (var context = - viaInstallation - ? io.grpc.Context.ROOT.withCancellation() - : io.grpc.Context.current() - .withDeadlineAfter(500, java.util.concurrent.TimeUnit.MILLISECONDS, scheduler)) { + try (var context = io.grpc.Context.ROOT.withCancellation()) { var outcome = new java.util.concurrent.CompletableFuture(); var installWatchdog = new java.util.concurrent.CompletableFuture(); var failureNanos = new java.util.concurrent.atomic.AtomicLong(); @@ -875,35 +870,38 @@ private void assertDeadlineDoesNotReleaseRetainedRecoveryBeforeActualSqlWorkerEx } else { owner.recoverRetainedNoWriteForTransition(TRANSITION_ID); } - outcome.complete(new AssertionError("caller ignored deadline")); + outcome.complete(null); } catch (Throwable failure) { failureNanos.set(System.nanoTime()); outcome.complete(failure); } })); assertThat(entered.await(5, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); - Throwable failure; if (viaInstallation) { long stop = installWatchdog.get(1, java.util.concurrent.TimeUnit.SECONDS); - failure = + Throwable failure = outcome.get( Math.max(0L, stop - System.nanoTime()), java.util.concurrent.TimeUnit.NANOSECONDS); + assertThat(failure).isInstanceOf(IllegalStateException.class); assertThat(failureNanos.get() - stop) .as("caller error before absolute watchdog") .isNegative(); + caller.join(2_000); + assertThat(caller.isAlive()).isFalse(); + org.mockito.Mockito.verifyNoInteractions(inventory); } else { - failure = outcome.get(2, java.util.concurrent.TimeUnit.SECONDS); + context.cancel(null); + assertThat(outcome.isDone()).isFalse(); } - assertThat(failure).isInstanceOf(IllegalStateException.class); - caller.join(2000); - assertThat(caller.isAlive()).isFalse(); - if (viaInstallation) org.mockito.Mockito.verifyNoInteractions(inventory); assertThat(exited.getCount()).isEqualTo(1L); assertThatThrownBy(() -> owner.reserveNoWriteRecovery(preparation.operationId())) .isInstanceOf(IllegalStateException.class); release.countDown(); assertThat(exited.await(5, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + if (!viaInstallation) { + assertThat(outcome.get(5, java.util.concurrent.TimeUnit.SECONDS)).isNull(); + } org.awaitility.Awaitility.await() .atMost(java.time.Duration.ofSeconds(5)) .untilAsserted(() -> { @@ -920,7 +918,6 @@ private void assertDeadlineDoesNotReleaseRetainedRecoveryBeforeActualSqlWorkerEx .isEqualTo("PREPARED"); } finally { release.countDown(); - scheduler.shutdownNow(); if (caller != null) { caller.join(5_000); assertThat(caller.isAlive()).as("caller must exit before fixture teardown").isFalse(); @@ -1576,8 +1573,8 @@ void ordinaryInstallationBorrowsAdmissionWhenOtherBackgroundSlotIsHeld() throws redis.ownerClient(), RedisFixture.clientUri(PRINCIPAL, PASSWORD), redis.catalog()); WorldFixture world = WorldFixture.open(); var inventory = mock(CanonicalGameplayBindingInventoryRepository.class); - when(inventory.readProvisionalCasEvidence(TRANSITION_ID)) - .thenReturn(provisionalEvidence(world.request())); + var evidence = provisionalEvidence(world.request()); + when(inventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(evidence); when(inventory.forBudget(org.mockito.ArgumentMatchers.any())).thenReturn(inventory); org.mockito.Mockito.doAnswer( invocation -> { From ef0b3c4ed72f0fdb24f266fac54e878115c717ca Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 24 Nov 2026 02:41:11 +1300 Subject: [PATCH 35/51] Anchor the physical Redis expiry regression after committed SQL claim --- ...meplayRegionLeaseOwnerIntegrationTest.java | 75 +++++++++++++------ 1 file changed, 52 insertions(+), 23 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index adf54b343d..70fbfb4333 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1841,7 +1841,6 @@ public Instant instant() { }; var controlledRepository = org.mockito.Mockito.spy(statusRepository); var scopedRepositoryCalls = new java.util.concurrent.atomic.AtomicInteger(); - var installRedisCutoff = new java.util.concurrent.atomic.AtomicLong(); org.mockito.Mockito.doAnswer( invocation -> { int call = scopedRepositoryCalls.incrementAndGet(); @@ -1852,31 +1851,45 @@ public Instant instant() { } var budget = invocation.getArgument(0); - if (call == 1) installRedisCutoff.set(budget.absoluteDeadlineMillis()); - return statusRepository.forBudget(budget); + var scoped = statusRepository.forBudget(budget); + if (call != 1) return scoped; + var claimBoundary = org.mockito.Mockito.spy(scoped); + org.mockito.Mockito.doAnswer( + claimInvocation -> { + // Successful real PROBE already preceded this call. Do not spend + // local deadline waiting for Redis until the actual SQL claim commits. + var target = + claimInvocation + . + getArgument(0); + assertThat(target.operationId()).isEqualTo(preparation.operationId()); + var permit = (java.util.Optional) claimInvocation.callRealMethod(); + assertThat(permit).as("acknowledged real first-region claim").isPresent(); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT phase FROM game_session_region_timeline_preparation" + + " WHERE initialization_operation_id = ?", + preparation.operationId()) + .get(0, String.class)) + .isEqualTo("INITIALIZING"); + awaitRedisTimelineCutoff(redis.admin(), budget.absoluteDeadlineMillis()); + return permit; + }) + .when(claimBoundary) + .beginInitialTimeline( + org.mockito.ArgumentMatchers.any( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation + .class), + org.mockito.ArgumentMatchers.any(Instant.class), + org.mockito.ArgumentMatchers.any()); + return claimBoundary; }) .when(controlledRepository) .forBudget(org.mockito.ArgumentMatchers.any()); world.resetReads(); - // The second source read occurs after Redis preflight, before the irreversible SQL claim. - world.setAfterRead( - 2, - () -> { - try { - long redisCutoff = installRedisCutoff.get(); - assertThat(redisCutoff).as("actual install budget cutoff").isPositive(); - long stopWaiting = System.nanoTime() + TimeUnit.SECONDS.toNanos(3); - long observed = redisTimeMillis(redis.admin()); - while (observed < redisCutoff && System.nanoTime() < stopWaiting) { - Thread.sleep(10); - observed = redisTimeMillis(redis.admin()); - } - assertThat(observed).isGreaterThanOrEqualTo(redisCutoff); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - }); var owner = new CanonicalGameplayRegionLeaseOwner( inventory, @@ -1947,7 +1960,6 @@ public void commandSucceeded(CommandSucceededEvent event) { } finally { redis.ownerClient().removeListener(observedOwnerCommand); } - world.setAfterRead(2, () -> {}); if (refuseFirstCleanup) { assertThat(scopedRepositoryCalls).hasValue(2); assertThat( @@ -1980,6 +1992,23 @@ public void commandSucceeded(CommandSucceededEvent event) { } } + private static void awaitRedisTimelineCutoff( + io.lettuce.core.api.sync.RedisCommands admin, long cutoff) { + assertThat(cutoff).as("actual install budget cutoff").isPositive(); + long stopWaiting = System.nanoTime() + TimeUnit.SECONDS.toNanos(3); + long observed = redisTimeMillis(admin); + try { + while (observed < cutoff && System.nanoTime() < stopWaiting) { + Thread.sleep(10); + observed = redisTimeMillis(admin); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + assertThat(observed).as("physical Redis TIME at INITIALIZE").isGreaterThanOrEqualTo(cutoff); + } + private static long redisTimeMillis( io.lettuce.core.api.sync.RedisCommands admin) { var time = admin.time(); From ec53eb3a8818a3cd4f3166e8040f5a18bc1b0e7a Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 01:06:16 +1300 Subject: [PATCH 36/51] Require exact durable successor for Game Session transfer completion --- ...GameplayRegionOwnerTransferRepository.java | 8 ++ ...equire_exact_region_transfer_successor.sql | 123 ++++++++++++++++++ ...ransferCapacityCustodyIntegrationTest.java | 63 ++++++++- ...eFamilyCatalogPostgresIntegrationTest.java | 21 ++- 4 files changed, 203 insertions(+), 12 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.15__require_exact_region_transfer_successor.sql diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 0b9bbca163..6f757479ab 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -436,6 +436,14 @@ FenceDispatch fenceDispatch( tx, "SELECT 1 FROM " + ITEM + " WHERE execution_digest=? AND fence_readback IS NOT NULL", item.execution().digest())) return new FenceDispatch(item, null); + if (incarnation == null + && tx.execute( + "UPDATE " + + TRANSFER + + " SET incarnation_digest=? WHERE transfer_id=? AND incarnation_digest IS NULL", + before.incarnationDigest(), + item.transferId()) + != 1) throw unavailable(); if (clock.millis() >= before.expiresAtEpochMillis()) throw unavailable(); UUID dispatchId = UUID.randomUUID(); if (tx.execute( diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.15__require_exact_region_transfer_successor.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.15__require_exact_region_transfer_successor.sql new file mode 100644 index 0000000000..bee0ab6ed7 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.15__require_exact_region_transfer_successor.sql @@ -0,0 +1,123 @@ +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_gs_region_owner_transfer_custody() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF ROW(NEW.executor_fence,NEW.owner_instance_id,NEW.lease_token_correlation,NEW.owner_service) + IS NOT DISTINCT FROM ROW(OLD.executor_fence,OLD.owner_instance_id,OLD.lease_token_correlation,OLD.owner_service) THEN RETURN NEW; END IF; + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Region owner replacement requires READ COMMITTED owner fencing' USING ERRCODE='23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_session_region_owner_transfer t WHERE t.tenant_id=OLD.tenant_id + AND t.game_instance_id=OLD.game_instance_id AND t.region_id=OLD.region_id AND t.state='FROZEN') THEN + RAISE EXCEPTION 'Region transfer must complete with owner installation' USING ERRCODE='23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_session_original_new_capacity_execution e + JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=e.transition_id + WHERE b.tenant_id=OLD.tenant_id AND b.game_instance_id=OLD.game_instance_id AND b.region_id=OLD.region_id + AND e.status IN ('INSTALL_DISPATCHED','AUTHORIZED')) AND NOT EXISTS ( + SELECT 1 FROM game_session_region_owner_transfer t WHERE t.tenant_id=OLD.tenant_id + AND t.game_instance_id=OLD.game_instance_id AND t.region_id=OLD.region_id + AND t.region_epoch=OLD.region_epoch AND t.old_owner_id=OLD.owner_instance_id AND t.old_owner_fence=OLD.executor_fence + AND t.old_lease_correlation=OLD.lease_token_correlation AND t.state='COMPLETED' + AND t.new_owner_id=NEW.owner_instance_id AND t.new_owner_fence=NEW.executor_fence + AND t.new_lease_correlation=NEW.lease_token_correlation AND t.verification_complete + AND OLD.owner_service='game-session-service' AND NEW.owner_service='game-session-service') THEN + RAISE EXCEPTION 'Region owner replacement lacks exact transfer custody' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +-- The owner writes completion first. Validate its exact installation at transaction end. +CREATE FUNCTION require_gs_region_transfer_successor() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM game_session_region_runtime_status r + WHERE r.tenant_id=NEW.tenant_id AND r.game_instance_id=NEW.game_instance_id AND r.region_id=NEW.region_id + AND r.region_epoch=NEW.region_epoch AND r.owner_service='game-session-service' + AND r.owner_instance_id=NEW.new_owner_id AND r.executor_fence=NEW.new_owner_fence + AND r.lease_token_correlation=NEW.new_lease_correlation + ) THEN + RAISE EXCEPTION 'Region transfer completion requires its exact installed successor' USING ERRCODE='23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER gs_region_transfer_exact_successor + AFTER UPDATE ON game_session_region_owner_transfer + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW WHEN (OLD.state='FROZEN' AND NEW.state='COMPLETED') + EXECUTE FUNCTION require_gs_region_transfer_successor(); + +-- Existing dispatch and receipt tuples keep their historical recovery rules. +CREATE OR REPLACE FUNCTION preserve_gs_region_fence_dispatch() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE parent game_session_region_owner_transfer%ROWTYPE; +BEGIN + IF TG_OP='INSERT' THEN + IF NEW.fence_dispatch_id IS NOT NULL THEN + RAISE EXCEPTION 'Region fence dispatch requires a retained item' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.fence_dispatch_id,NEW.fence_dispatch_incarnation) + IS NOT DISTINCT FROM ROW(OLD.fence_dispatch_id,OLD.fence_dispatch_incarnation) THEN + RETURN NEW; + END IF; + IF OLD.fence_dispatch_id IS NOT NULL OR OLD.fence_readback IS NOT NULL + OR NEW.fence_dispatch_id IS NULL OR NEW.fence_readback IS NOT NULL + OR current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Region fence dispatch custody is immutable' USING ERRCODE='23514'; + END IF; + SELECT * INTO STRICT parent FROM game_session_region_owner_transfer + WHERE transfer_id=NEW.transfer_id FOR UPDATE; + IF parent.state <> 'FROZEN' + OR parent.incarnation_digest IS NULL + OR parent.incarnation_digest IS DISTINCT FROM NEW.fence_dispatch_incarnation + OR EXISTS (SELECT 1 FROM game_session_region_owner_transfer_item i + WHERE i.execution_digest=NEW.execution_digest AND i.fence_readback IS NOT NULL) THEN + RAISE EXCEPTION 'Region fence dispatch requires an unfenced frozen original with its exact bound incarnation' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +-- [jooq ignore stop] + +-- Runtime-family catalog registration +-- [jooq ignore start] +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1065.0.14' + ) AND ($needle$; + replacement := $replacement$WHERE version='1065.0.14' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.15__require_exact_region_transfer_successor.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.15' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.14'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.15'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.14','V1065.0.14__seal_transfer_dispatch_preparation.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.15'',''V1065.0.15__require_exact_region_transfer_successor.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 78c31dcaad..4ff7be83fc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -1420,20 +1420,30 @@ void resumedFenceReceiptCannotChangeDispatchedStorageIncarnation() throws Except proof.seedUndeliveredDispatch(proof.execution); UUID id = proof.insertRawFrozenTransfer(proof.sql); proof.insertRawTransferItem(proof.sql, id, 0); + String dispatchSql = + "UPDATE game_session_region_owner_transfer_item" + + " SET fence_dispatch_id=?,fence_dispatch_incarnation=? WHERE transfer_id=?"; + UUID dispatch = UUID.randomUUID(); + String observed = "sha256:" + "a".repeat(64); + String changed = "sha256:" + "b".repeat(64); + assertThatThrownBy(() -> proof.sql.execute(dispatchSql, dispatch, observed, id)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("exact bound incarnation"); proof.sql.execute( - "UPDATE game_session_region_owner_transfer_item SET fence_dispatch_id=?,fence_dispatch_incarnation=? WHERE transfer_id=?", - UUID.randomUUID(), - "sha256:" + "a".repeat(64), + "UPDATE game_session_region_owner_transfer SET incarnation_digest=? WHERE transfer_id=?", + observed, id); + assertThatThrownBy(() -> proof.sql.execute(dispatchSql, dispatch, changed, id)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("exact bound incarnation"); + assertThat(proof.sql.execute(dispatchSql, dispatch, observed, id)).isEqualTo(1); String dispatched = proof.itemImage(id); assertThatThrownBy(() -> proof.sql.transaction(configuration -> { var transaction = DSL.using(configuration); - var changed = "sha256:" + "b".repeat(64); var round = UUID.randomUUID(); transaction.execute( - "UPDATE game_session_region_owner_transfer SET incarnation_digest=?,verification_round=? WHERE transfer_id=?", - changed, + "UPDATE game_session_region_owner_transfer SET verification_round=? WHERE transfer_id=?", round, id); transaction.execute( @@ -1460,6 +1470,47 @@ void resumedFenceReceiptCannotChangeDispatchedStorageIncarnation() throws Except } } + @Test + void terminalTransferCompletionRequiresItsExactInstalledSuccessor() throws Exception { + try (var proof = new TransferSqlProof()) { + UUID id = proof.insertRawFrozenTransfer(proof.sql); + String frozen = proof.transferImage(id); + String successor = "terminal-successor"; + String lease = "e".repeat(64); + assertThatThrownBy(() -> + proof.sql.transaction(configuration -> + CanonicalGameplayRegionOwnerTransferRepository.completeTerminalOnly( + DSL.using(configuration), + proof.prior, + successor, + proof.prior.executorFence().longValueExact() + 1, + lease))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "Region transfer completion requires its exact installed successor"); + assertThat(proof.transferImage(id)).isEqualTo(frozen); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + + assertThatThrownBy(() -> + proof.sql.execute( + "UPDATE game_session_region_runtime_status SET owner_service=?" + + " WHERE tenant_id=? AND game_instance_id=? AND region_id=?", + "other-owner-service", + proof.scope.tenantId(), + proof.scope.gameInstanceId(), + proof.scope.regionId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Region transfer must complete with owner installation"); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + + var installed = proof.rawCompleteAndInstall(id, successor, lease); + assertThat(installed.ownerService()).isEqualTo("game-session-service"); + assertThat(installed.ownerInstanceId()).isEqualTo(successor); + assertThat(installed.leaseTokenCorrelation()).isEqualTo(lease); + assertThat(proof.currentOwner()).isEqualTo(installed); + } + } + @Test void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throws Exception { try (var proof = new TransferSqlProof()) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 1bb41103f1..dcebd3f51b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(23); + assertThat(catalog.catalogEpoch()).isEqualTo(24); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -177,6 +177,11 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB && fact.identity() .equals( "game_session_original_new_capacity_execution.gs_capacity_execution_initial_dispatch")) + .anyMatch(fact -> + fact.kind() == FactKind.TRIGGER + && fact.identity() + .equals( + "game_session_region_owner_transfer.gs_region_transfer_exact_successor")) .anyMatch(fact -> fact.kind() == FactKind.SEQUENCE); assertThat( catalog.schemaFacts().stream() @@ -206,7 +211,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1065.0.11", "catalog-installation:1065.0.12", "catalog-installation:1065.0.13", - "catalog-installation:1065.0.14") + "catalog-installation:1065.0.14", + "catalog-installation:1065.0.15") .noneMatch(identity -> identity.contains(":1057:") || identity.contains(":1058:") @@ -230,7 +236,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1065.0.11:") || identity.contains(":1065.0.12:") || identity.contains(":1065.0.13:") - || identity.contains(":1065.0.14:")); + || identity.contains(":1065.0.14:") + || identity.contains(":1065.0.15:")); assertThat( f.dsl .fetchSingle( @@ -767,7 +774,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(23); + assertThat(original.catalog().catalogEpoch()).isEqualTo(24); assertThat(original.catalog().schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_probe_view")) @@ -923,7 +930,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.11", "1065.0.12", "1065.0.13", - "1065.0.14")) { + "1065.0.14", + "1065.0.15")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -974,7 +982,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.11", "1065.0.12", "1065.0.13", - "1065.0.14")) { + "1065.0.14", + "1065.0.15")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " From 96f7efa1b09ac7570bddce982ba7c2f22657c7f1 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 01:22:05 +1300 Subject: [PATCH 37/51] Recheck every completed region transfer fence before serving --- .../game-session-service/runtime-and-data.md | 2 +- ...ameplayRegionOwnerTransferCoordinator.java | 70 +++++++++++-------- ...ransferCapacityCustodyIntegrationTest.java | 64 +++++++++++++++++ 3 files changed, 106 insertions(+), 30 deletions(-) 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 11037783e1..d812d943a9 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -44,7 +44,7 @@ New forward-only transfer dispatches additionally retain a permanent `session:ga After descriptor, principal and connection preflight, SQL durably issues the sealed dispatch's APPLY permission once while the protected before-observation remains fresh. Redis mutation is bounded by the shorter of that observation's expiry and the operation deadline. Only its acknowledged issuer may send APPLY. Every reconstructed or repeated caller is read-only: each current transfer-fence verification requires the retained APPLIED receipt and its exact current target without recreating a missing receipt or target. A missing, malformed or restored PREPARED receipt after issuance remains held, even with an unchanged storage incarnation. Loss of the SQL issuance acknowledgement, or process loss after issuance but before submission, remains an unknown-effect liveness boundary rather than permission to apply again. An interrupted acknowledged application can recover its retained APPLIED receipt and exact physical outcome. Historical UUID-only dispatches are not upgraded into this protocol. These receipts do not prove storage continuity, an original execution outcome, closure, capacity release or runtime activation. -An observed `COMMITTED` hash is not a transfer exemption: the existing positive continuation must verify the complete serving/session/index outcome, persist any missing final SQL receipt and retain immutable `COMMITTED` evidence before that item is handled. Missing positive proof blocks transfer. Existing exact `CLOSED` evidence likewise follows the existing independent closure-retention path. Neither terminal record is overwritten. The acquire/install/revalidate path installs the successor and immutable transfer completion in one transaction. A nonempty transfer requires its current fencing capability and complete locked inventory check. The SQL completion guard requires each captured item’s complete receipt for the current verification round, including items whose execution became terminal after capture. A terminal-only transfer requires an empty retained inventory and proof that no unresolved predecessor execution remains. The original attempts remain fenced and non-admitting. A completed transfer supports a separately phase-bound signed currentness read only while its immutable successor still matches the actual current region source; completed observations cannot enroll items, change receipts or authorize another installation. If confirmation fails after SQL commits, the same process can use its retained live grant to recheck the exact completed successor and its retained physical fences, or the exact terminal-only completion and empty inventory, before completing installation. If an empty advance does not retain a transfer identifier, its same-process recovery checks the durable owner tuple against the original private live grant without repeating owner installation or creating a transfer receipt. A lost or expired grant leaves this continuation held. A process using the same stable instance ID may start a separate normal handoff only when fresh-token atomic acquisition establishes that the scoped lease is absent. That handoff revalidates the current source, protected incarnation and timeline, and completes the normal census, fencing and guarded installation under its new grant. The earlier completion remains immutable. A fully retained committed original can supply the exact topology for a first handoff. Game Session verifies its retained capacity outcome and current predecessor, then requires the existing installed timeline and a fresh successor grant. The committed original supplies no provisional admission authority. +An observed `COMMITTED` hash is not a transfer exemption: the existing positive continuation must verify the complete serving/session/index outcome, persist any missing final SQL receipt and retain immutable `COMMITTED` evidence before that item is handled. Missing positive proof blocks transfer. Existing exact `CLOSED` evidence likewise follows the existing independent closure-retention path. Neither terminal record is overwritten. The acquire/install/revalidate path installs the successor and immutable transfer completion in one transaction. A nonempty transfer requires its current fencing capability and complete locked inventory check. The SQL completion guard requires each captured item’s complete receipt for the current verification round, including items whose execution became terminal after capture. A terminal-only transfer requires an empty retained inventory and proof that no unresolved predecessor execution remains. The original attempts remain fenced and non-admitting. A completed transfer supports a separately phase-bound signed currentness read only while its immutable successor still matches the actual current region source; completed observations cannot enroll items, change receipts or authorize another installation. Before returning a completed nonempty installation to serving, Game Session rechecks the exact current successor, signed storage incarnation, and every retained physical fence under the original operation deadline. If confirmation fails after SQL commits, the same process can use its retained live grant to recheck the exact completed successor and its retained physical fences, or the exact terminal-only completion and empty inventory, before completing installation. If an empty advance does not retain a transfer identifier, its same-process recovery checks the durable owner tuple against the original private live grant without repeating owner installation or creating a transfer receipt. A lost or expired grant leaves this continuation held. A process using the same stable instance ID may start a separate normal handoff only when fresh-token atomic acquisition establishes that the scoped lease is absent. That handoff revalidates the current source, protected incarnation and timeline, and completes the normal census, fencing and guarded installation under its new grant. The earlier completion remains immutable. A fully retained committed original can supply the exact topology for a first handoff. Game Session verifies its retained capacity outcome and current predecessor, then requires the existing installed timeline and a fresh successor grant. The committed original supplies no provisional admission authority. An exact retained first-NEW Account-aborted original remains part of the transfer inventory, whether abort preceded capture or completed while the transfer was frozen. Its topology lookup verifies the retained definitive abort and existing immutable mapping without restoring provisional admission authority. First negative closure still requires the complete physical candidate/index proof; already-retained CLOSED replay uses its exact permanent tombstone. Unknown history remains fenced and indeterminate, never discarded because Account or SQL records an abort. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java index 891ded1326..854190c852 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java @@ -184,15 +184,15 @@ CanonicalGameplayRegionRuntimeStatus install( ownerInstanceId, clock.instant(), proof); - // Completion grants no historical-fence exemption. The source now independently checks - // the immutable completed successor against the actual current region owner. + // Completion grants no historical-fence exemption. Recheck the exact committed + // successor and every retained marker before returning a serving capability. var completed = - observations.observeForRegionOwnerTransfer( - transferId, first.getFirst().ordinal(), budget); - if (!after.incarnationDigest().equals(completed.incarnationDigest())) throw held(); - repository.requireRetainedPhysical( - first.getFirst(), - owner.readTransferFence(first.getFirst(), budget.absoluteDeadlineMillis())); + repository.completedSuccessor(transferId, ownerInstanceId, leaseCorrelation); + if (!installed.equals(completed.status()) + || !after.incarnationDigest().equals(completed.incarnationDigest())) throw held(); + var completedFirst = repository.completedPage(transferId, -1); + if (completedFirst.isEmpty()) throw held(); + requireCompletedInventory(transferId, completed, completedFirst, budget); return installed; }); } @@ -209,31 +209,43 @@ CanonicalGameplayRegionRuntimeStatus recoverCompleted( repository.requireTerminalOnlyCompletion(transferId, completed); return completed.status(); } - var first = firstPage.getFirst(); - var before = observe(first, budget); - if (!before.incarnationDigest().equals(completed.incarnationDigest())) throw held(); - var owner = capacity.forTransferBudget(budget); - owner.withTransferReadback(reader -> { - var page = firstPage; - while (!page.isEmpty()) { - for (var item : page) { - budget.check(); - repository.requireRetainedPhysical( - item, reader.readTransferFence(item, budget.absoluteDeadlineMillis())); - } - page = repository.completedPage(transferId, page.getLast().ordinal()); - } - }); - var after = observe(first, budget); - if (!after.incarnationDigest().equals(completed.incarnationDigest()) - || !completed.equals( - repository.completedSuccessor(transferId, ownerInstance, correlation))) { - throw held(); - } + requireCompletedInventory(transferId, completed, firstPage, budget); return completed.status(); }); } + /** Rechecks a nonempty completed transfer without mutation or a second operation budget. */ + private void requireCompletedInventory( + UUID transferId, + CanonicalGameplayRegionOwnerTransferRepository.CompletedTransfer completed, + List firstPage, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + var first = firstPage.getFirst(); + var before = observe(first, budget); + if (!before.incarnationDigest().equals(completed.incarnationDigest())) throw held(); + var owner = capacity.forTransferBudget(budget); + owner.withTransferReadback(reader -> { + var page = firstPage; + while (!page.isEmpty()) { + for (var item : page) { + budget.check(); + repository.requireRetainedPhysical( + item, reader.readTransferFence(item, budget.absoluteDeadlineMillis())); + } + page = repository.completedPage(transferId, page.getLast().ordinal()); + } + }); + var after = observe(first, budget); + if (!after.incarnationDigest().equals(completed.incarnationDigest()) + || !completed.equals( + repository.completedSuccessor( + transferId, + completed.status().ownerInstanceId(), + completed.status().leaseTokenCorrelation()))) { + throw held(); + } + } + private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observe( CanonicalGameplayRegionOwnerTransferRepository.Item item, CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 4ff7be83fc..73d1f6af2d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -10,6 +10,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; @@ -845,6 +846,69 @@ void finalQualificationRechecksLostFenceBeyondTheFirstPageWithoutRecreatingIt() } } + @Test + void installationDoesNotReturnServingCapabilityWhenAnyCompletedMarkerIsLost() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + var secondExecution = proof.newIndependentControlledOriginExecution(); + proof.seedUndeliveredDispatch(secondExecution); + UUID id = proof.begin(); + assertThat(proof.captureAndFence(id)).hasSize(2); + proof.verifyPage(id); + boolean verificationComplete = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(verificationComplete).isTrue(); + + var lostAfterInstall = new AtomicBoolean(); + var listener = + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.stripLeading() + .toLowerCase(Locale.ROOT) + .startsWith("update game_session_region_runtime_status") + && lostAfterInstall.compareAndSet(false, true)) { + // Model a retained marker disappearing after SQL installs the successor but + // before the coordinator can return its serving capability. + proof.losePhysicalExecution(secondExecution); + } + } + }; + DSLContext installingSql = DSL.using(proof.sql.configuration().deriveAppending(listener)); + var transfers = proof.transfers(installingSql); + var observations = + new CanonicalGameplayControlledRegionTransferObservationFixture(proof.clock) + .receiver(transfers, proof.tags); + var coordinator = + new CanonicalGameplayRegionOwnerTransferCoordinator( + installingSql, proof.clock, transfers, proof.capacity(installingSql), observations); + + assertThatThrownBy(() -> + coordinator.install( + id, + proof.scope, + proof.prior, + "e".repeat(64), + "game-session-service", + "sql-proof-successor", + transferDeadline())) + .isInstanceOf(IllegalStateException.class); + + assertThat(lostAfterInstall).isTrue(); + assertThat(proof.currentOwner().ownerInstanceId()).isEqualTo("sql-proof-successor"); + assertThat(proof.transfers.readCurrent(id, 0).controlState()).isEqualTo("COMPLETED"); + assertThat(proof.physicalExecutionExists(proof.execution)).isTrue(); + assertThat(proof.physicalExecutionExists(secondExecution)).isFalse(); + assertThatThrownBy(() -> + coordinator.recoverCompleted( + id, "sql-proof-successor", "e".repeat(64), transferDeadline())) + .isInstanceOf(IllegalStateException.class); + } + } + @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) void missingAppliedReceiptCannotQualifyCurrentTransfer(boolean installedBeforeLoss) From 47816742937bf3a92ed470353b91598164819639 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 01:51:32 +1300 Subject: [PATCH 38/51] Retain exact timeline no-write release evidence --- .../game-session-service/operations.md | 2 +- .../game-session-service/runtime-and-data.md | 2 +- ...anonicalGameplayRegionLeaseRedisOwner.java | 4 + ...GameplayRegionRuntimeStatusRepository.java | 59 ++++++----- ...xact_initial_timeline_no_write_release.sql | 100 ++++++++++++++++++ ...meplayRegionLeaseOwnerIntegrationTest.java | 57 ++++++---- ...eFamilyCatalogPostgresIntegrationTest.java | 21 ++-- 7 files changed, 192 insertions(+), 53 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.16__retain_exact_initial_timeline_no_write_release.sql diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index 85f6a33998..592693fbb7 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -109,7 +109,7 @@ Keep the realm held and preserve the source and protection evidence for owner re ### Initial region timeline recovery boundary -For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata cannot distinguish never-executed initialization from metadata loss. Descriptor, source, connection, principal, `SCRIPT LOAD`, or current-binding/World/incarnation revalidation refusal before the SQL claim does not change the preparation phase or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains valid, a corrected ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held unless its live prepared owner proves `EVALSHA` was never invoked or retains the exact definitive v2 `INITIALIZE` no-write result. Only that local never-dispatched fact or completed `-3` response supplies a single-use capability for separately bounded SQL cleanup of the matching claim back to `PREPARED`; stale permits/proofs cannot release a later claim. The composed owner reserves one of 64 bounded local recovery slots before claiming creation permission, retaining the exact no-write capability if cleanup admission or SQL fails. A later same-operation attempt retries that capability before requesting a new claim; capacity exhaustion refuses before claim and never evicts retained evidence. These slots are process-local, not restart recovery. A successful rollback before any cleanup commit attempt preserves the exact proof for retry; an ambiguous commit never restores it, even if a later rollback returns successfully. This does not derive recovery authority from Redis absence, logs, elapsed time, or operator phase edits. After those checks pass, the owner claims the permission and immediately attempts the sole `EVALSHA`; a process stop between claim and send or an ambiguous send/result leaves the scope held, with no automatic same-scope retry or recovery. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. For that unknown-effect case, no same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). +For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata cannot distinguish never-executed initialization from metadata loss. Descriptor, source, connection, principal, `SCRIPT LOAD`, or current-binding/World/incarnation revalidation refusal before the SQL claim does not change the preparation phase or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains valid, a corrected ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held unless its live prepared owner proves `EVALSHA` was never invoked or retains the exact definitive v2 `INITIALIZE` no-write result. Only that local never-dispatched fact or completed `-3` response supplies a single-use capability for separately bounded SQL cleanup of the matching claim back to `PREPARED`; stale permits/proofs cannot release a later claim. The composed owner reserves one of 64 bounded local recovery slots before claiming creation permission, retaining the exact no-write capability if cleanup admission or SQL fails. A later same-operation attempt retries that capability before requesting a new claim; capacity exhaustion refuses before claim and never evicts retained evidence. These slots are process-local, not restart recovery. A successful rollback before any cleanup commit attempt preserves the exact proof for retry. After an ambiguous commit, the live owner may use only read-only confirmation of the [original durable release](./runtime-and-data.md#tick-coordination-and-lease-ownership) to clear the local slot. A later rollback cannot restore the consumed proof. This does not derive recovery authority from Redis absence, logs, elapsed time, or operator phase edits. After those checks pass, the owner claims the permission and immediately attempts the sole `EVALSHA`; a process stop between claim and send or an ambiguous send/result leaves the scope held, with no automatic same-scope retry or recovery. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. For that unknown-effect case, no same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). ## Scaling and Region Rebalancing 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 d812d943a9..416794cac0 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -331,7 +331,7 @@ Tick coordination is region-scoped, not session-scoped. Tick queues, locks, time Session shutdown therefore cleans up session keys but does not implicitly delete region-level tick coordination keys. -Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. Ordinary installation retains the registered v1 timeline script. Transfer-enabled composed installation uses a separate v2 descriptor carrying the same frozen absolute handoff deadline through the absence probe, prepared setup, initialization, and verification; Redis `TIME` refuses an expired v2 `PROBE` before the SQL creation permission is consumed, refuses an expired v2 `INITIALIZE` before either metadata or lease is written, and caps a new lease at the remaining deadline. Expiry can still occur after the SQL claim. A live prepared session that proves it never invoked `EVALSHA`, or a completed v2 `INITIALIZE` result of `-3`, supplies an owner-local, single-use no-write proof: a separately bounded SQL cleanup may return only that exact `INITIALIZING` preparation to `PREPARED`, with unchanged operation and source identity and no installed runtime row. Each creation permit can dispatch only once, and the proof can release only once, so neither can affect a later claim. For explicit handoff, the return callback records that proof without waiting for a new cleanup budget. The next attempt can consume it through the existing bounded cleanup before requesting a new creation claim. A fresh attempt must repeat the normal source, incarnation, descriptor, and Redis preflight checks. A confirmed rollback before any cleanup commit attempt preserves that exact proof for retry; a failed or ambiguous commit consumes it and retains fail-closed custody. Timeout, cancellation, lost response after dispatch invocation, and absent Redis keys do not establish no-write proof and never authorize release. Installation World placement and lifecycle revalidation share the same absolute operation deadline. Before the SQL claim, the owner validates the registered script descriptor and digest-checked bytes, connects, verifies `ACL WHOAMI`, and loads the script on the same private connection it retains for the sole `EVALSHA`. While that prepared session remains open, it revalidates the provisional binding, current World assignment and lifecycle, stable incarnation, and retained preparation. A descriptor, source, connection, principal, `SCRIPT LOAD`, or current-context refusal closes the session without changing the preparation or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains absent, a later ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held unless its still-live owner retains the exact definitive no-write proof described above. Only after those checks succeed does the owner claim the SQL permission and immediately invoke the prepared session once. If the process stops between claim and send, or the send/result is ambiguous, the preparation remains `INITIALIZING`; a later attempt cannot distinguish never-executed initialization from lost metadata. It therefore fails closed without obtaining a fresh creation permission, acquiring a lease or rewriting the same-epoch baseline. This unknown-effect case remains a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for that case. SQL phase edits and raw Redis key surgery are not recovery authority. Operator handling and authorized scope retirement belong to the [initial timeline recovery boundary](./operations.md#initial-region-timeline-recovery-boundary). The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps), with focused first-NEW proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). +Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. Ordinary installation retains the registered v1 timeline script. Transfer-enabled composed installation uses a separate v2 descriptor carrying the same frozen absolute handoff deadline through the absence probe, prepared setup, initialization, and verification; Redis `TIME` refuses an expired v2 `PROBE` before the SQL creation permission is consumed, refuses an expired v2 `INITIALIZE` before either metadata or lease is written, and caps a new lease at the remaining deadline. Expiry can still occur after the SQL claim. A live prepared session that proves it never invoked `EVALSHA`, or a completed v2 `INITIALIZE` result of `-3`, supplies an owner-local, single-use no-write proof: a separately bounded SQL cleanup may return only that exact `INITIALIZING` preparation to `PREPARED`, with unchanged operation and source identity and no installed runtime row. Each creation permit carries the next positive ordinal for its exact preparation and can dispatch only once. The same SQL transaction that releases an exact claim advances the preparation’s highest consecutively released ordinal. A later claim can be issued only after the previous one was positively released. This fixed-size release history lets the live owner confirm an already-consumed proof by its original operation, source digest and ordinal even after a later claim or owner installation. This confirmation only reads retained evidence. Old preparations receive no release credit, and an unknown or exhausted ordinal cannot grant another creation permit. For explicit handoff, the return callback records that proof without waiting for a new cleanup budget. The next attempt can consume it through the existing bounded cleanup before requesting a new creation claim. A fresh attempt must repeat the normal source, incarnation, descriptor, and Redis preflight checks. A confirmed rollback before any cleanup commit attempt preserves that exact proof for retry. After a failed or ambiguous commit the proof remains consumed, and cleanup stays held until an exact durable release can be confirmed. Timeout, cancellation, lost response after dispatch invocation, and absent Redis keys do not establish no-write proof and never authorize release. Installation World placement and lifecycle revalidation share the same absolute operation deadline. Before the SQL claim, the owner validates the registered script descriptor and digest-checked bytes, connects, verifies `ACL WHOAMI`, and loads the script on the same private connection it retains for the sole `EVALSHA`. While that prepared session remains open, it revalidates the provisional binding, current World assignment and lifecycle, stable incarnation, and retained preparation. A descriptor, source, connection, principal, `SCRIPT LOAD`, or current-context refusal closes the session without changing the preparation or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains absent, a later ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held unless its still-live owner retains the exact definitive no-write proof described above. Only after those checks succeed does the owner claim the SQL permission and immediately invoke the prepared session once. If the process stops between claim and send, or the send/result is ambiguous, the preparation remains `INITIALIZING`; a later attempt cannot distinguish never-executed initialization from lost metadata. It therefore fails closed without obtaining a fresh creation permission, acquiring a lease or rewriting the same-epoch baseline. This unknown-effect case remains a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for that case. SQL phase edits and raw Redis key surgery are not recovery authority. Operator handling and authorized scope retirement belong to the [initial timeline recovery boundary](./operations.md#initial-region-timeline-recovery-boundary). The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps), with focused first-NEW proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). ## Reconnection and Disconnect Handling diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index 4267c1e714..2e674761cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -512,6 +512,10 @@ private InitializationNoWriteProof( this.permit = permit; } + long claimOrdinal() { + return permit.claimOrdinal(); + } + void restoreAfterConfirmedRollback() { consumed.set(false); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index 7e17fda075..105ebd21f3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -380,16 +380,23 @@ public void release(java.sql.Connection connection) { // Lock waits and source checks cannot consume the installation deadline and still // grant irreversible permission to create Redis meta. if (installationBudget != null) installationBudget.check(); + long previousClaim = row.get("initialization_claim_ordinal", Long.class); + if (previousClaim != row.get("no_write_released_through", Long.class) + || previousClaim == Long.MAX_VALUE) throw unavailable(); + long claimOrdinal = previousClaim + 1; int updated = transaction.execute( "UPDATE " + PREPARATION_TABLE - + " SET phase = 'INITIALIZING', updated_at = ?" + + " SET phase = 'INITIALIZING', initialization_claim_ordinal = ?, updated_at = ?" + " WHERE initialization_operation_id = ? AND phase = 'PREPARED'", + claimOrdinal, java.sql.Timestamp.from(now), current.operationId); if (updated != 1) throw unavailable(); - var permit = new InitialInitializationPermit(current.operationId, current.sourceDigest()); + var permit = + new InitialInitializationPermit( + current.operationId, current.sourceDigest(), claimOrdinal); issued.set(permit); return Optional.of(permit); }); @@ -419,31 +426,21 @@ void releaseInitialTimelineNoWrite( Objects.requireNonNull(now, "now"); if (proof == null) throw unavailable(); if (!proof.consumeFor(preparation)) { - // A commit may have succeeded before its completion signal failed. Reconcile only an - // already-consumed exact capability against durable PREPARED state; never restore or - // re-use it to mutate a later INITIALIZING claim. + // A contiguous release history proves this exact consumed claim even after later claims. + // An acknowledgement check does not restore permission to change the preparation. if (!proof.consumedFor(preparation)) throw unavailable(); dsl.transaction(configuration -> { DSLContext transaction = DSL.using(configuration); lockRegionScope(transaction, preparation.tenantRegionTag); - Record row = - transaction.fetchOne( - "SELECT * FROM " + if (transaction.fetchOne( + "SELECT 1 FROM " + PREPARATION_TABLE - + " WHERE initialization_operation_id = ? FOR UPDATE", - preparation.operationId); - if (row == null) throw unavailable(); - TimelinePreparation current = toTimelinePreparation(row); - if (!samePreparation(preparation, current) - || current.phase != TimelinePreparationPhase.PREPARED - || transaction.fetchExists( - DSL.selectOne() - .from(DSL.table(TABLE)) - .where(DSL.field("tenant_id").eq(preparation.source.tenantId())) - .and(DSL.field("game_instance_id").eq(preparation.source.gameInstanceId())) - .and(DSL.field("region_id").eq(preparation.source.regionId())))) { - throw unavailable(); - } + + " WHERE initialization_operation_id = ? AND preparation_digest = ?" + + " AND no_write_released_through >= ?", + preparation.operationId, + preparation.sourceDigest(), + proof.claimOrdinal()) + == null) throw unavailable(); }); return; } @@ -500,6 +497,7 @@ public void rollback(org.jooq.TransactionContext context) { TimelinePreparation current = toTimelinePreparation(row); if (!samePreparation(preparation, current) || current.phase != TimelinePreparationPhase.INITIALIZING + || proof.claimOrdinal() != row.get("initialization_claim_ordinal", Long.class) || transaction.fetchExists( DSL.selectOne() .from(DSL.table(TABLE)) @@ -511,10 +509,13 @@ public void rollback(org.jooq.TransactionContext context) { transaction.execute( "UPDATE " + PREPARATION_TABLE - + " SET phase = 'PREPARED', updated_at = ?" - + " WHERE initialization_operation_id = ? AND phase = 'INITIALIZING'", + + " SET phase = 'PREPARED', no_write_released_through = ?, updated_at = ?" + + " WHERE initialization_operation_id = ? AND phase = 'INITIALIZING'" + + " AND initialization_claim_ordinal = ?", + proof.claimOrdinal(), java.sql.Timestamp.from(now), - preparation.operationId); + preparation.operationId, + proof.claimOrdinal()); if (changed != 1) throw unavailable(); }); } @@ -1443,15 +1444,17 @@ String absenceProofDigest() { static final class InitialInitializationPermit { private final UUID operationId; private final String sourceDigest; + private final long claimOrdinal; private final AtomicBoolean dispatched = new AtomicBoolean(); boolean consumeDispatch() { return dispatched.compareAndSet(false, true); } - private InitialInitializationPermit(UUID operationId, String sourceDigest) { + private InitialInitializationPermit(UUID operationId, String sourceDigest, long claimOrdinal) { this.operationId = Objects.requireNonNull(operationId, "operationId"); this.sourceDigest = Objects.requireNonNull(sourceDigest, "sourceDigest"); + this.claimOrdinal = claimOrdinal; } UUID operationId() { @@ -1461,6 +1464,10 @@ UUID operationId() { String sourceDigest() { return sourceDigest; } + + long claimOrdinal() { + return claimOrdinal; + } } enum TimelinePreparationPhase { diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.16__retain_exact_initial_timeline_no_write_release.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.16__retain_exact_initial_timeline_no_write_release.sql new file mode 100644 index 0000000000..379436428e --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.16__retain_exact_initial_timeline_no_write_release.sql @@ -0,0 +1,100 @@ +-- Zero ordinals preserve existing preparations without crediting historical claims. +ALTER TABLE game_session_region_timeline_preparation + ADD COLUMN initialization_claim_ordinal BIGINT NOT NULL DEFAULT 0, + ADD COLUMN no_write_released_through BIGINT NOT NULL DEFAULT 0, + ADD CONSTRAINT gs_timeline_no_write_contiguous CHECK ( + no_write_released_through >= 0 + AND initialization_claim_ordinal >= no_write_released_through + AND initialization_claim_ordinal - no_write_released_through <= 1); + +-- [jooq ignore start] +CREATE FUNCTION preserve_gs_timeline_no_write_release() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='TRUNCATE' THEN + RAISE EXCEPTION 'Initial timeline claim history is retained' USING ERRCODE='23514'; + ELSIF TG_OP='DELETE' THEN + IF OLD.initialization_claim_ordinal > 0 THEN + RAISE EXCEPTION 'Initial timeline claim history is retained' USING ERRCODE='23514'; + END IF; + RETURN OLD; + ELSIF TG_OP='INSERT' THEN + IF NEW.initialization_claim_ordinal <> 0 OR NEW.no_write_released_through <> 0 + OR NEW.phase='INITIALIZING' THEN + RAISE EXCEPTION 'Initial timeline claim requires an existing preparation' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + + IF (OLD.initialization_claim_ordinal > 0 OR NEW.initialization_claim_ordinal > 0) + AND ROW(NEW.initialization_operation_id,NEW.preparation_digest) + IS DISTINCT FROM ROW(OLD.initialization_operation_id,OLD.preparation_digest) THEN + RAISE EXCEPTION 'Initial timeline claim source is immutable' USING ERRCODE='23514'; + END IF; + IF OLD.phase='PREPARED' AND NEW.phase='INITIALIZING' THEN + IF OLD.initialization_claim_ordinal <> OLD.no_write_released_through + OR NEW.initialization_claim_ordinal <= 0 + OR NEW.initialization_claim_ordinal - 1 <> OLD.initialization_claim_ordinal + OR NEW.no_write_released_through <> OLD.no_write_released_through THEN + RAISE EXCEPTION 'Initial timeline claim must follow the positively released prefix' USING ERRCODE='23514'; + END IF; + ELSIF OLD.phase='INITIALIZING' AND NEW.phase='PREPARED' THEN + IF OLD.initialization_claim_ordinal <= OLD.no_write_released_through + OR NEW.initialization_claim_ordinal <> OLD.initialization_claim_ordinal + OR NEW.no_write_released_through <> OLD.initialization_claim_ordinal THEN + RAISE EXCEPTION 'Initial timeline release must close its exact active claim' USING ERRCODE='23514'; + END IF; + ELSIF ROW(NEW.initialization_claim_ordinal,NEW.no_write_released_through) + IS DISTINCT FROM ROW(OLD.initialization_claim_ordinal,OLD.no_write_released_through) THEN + RAISE EXCEPTION 'Initial timeline claim history requires a guarded phase transition' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER gs_timeline_no_write_release_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_session_region_timeline_preparation + FOR EACH ROW EXECUTE FUNCTION preserve_gs_timeline_no_write_release(); +CREATE TRIGGER gs_timeline_no_write_release_no_truncate BEFORE TRUNCATE + ON game_session_region_timeline_preparation + FOR EACH STATEMENT EXECUTE FUNCTION preserve_gs_timeline_no_write_release(); +-- [jooq ignore stop] + +-- Runtime-family catalog registration +-- [jooq ignore start] +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1065.0.15' + ) AND ($needle$; + replacement := $replacement$WHERE version='1065.0.15' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.16__retain_exact_initial_timeline_no_write_release.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.16' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.15'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.16'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.15','V1065.0.15__require_exact_region_transfer_successor.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.16'',''V1065.0.16__retain_exact_initial_timeline_no_write_release.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 62f6870595..de6ff702c1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -2296,7 +2296,7 @@ void confirmedSqlRollbackPreservesExactNoWriteProofForRetry() throws Exception { } @Test - void ambiguousReleaseCommitNeverRestoresProofEvenAfterRollbackReturns() throws Exception { + void lostReleaseAcknowledgementReconcilesExactClaimAfterTheNextClaim() throws Exception { assertKnownNoWriteRecovery(3); } @@ -2765,6 +2765,16 @@ public void executeStart( .isInstanceOf(RuntimeException.class); assertThat(concurrentRelease.get()).isNotNull(); concurrentRelease.get().orTimeout(10, TimeUnit.SECONDS).join(); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT no_write_released_through" + + " FROM game_session_region_timeline_preparation" + + " WHERE initialization_operation_id = ?", + preparation.operationId()) + .get(0, Long.class)) + .isZero(); assertThat( repository.findTimelinePreparation(source).orElseThrow().phase()) .isEqualTo( @@ -2816,18 +2826,6 @@ public void rollback(org.jooq.TransactionContext context) { } } assertThat(proof.get()).isNotNull(); - if (mode == 3) { - // The commit reached PREPARED but its caller saw failure. The owner retains the - // consumed capability and reconciles durable state without restoring mutation authority. - assertThat(proof.get().consumedFor(preparation)).isTrue(); - recoveryOwner.releaseNoWriteRecovery(preparation.operationId(), recoverySlot); - var retry = recoveryOwner.reserveNoWriteRecovery(preparation.operationId()); - assertThat(retry).isSameAs(recoverySlot); - recoveryOwner.recoverNoWrite(preparation, retry); - assertThat(retry.proof).isNull(); - assertThat(proof.get().consumedFor(preparation)).isTrue(); - recoveryOwner.releaseNoWriteRecovery(preparation.operationId(), retry); - } if (mode == 4) { assertThat(repository.findTimelinePreparation(source).orElseThrow().phase()) .isEqualTo( @@ -2856,12 +2854,33 @@ public void rollback(org.jooq.TransactionContext context) { assertThat(proof.get().consumedFor(preparation)).isTrue(); } assertPreparedTimelineUnchanged(testSchema.dsl(), repository, redis, source, preparation); - var retryPermit = repository.beginInitialTimeline(preparation, NOW).orElseThrow(); - // A stale proof cannot release the next claim, and a previously dispatched creation permit - // cannot be replayed through a different Redis session after PREPARED is restored. - assertThatThrownBy( - () -> repository.releaseInitialTimelineNoWrite(preparation, proof.get(), NOW)) - .isInstanceOf(IllegalStateException.class); + var laterOwner = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var retryPermit = laterOwner.beginInitialTimeline(preparation, NOW).orElseThrow(); + assertThat(retryPermit.claimOrdinal()).isEqualTo(permit.claimOrdinal() + 1); + String claimImage = + "SELECT to_jsonb(p)::text FROM game_session_region_timeline_preparation p" + + " WHERE initialization_operation_id = ?"; + String beforeReplay = + testSchema.dsl().fetchSingle(claimImage, preparation.operationId()).get(0, String.class); + assertThat(proof.get().consumedFor(preparation)).isTrue(); + if (mode == 3) { + // Reconcile the original owner's lost acknowledgement after the later owner claims. + recoveryOwner.releaseNoWriteRecovery(preparation.operationId(), recoverySlot); + var retry = recoveryOwner.reserveNoWriteRecovery(preparation.operationId()); + assertThat(retry).isSameAs(recoverySlot); + recoveryOwner.recoverNoWrite(preparation, retry); + assertThat(retry.proof).isNull(); + recoveryOwner.releaseNoWriteRecovery(preparation.operationId(), retry); + } else { + repository.releaseInitialTimelineNoWrite(preparation, proof.get(), NOW); + } + assertThat(proof.get().consumedFor(preparation)).isTrue(); + assertThat( + testSchema + .dsl() + .fetchSingle(claimImage, preparation.operationId()) + .get(0, String.class)) + .isEqualTo(beforeReplay); assertThat(repository.findTimelinePreparation(source).orElseThrow().phase()) .isEqualTo( CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INITIALIZING); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index dcebd3f51b..762bddf004 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(24); + assertThat(catalog.catalogEpoch()).isEqualTo(25); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -182,6 +182,11 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB && fact.identity() .equals( "game_session_region_owner_transfer.gs_region_transfer_exact_successor")) + .anyMatch(fact -> + fact.kind() == FactKind.TRIGGER + && fact.identity() + .equals( + "game_session_region_timeline_preparation.gs_timeline_no_write_release_guard")) .anyMatch(fact -> fact.kind() == FactKind.SEQUENCE); assertThat( catalog.schemaFacts().stream() @@ -212,7 +217,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1065.0.12", "catalog-installation:1065.0.13", "catalog-installation:1065.0.14", - "catalog-installation:1065.0.15") + "catalog-installation:1065.0.15", + "catalog-installation:1065.0.16") .noneMatch(identity -> identity.contains(":1057:") || identity.contains(":1058:") @@ -237,7 +243,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1065.0.12:") || identity.contains(":1065.0.13:") || identity.contains(":1065.0.14:") - || identity.contains(":1065.0.15:")); + || identity.contains(":1065.0.15:") + || identity.contains(":1065.0.16:")); assertThat( f.dsl .fetchSingle( @@ -774,7 +781,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(24); + assertThat(original.catalog().catalogEpoch()).isEqualTo(25); assertThat(original.catalog().schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_probe_view")) @@ -931,7 +938,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.12", "1065.0.13", "1065.0.14", - "1065.0.15")) { + "1065.0.15", + "1065.0.16")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -983,7 +991,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.12", "1065.0.13", "1065.0.14", - "1065.0.15")) { + "1065.0.15", + "1065.0.16")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " From 9f0fe77a2bb88f025f8270ef6a9e80df620cba30 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 02:40:08 +1300 Subject: [PATCH 39/51] Prove repeat region handoff retains exact fence custody --- ...iginalNewRegionHandoffIntegrationTest.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java index 20c697c02b..5f616f035f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java @@ -806,6 +806,14 @@ void secondFrozenHandoffResumesOlderOriginalAbortedBeforeCapture() throws Except firstTransferId) .get(0, String.class)) .isEqualTo("COMPLETED"); + String retainedFenceSql = + "SELECT fence_dispatch_id,fence_readback,incarnation_digest" + + " FROM game_session_region_owner_transfer_item" + + " WHERE transfer_id=? AND execution_digest=?"; + var firstFence = + fixture.dsl().fetchSingle(retainedFenceSql, firstTransferId, controlledCapacity.digest()); + assertThat(firstFence.get("fence_dispatch_id", UUID.class)).isNotNull(); + assertThat(firstFence.get("fence_readback", byte[].class)).isNotEmpty(); UUID secondTransferId = repository.within( @@ -845,6 +853,24 @@ void secondFrozenHandoffResumesOlderOriginalAbortedBeforeCapture() throws Except .containsExactly(originalCandidate.canonicalBytes()); byte[] candidateBytes = admin.get(ascii(installation.sessionKey())); + var changedStorage = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags, "replacement-storage"); + var changedTransfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), changedStorage); + assertThatThrownBy(() -> + changedTransfer.resume( + frozenOriginal, firstSuccessor.source, firstSuccessor.status, deadline())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Normal region owner transfer is held") + .hasStackTraceContaining("CanonicalGameplayRegionOwnerTransferRepository.fenceDispatch"); + var heldFence = + fixture.dsl().fetchSingle(retainedFenceSql, secondTransferId, controlledCapacity.digest()); + assertThat(heldFence.get("fence_dispatch_id", UUID.class)).isNull(); + assertThat(heldFence.get("fence_readback", byte[].class)).isNull(); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(candidateBytes); + var thirdIdentity = new net.firedevops.firemud.common.runtime.RuntimeIdentity( "game-session-service", @@ -874,6 +900,18 @@ void secondFrozenHandoffResumesOlderOriginalAbortedBeforeCapture() throws Except var secondSuccessor = thirdOwner.installForTransition( null, firstSuccessor.transitionId, firstSuccessor.worldRequest, transfer, deadline()); + var secondFence = + fixture.dsl().fetchSingle(retainedFenceSql, secondTransferId, controlledCapacity.digest()); + assertThat(secondFence.get("fence_dispatch_id", UUID.class)).isNull(); + assertThat(secondFence.get("fence_readback", byte[].class)) + .containsExactly(firstFence.get("fence_readback", byte[].class)); + assertThat(secondFence.get("incarnation_digest", String.class)) + .isEqualTo(firstFence.get("incarnation_digest", String.class)); + assertThat( + fixture + .dsl() + .fetchSingle(retainedFenceSql, firstTransferId, controlledCapacity.digest())) + .isEqualTo(firstFence); assertThat(secondSuccessor.status.ownerInstanceId()).isEqualTo("third-owner-handoff"); assertThat(secondSuccessor.status.executorFence()) .isGreaterThan(firstSuccessor.status.executorFence()); From 08ab513c20c14da751f5802f05e2336356537dab Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 03:33:16 +1300 Subject: [PATCH 40/51] Retain the exact Account capacity send boundary --- .../account-service/api-contracts.md | 4 +- .../game-session-service/runtime-and-data.md | 2 +- .../system-architecture-redis-ops-access.md | 2 + .../player-access-and-session.md | 2 + protos/account/v1/account_service.proto | 3 + .../AccountTenantCapacityRepository.java | 48 +++- .../AccountTenantCapacityWorkloadGuard.java | 15 + .../service/AccountTenantCapacityOwner.java | 55 +++- .../AccountTenantCapacityGrpcService.java | 65 +++++ ...alAdmissionCompositionIntegrationTest.java | 53 +++- ...ccountTenantCapacityWorkloadGuardTest.java | 25 +- .../AccountTenantCapacityGrpcServiceTest.java | 229 +++++++++++++++- .../client/AccountTenantCapacityClient.java | 33 +++ ...nonicalGameplayCapacityEvidenceBudget.java | 83 +++++- ...playOriginalNewCapacityExecutionOwner.java | 49 ++++ ...yOriginalNewFinalAdmissionCoordinator.java | 45 ++- ...65.0.17__retain_capacity_send_boundary.sql | 258 ++++++++++++++++++ ...CapacityExecutionOwnerIntegrationTest.java | 6 +- ...alNewFinalAdmissionCompositionFixture.java | 59 +++- ...lAdmissionOwnerIntegrationTestSupport.java | 29 +- ...tatusRepositoryIntegrationTestSupport.java | 60 +++- ...ransferCapacityCustodyIntegrationTest.java | 187 ++++++++++++- ...nTransferSerializationIntegrationTest.java | 21 +- ...eFamilyCatalogPostgresIntegrationTest.java | 117 +++++++- ...riginalNewCapacityExecutionBudgetTest.java | 4 +- 25 files changed, 1390 insertions(+), 64 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.17__retain_capacity_send_boundary.sql diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 6805358771..fe51793c19 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -238,7 +238,9 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued Exact replay is guaranteed only for outcomes Account durably retained. A billing or non-creating entitlement refusal that did not retain a decision receipt is not a replayable outcome; a later retry rechecks current evidence freshness before deciding and cannot treat the earlier refusal as a retained result. -`ReadTenantCapacityQuotaDenial` is the private read-only reconciliation operation for the exact Game Session mTLS peer while its original reserve remains active. It takes the original commit request and matches the outer identity, attempt, fence, complete payload and digest. Account returns the original durable quota denial and no other outcome. Missing or ambiguous evidence keeps the original reserve and admission closed. A fresh request or automatic mutation retry does not recover the original outcome. Before enabling this composition, qualify recovery after the original response is lost, quota headroom returns and the caller restarts. Verify that no new attempt, reservation or refusal slot was used. Verify in the Game Session settlement owner that the same original reserve and its current fence are still authoritative in the transaction that consumes the denial. The historical request and Account receipt authenticate the original outcome, not ownership after the RPC returns. Before composition is enabled, qualify a disposable case where the original reserve fence changes while the read is outstanding: the late denial must not advance, release or otherwise mutate that reserve, and the unchanged-fence case must preserve the original reconciliation semantics. The [strict tenant-capacity owner tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the remaining caller and owner proof. +`ReadTenantCapacityAdmissionOutcome` is a private read-only reconciliation method for the exact Game Session mTLS peer and typed player context. It binds the original commit request's full outer identity, attempt, fence, canonical payload and digest. Account returns that attempt's retained reservation or exact durable quota denial. A reservation read conveys the retained lifecycle state; the result alone grants no new execution, renewal or transfer authority. Missing or mismatched evidence fails closed without requesting a new evaluation, consuming a refusal slot or changing Account state. + +`ReadTenantCapacityQuotaDenial` reads only the original durable quota denial under the same exact identity. Game Session can use it to settle a still-held original charge even after the original OPEN window expires. The local transaction must recheck the current selected owner and the original charge against concurrent execution custody. The denial conveys no permission to admit the player or replace the attempt. See [Game Session capacity evidence](../game-session-service/runtime-and-data.md#original-new-capacity-execution-evidence) for send and retention rules. The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. 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 8b08eacc90..9d0c82ef1a 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -6,7 +6,7 @@ V1063 adds retained exact original capacity execution evidence and the final tra The seven-key tenant-slot final script atomically serializes `FINAL` against permanent same-attempt `CLOSE`, retaining the complete attempt envelope, reservation fence/expiry, original owner and actual committed session hash/times. New execution requires the exact persistent `AUTHORIZED` record and an unexpired reservation at Redis `TIME`. Account transition restrictions, coupled to the irreversible closure, exclude a delayed final CAS after release or rearm without relying on a one-time remote current-fence read. Original evidence is immutable and retained without TTL, deletion or truncation. V1063 separately classifies the evidence family and seals the next runtime-family catalog epoch without changing retained predecessor epochs or migration histories. -Game Session bounds the number and retained bytes of original-NEW capacity execution records per tenant allocation. Its durable owner precharges each exact attempt before dispatch so a full budget can refuse new admissions while preserving room to fence an already charged unresolved original whose execution key is absent. The charge covers the largest permitted execution record for that attempt and is shared by installation, same-attempt closure and transfer fencing. An authenticated exact Account quota denial can return that attempt’s active count and byte reservation only after Account durably excludes acceptance and Game Session matches the current selected owner under the region lock in the transaction that settles the charge. The settlement also serializes against execution insertion. The original charge binding and decision identifier remain durable under a separate finite record limit. Exact denied replays use that receipt, and lost or ambiguous Account responses keep the charge active. Exact retries neither increase the charge nor create a new dispatch. An absent or unqualified charge withholds new effects, preserves the original evidence and leaves the Account reservation held. The [Coordination reset policy](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) governs storage loss and restore. The bounded preparation retains the full binding and reserves no authority to delete evidence. Fleet sizing, operational qualification and an independently approved retirement policy are activation prerequisites. +Game Session bounds the number and retained bytes of original-NEW capacity execution records per tenant allocation. Its durable owner precharges each exact attempt before dispatch so a full budget can refuse new admissions while preserving room to fence an already charged unresolved original whose execution key is absent. The charge covers the largest permitted execution record for that attempt and is shared by installation, same-attempt closure and transfer fencing. An authenticated exact Account quota denial can return that attempt’s active count and byte reservation only after Account durably excludes acceptance and Game Session matches the current selected owner under the region lock in the transaction that settles the charge. The settlement also serializes against execution insertion. The original charge binding and decision identifier remain durable under a separate finite record limit. Exact denied replays use that receipt, and lost or ambiguous Account responses keep the charge active. Exact retries neither increase the charge nor create a new dispatch. An absent or unqualified charge withholds new effects, preserves the original evidence and leaves the Account reservation held. The first creating Account call requires a committed Game Session send claim under the same exact region and tenant budget locks. An unclaimed attempt can release active count and bytes only when a local transaction proves its send permission was never issued. The retained identity and release receipt still count against total history. A new precharge can reclaim one expired unclaimed slot in the same tenant, under the tenant budget lock, even after the original region moves. A new budget requires an explicit retained-history bound. Older immutable budgets without one cannot admit new charges. Exact reacquisition is permitted only while the original authorization and owner remain current, under the existing active ceiling. With its send permission issued, or with unknown predecessor state, the attempt uses Account's exact read-only outcome. A missing or ambiguous read does not authorize creation, retirement or settlement. If the original admission currentness check fails, Game Session can still read an exact durable Account denial for its existing unsettled charge under the selected region owner and settle that local charge. The admission remains refused. Activation must first exclude any writer that could call Account without acquiring the durable send claim. The [Coordination reset policy](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) governs storage loss and restore. The bounded preparation retains the full binding and reserves no authority to delete evidence. Fleet sizing, operational qualification and an independently approved retirement policy are activation prerequisites. The finalized schema-2 reader requires `capacityExecutionDigest`; predecessor finalized values without it are unsupported by this unregistered preproduction cutover. Before activation or reuse of predecessor-populated storage, establish and resolve retained-data and active original-confirmation or recovery obligations while preserving immutable historical evidence. The [owning tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records this cutover limitation and the unknown inventory of earlier manually persisted data. diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index fedce5b3ac..1dae49bb6b 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -89,6 +89,8 @@ Per-service READMEs are expected to state which ACL user(s) each service uses an - The logical `coord_app` profile is instantiated as distinct `account_coord_app`, `gateway_coord_app`, `entity_coord_app`, `gamesession_coord_app`, and `automation_coord_app` principals with disjoint key-pattern allowlists. The ConflictTracker grants are exact: `entity_coord_app` may access only `~conflict:entity:*`, while the Game Session grant is only `~conflict:session:*` for that diagnostic family (alongside Game Session's separately registered tick/session families); neither principal may access the other's conflict scope. No service or maintenance tool may use a shared principal that can read/write another service's owner families, and no ACL user may read/write both coordination and cache prefixes on the same deployment. - `automation_queue_rebuild_maint` is admitted only for the externally fenced Automation queue reset/rebuild path; future non-Automation rebuilds require separate named owner principals and prefix contracts rather than reusing it. +Before registering capacity-bound timeline initialization, the effective `gamesession_coord_app` profile must allow Redis `TIME` for the deadline-bound Game Session timeline script. Qualification uses that named principal against an absent test timeline in each registering profile. The expected result is the script's read-only absence result within the proposed deadline. Fixture-only ACLs do not establish that an installed profile has this capability. + Game Session's target dual-role wiring is explicit: `gamesession_coord_app` uses `RedisCoordConfig` and a dedicated Coordination Redis connection for tick/session coordination families, while `gamesession_cache_app` uses `RedisCacheConfig` and a separate Cache/Rate-Limit Redis connection for `view:room-look:*` only. The clients, credentials, pools, and endpoint configuration are distinct. The current generic `firemud.redis.*` binding and shared Spring Redis template remain implementation drift and are not proof that role separation or the target ACLs are implemented. ## Configuration and Redis Role Selection 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 3b442f4082..c7838dcc91 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -36,6 +36,8 @@ Account capacity activation requires an explicit finite V1040.2 refusal budget f V1065.0.5–V1065.0.7 prepare execution evidence budgets, exact Account denial settlement and transfer inventory reservation under the [Game Session execution owner](../../architecture/microservices/game-session-service/runtime-and-data.md#original-new-capacity-execution-evidence). Physical proof covers independent count and byte exhaustion, concurrent last-slot claims, exact replay, absent-key fencing at capacity, stale or restored Redis evidence, a populated catalog upgrade, and frozen-transfer completion and replay at exhaustion. Production budgets, predecessor backfill, deployment-wide sizing, coordinated restore, retention policy, registration and activation remain open. +Game Session V1065.0.17 and the Account retained-outcome method keep the original exact binding from first send through recovery. The Game Session owner records send permission before the first creating RPC, reclaims expired still-unclaimed active slots without deleting history, and uses authenticated read-only Account evidence after a possible send. A missed-denial settlement can recover after OPEN expiry while the same region owner remains authoritative. Live activation still requires excluding older writers, qualifying explicit tenant budgets and verifying the deployed Coordination Redis authority. + The Game Session parent slice builds on the Account capacity foundation. It owns original-NEW execution, its exact local read/proof, and normal owner handoff. The authenticated Account recovery read and physical cross-service proof remain in the dependent receiving slice. The selected owner retains its original execution and handoff evidence while registration and admission remain held. The [shared capacity-admission/v1 schema](../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json), typed contract/digest, exact-presence proto/codec, bounded unregistered Account mTLS receiver, and unregistered [Game Session client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java) are locally prepared. The complete existing Account bundle is strictly decoded and bound byte-for-byte in the ADR 0047 grammar, including its snapshot/evaluation identities, entitlement fields, authority tuple, billing cutoff and all checkpoints. It is never replaced by a quota read, subset or digest-only surrogate. Game Session and World contexts remain distinct, and the receiver derives the exact workload from TLS rather than a serialized identity. diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index dad814ccb5..f60fe06440 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -15,6 +15,9 @@ service AccountService { // Private read-only reconciliation of an exact retained quota denial. An unavailable // outcome does not prove the original attempt did not commit. rpc ReadTenantCapacityQuotaDenial(CommitTenantCapacityAdmissionRequest) returns (CommitTenantCapacityAdmissionResponse); + // Private read-only reconciliation of an exact retained positive or quota-denial outcome. + // An unavailable outcome does not prove the original attempt did not commit. + rpc ReadTenantCapacityAdmissionOutcome(CommitTenantCapacityAdmissionRequest) returns (CommitTenantCapacityAdmissionResponse); rpc Ping(PingRequest) returns (PingResponse); rpc CreateAccount(CreateAccountRequest) returns (CreateAccountResponse); rpc Authenticate(AuthenticateRequest) returns (AuthenticateResponse); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java index 04c302b678..57e909dc22 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -93,8 +93,18 @@ public Record findForReplay(Identity id) { return find(id, FIND_RESERVATION); } + /** Exact outcome read uses the same replay selector inside a genuine read-only transaction. */ + public Record findForReplayReadOnly(Identity id) { + return find(id, FIND_RESERVATION, true); + } + private Record find(Identity id, String query) { - transaction(); + return find(id, query, false); + } + + private Record find(Identity id, String query, boolean readOnly) { + if (readOnly) readOnlyTransaction(); + else transaction(); return dsl.fetchOne(query, id.tenantId(), id.requestId(), id.admissionId()); } @@ -110,14 +120,27 @@ public Record usage(Request request) { } public Result exact(Request request, Record row) { - if (!request.mutationDigest().equals(row.get("mutation_digest", String.class)) + requireExact(request, row, false); + return result(row); + } + + /** Read-only counterpart to exact replay; digest and identity checks are shared with mutation. */ + public Result exactReadOnly(Request request, Record row) { + readOnlyTransaction(); + requireExact(request, row, true); + return resultReadOnly(row); + } + + private static void requireExact(Request request, Record row, boolean unavailableOnMismatch) { + if (row == null + || !request.mutationDigest().equals(row.get("mutation_digest", String.class)) || !request.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class)) || request.capacityRearmFence() != number(row, "capacity_rearm_fence") || !Arrays.equals( CapacityAdmissionDigest.preimage(request), row.get("canonical_payload", byte[].class)) - || !request.evidence().callerWorkload().equals(row.get("caller_workload", String.class))) - throw conflict(); - return result(row); + || !request.evidence().callerWorkload().equals(row.get("caller_workload", String.class))) { + throw unavailableOnMismatch ? unavailable() : conflict(); + } } public void requirePriorHistory(Request prior, Request next) { @@ -201,6 +224,16 @@ public void updateUsage(Request request, Record before, long held, long used) { public Result result(Record row) { transaction(); + return resultFromSnapshot(row); + } + + /** Builds the exact retained positive result under the read-only transaction guard. */ + public Result resultReadOnly(Record row) { + readOnlyTransaction(); + return resultFromSnapshot(row); + } + + private Result resultFromSnapshot(Record row) { Record evaluation = dsl.fetchOne( "SELECT snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", @@ -243,6 +276,11 @@ public static void transaction() { || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw unavailable(); } + public static void readOnlyTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw unavailable(); + } + public static CapacityException conflict() { return new CapacityException(Failure.IDEMPOTENCY_CONFLICT); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java index cd3f6d6684..543aed23e2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java @@ -41,6 +41,14 @@ public String requireAuthenticatedCaller() { } public String requireQuotaDenialReader() { + return requireGameSessionOutcomeReader(); + } + + public String requireAdmissionOutcomeReader() { + return requireGameSessionOutcomeReader(); + } + + private String requireGameSessionOutcomeReader() { String value = quotaDenialReader.get(); if (!gameSession.equals(value) || ambient()) throw Status.UNAUTHENTICATED.asRuntimeException(); return value; @@ -69,6 +77,13 @@ public ServerCall.Listener interceptCall( return Contexts.interceptCall( Context.current().withValue(quotaDenialReader, workload), call, headers, next); } + if (AccountServiceGrpc.getReadTenantCapacityAdmissionOutcomeMethod() + .getFullMethodName() + .equals(method) + && gameSession.equals(workload)) { + return Contexts.interceptCall( + Context.current().withValue(quotaDenialReader, workload), call, headers, next); + } return deny(call, Status.PERMISSION_DENIED); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 40f08a92d2..0afe86a7e7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -66,7 +66,7 @@ public final class AccountTenantCapacityOwner { private final AccountTenantCapacityRepository capacity; private final AccountCapacityOriginDecisionRepository originDecisions; private final TransactionTemplate transaction; - private final TransactionTemplate denialReadTransaction; + private final TransactionTemplate retainedOutcomeReadTransaction; private final Clock clock; private final String namespace; @@ -94,11 +94,13 @@ public AccountTenantCapacityOwner( transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); transaction.setTimeout(TRANSACTION_TIMEOUT_SECONDS); - denialReadTransaction = new TransactionTemplate(transactions); - denialReadTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - denialReadTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - denialReadTransaction.setReadOnly(true); - denialReadTransaction.setTimeout(TRANSACTION_TIMEOUT_SECONDS); + retainedOutcomeReadTransaction = new TransactionTemplate(transactions); + retainedOutcomeReadTransaction.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + retainedOutcomeReadTransaction.setIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + retainedOutcomeReadTransaction.setReadOnly(true); + retainedOutcomeReadTransaction.setTimeout(TRANSACTION_TIMEOUT_SECONDS); } /** Reads only an exact historical quota refusal; absence does not resolve an unknown commit. */ @@ -115,7 +117,7 @@ public UUID readRetainedQuotaDenial(Request request, String authenticatedCaller) || Context.current().isCancelled()) throw unavailable(); try { UUID denialId = - denialReadTransaction.execute(status -> { + retainedOutcomeReadTransaction.execute(status -> { if (Context.current().isCancelled()) throw unavailable(); dsl.connection(connection -> { if (connection.getAutoCommit() || !connection.isReadOnly()) throw unavailable(); @@ -133,6 +135,45 @@ public UUID readRetainedQuotaDenial(Request request, String authenticatedCaller) } } + /** + * Reads only an exact retained positive reservation or exact retained quota denial. It neither + * refreshes current source evidence nor authorizes a new commit. + */ + public Result readRetainedAdmissionOutcome(Request request, String authenticatedCaller) { + requireCaller(request, authenticatedCaller); + if (!TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION) + .equals(authenticatedCaller)) throw new CapacityException(Failure.PERMISSION_DENIED); + request.requireStructurallyValid(); + requireSupportedShape(request); + if (request.capacityRearmFence() != 1 || !request.evidence().permitsCreation()) + throw unavailable(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || Context.current().isCancelled()) throw unavailable(); + try { + Result result = + retainedOutcomeReadTransaction.execute(status -> { + if (Context.current().isCancelled()) throw unavailable(); + dsl.connection(connection -> { + if (connection.getAutoCommit() || !connection.isReadOnly()) throw unavailable(); + }); + Record reservation = capacity.findForReplayReadOnly(request.identity()); + if (reservation != null) return capacity.exactReadOnly(request, reservation); + UUID denialId = originDecisions.readRetainedQuotaDenial(request); + if (denialId == null) throw unavailable(); + throw new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED, denialId); + }); + if (result == null) throw unavailable(); + return result; + } catch (CapacityException failure) { + // A mismatch or any non-quota refusal is not evidence that this attempt did not commit. + if (failure.code() == Failure.IDEMPOTENCY_CONFLICT) throw unavailable(); + throw failure; + } catch (IllegalArgumentException invalidEvidence) { + throw unavailable(); + } + } + public Result commit(Request request, String authenticatedCaller) { requireCaller(request, authenticatedCaller); request.requireStructurallyValid(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index c0da7cb8aa..1ffbb07bdd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -173,4 +173,69 @@ public void readTenantCapacityQuotaDenial( observer.onError(Status.INTERNAL.asRuntimeException()); } } + + @Override + public void readTenantCapacityAdmissionOutcome( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String peer; + try { + peer = guard.requireAdmissionOutcomeReader(); + } catch (StatusRuntimeException denied) { + observer.onError(Failure.AUTH_UNAVAILABLE.toStatusException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); + return; + } + final Request request; + try { + request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + } catch (IllegalArgumentException | ArithmeticException invalid) { + observer.onError(Failure.INVALID_ARGUMENT.toStatusException()); + return; + } + if (!request.evidence().callerWorkload().equals(peer)) { + observer.onError(Failure.PERMISSION_DENIED.toStatusException()); + return; + } + CommitTenantCapacityAdmissionResponse result; + try { + try { + result = + TenantCapacityAdmissionGrpcCodec.toResponse( + request, owner.readRetainedAdmissionOutcome(request, peer)); + } catch (CapacityException denied) { + if (denied.code() != Failure.CAPACITY_QUOTA_EXCEEDED) throw denied; + result = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, denied.code(), denied.durableDenialId()); + } + } catch (CapacityException denied) { + Failure code = + switch (denied.code()) { + case INVALID_ARGUMENT, PERMISSION_DENIED -> denied.code(); + default -> Failure.ENTITLEMENT_UNAVAILABLE; + }; + observer.onError(code.toStatusException()); + return; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException unavailable) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); + return; + } catch (RuntimeException internal) { + observer.onError(Status.INTERNAL.asRuntimeException()); + return; + } + try { + observer.onNext(result); + observer.onCompleted(); + } catch (RuntimeException callback) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 8deec4026a..92e59c6f85 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -86,6 +86,8 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.TransactionDefinition; @@ -149,6 +151,18 @@ void actualCoordinatorConfirmsAndRecreatedOwnersRetryExactOriginalResult() throw String rows = session.durableImage(); String capacity = session.capacityImage(); String decisions = session.capacityDecisionImage(); + var retained = + session.capacityClient.commitWithSendBoundary( + session.capacityRequest, + CLOCK.millis() + 5_000L, + () -> AccountTenantCapacityClient.SendDisposition.READ_RETAINED); + assertThat(retained.identity()).isEqualTo(session.capacityRequest.identity()); + assertThat(retained.admissionAttemptId()) + .isEqualTo(session.capacityRequest.admissionAttemptId()); + assertThat(retained.mutationDigest()).isEqualTo(session.capacityRequest.mutationDigest()); + assertThat(session.durableImage()).isEqualTo(rows); + assertThat(session.capacityImage()).isEqualTo(capacity); + assertThat(session.capacityDecisionImage()).isEqualTo(decisions); var physical = new java.util.TreeMap<>(session.gs.capacityStateImage()); // The current region owner can renew its lease independently of admission replay. physical.keySet().removeIf(key -> key.startsWith("redis:tick-executor-lease:")); @@ -679,8 +693,10 @@ void actualCoordinatorSettlesTheLastActiveSlotAndReplaysTheDenialWithoutAccountC } } - @Test - void localSettlementRollbackPreservesAccountRefusalAndAllowsExactRetry() throws Exception { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void localSettlementRollbackPreservesAccountRefusalAndAllowsExactRetry(boolean openExpired) + throws Exception { try (Session session = session(CLOCK, 1, 2); OriginalNewCredential credential = session.issue()) { session.provisionCapacityRefusalBudget(); @@ -693,6 +709,7 @@ void localSettlementRollbackPreservesAccountRefusalAndAllowsExactRetry() throws sql.execute( "CREATE TRIGGER controlled_settlement_rollback BEFORE UPDATE" + " ON game_session_capacity_evidence_charge FOR EACH ROW" + + " WHEN (NEW.account_denial_id IS DISTINCT FROM OLD.account_denial_id)" + " EXECUTE FUNCTION controlled_settlement_rollback()"); UUID denialId; try { @@ -716,8 +733,22 @@ void localSettlementRollbackPreservesAccountRefusalAndAllowsExactRetry() throws sql.execute("DROP FUNCTION controlled_settlement_rollback()"); } var beforeRetry = session.capacityDecisionImage(); - var replay = assertThrows(CapacityRefusedException.class, () -> session.complete(request)); - assertThat(replay.durableDenialId()).isEqualTo(denialId); + if (openExpired) { + assertThat( + assertThrows( + IllegalStateException.class, + () -> + session.gs.completeAfterInitialOpenWindow( + session.client, + session.jwks, + session.jwt, + session.capacityClient, + request))) + .isNotInstanceOf(CapacityRefusedException.class); + } else { + var replay = assertThrows(CapacityRefusedException.class, () -> session.complete(request)); + assertThat(replay.durableDenialId()).isEqualTo(denialId); + } assertThat(session.capacityDecisionImage()).isEqualTo(beforeRetry); assertThat( sql.fetchSingle( @@ -797,7 +828,8 @@ void lostCommittedQuotaResponseKeepsReserveUntilExactRetry() throws Exception { assertThrows(CapacityRefusedException.class, () -> session.complete(request)); assertThat(assertExactAccountQuotaDenial(session, request, exactRetry)) .isEqualTo(committedId); - assertThat(fault.calls.get()).isEqualTo(2); + assertThat(fault.calls.get()).isEqualTo(1); + assertThat(fault.retainedReads.get()).isEqualTo(1); assertThat(session.capacityDecisionImage()).isEqualTo(decision); assertThat( session @@ -823,7 +855,8 @@ void lostCommittedQuotaResponseKeepsReserveUntilExactRetry() throws Exception { session.stopCapacityServer(); var replay = assertThrows(CapacityRefusedException.class, () -> session.complete(request)); assertThat(replay.durableDenialId()).isEqualTo(committedId); - assertThat(fault.calls.get()).isEqualTo(2); + assertThat(fault.calls.get()).isEqualTo(1); + assertThat(fault.retainedReads.get()).isEqualTo(1); assertThat(session.capacityDecisionImage()).isEqualTo(decision); assertThat(session.capacityImage()).isEqualTo(capacityBefore); assertThat(session.gsReceiptImage()).isEqualTo(transitionsBefore); @@ -883,6 +916,8 @@ private static final class DropFirstQuotaResponse implements ClientInterceptor { private final TenantCapacityAdmission.Request exact; final java.util.concurrent.atomic.AtomicInteger calls = new java.util.concurrent.atomic.AtomicInteger(); + final java.util.concurrent.atomic.AtomicInteger retainedReads = + new java.util.concurrent.atomic.AtomicInteger(); final java.util.concurrent.atomic.AtomicReference observedDenial = new java.util.concurrent.atomic.AtomicReference<>(); final java.util.concurrent.atomic.AtomicBoolean successfullyDropped = @@ -896,6 +931,12 @@ private static final class DropFirstQuotaResponse implements ClientInterceptor { public ClientCall interceptCall( MethodDescriptor method, CallOptions options, Channel next) { var delegate = next.newCall(method, options); + if (net.firedevops.firemud.account.v1.AccountServiceGrpc + .getReadTenantCapacityAdmissionOutcomeMethod() + .getFullMethodName() + .equals(method.getFullMethodName())) { + retainedReads.incrementAndGet(); + } if (!net.firedevops.firemud.account.v1.AccountServiceGrpc .getCommitTenantCapacityAdmissionMethod() .getFullMethodName() diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java index 2d7c2b4ce9..a286d7e91f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java @@ -105,6 +105,23 @@ void quotaDenialReadRequiresExactGameSessionTlsWithoutAmbientAuthority() throws assertThat(invoke(method, gameSession).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); } + @Test + void admissionOutcomeReadRequiresExactGameSessionTlsWithoutAmbientAuthority() throws Exception { + var method = AccountServiceGrpc.getReadTenantCapacityAdmissionOutcomeMethod(); + var gameSession = tls("firemud", "game-session-service"); + assertThat(invoke(method, gameSession, "spiffe://firemud/ns/firemud/sa/game-session-service")) + .isNull(); + assertThatThrownBy(guard::requireAdmissionOutcomeReader) + .isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(invoke(method, tls("firemud", "world-management-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(invoke(method, tls("other", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, gameSession).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + private Status invoke(MethodDescriptor method, SSLSession ssl) { return invoke(method, ssl, null); } @@ -122,9 +139,13 @@ private Status invoke(MethodDescriptor method, SSLSession ssl, String expectedCa ServerCallHandler next = (ignored, headers) -> { if (AccountServiceGrpc.getReadTenantCapacityQuotaDenialMethod() - .getFullMethodName() - .equals(method.getFullMethodName())) { + .getFullMethodName() + .equals(method.getFullMethodName()) + || AccountServiceGrpc.getReadTenantCapacityAdmissionOutcomeMethod() + .getFullMethodName() + .equals(method.getFullMethodName())) { assertThat(guard.requireQuotaDenialReader()).isEqualTo(expectedCallerUri); + assertThat(guard.requireAdmissionOutcomeReader()).isEqualTo(expectedCallerUri); assertThatThrownBy(guard::requireAuthenticatedCaller) .isInstanceOf(StatusRuntimeException.class); } else { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 0dc6506fe7..c9c8d4e7c8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -18,6 +18,7 @@ import io.grpc.stub.StreamObserver; import java.sql.Connection; import java.time.Clock; +import java.time.OffsetDateTime; import java.util.UUID; import java.util.stream.Stream; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; @@ -60,6 +61,18 @@ private enum RetainedEvidence { AUTOCOMMIT_CONNECTION } + private enum RetainedOutcome { + EXACT_POSITIVE, + EXACT_QUOTA_DENIAL, + ABSENT, + MISMATCHED_POSITIVE, + MISMATCHED_ATTEMPT, + MISMATCHED_CANONICAL_PAYLOAD, + GENERIC_NO_ACCEPT, + WRITABLE_CONNECTION, + AUTOCOMMIT_CONNECTION + } + @Test void malformedWireAndStructurallyInvalidRequestsRefuseBeforeOwner() { var valid = @@ -277,7 +290,7 @@ void quotaDenialReadUsesOnlyTheImmutableSelect(RetainedEvidence evidence) throws new AccountTenantCapacityOwner( dsl, accounts, memberships, issuances, scopes, transactions, clock, "prod"); StreamObserver observer = mock(); - try (var guards = quotaDenialReader(CapacityAdmissionTestFixture.PEER)) { + try (var guards = retainedOutcomeReader(CapacityAdmissionTestFixture.PEER)) { new AccountTenantCapacityGrpcService(owner, "prod") .readTenantCapacityQuotaDenial( TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); @@ -312,13 +325,14 @@ void quotaDenialReadRejectsWrongCallerBindingAndMalformedOriginalBeforeOwner() { var request = CapacityAdmissionTestFixture.playerRequest(); var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); AccountTenantCapacityOwner owner = mock(); - try (var guards = quotaDenialReader("spiffe://firemud/ns/prod/sa/world-management-service")) { + try (var guards = + retainedOutcomeReader("spiffe://firemud/ns/prod/sa/world-management-service")) { StreamObserver observer = mock(); new AccountTenantCapacityGrpcService(owner, "prod") .readTenantCapacityQuotaDenial(wire, observer); assertFailure(observer, Failure.PERMISSION_DENIED); } - try (var guards = quotaDenialReader(CapacityAdmissionTestFixture.PEER)) { + try (var guards = retainedOutcomeReader(CapacityAdmissionTestFixture.PEER)) { StreamObserver observer = mock(); new AccountTenantCapacityGrpcService(owner, "prod") .readTenantCapacityQuotaDenial(wire.toBuilder().setCapacityDelta(0).build(), observer); @@ -327,6 +341,208 @@ void quotaDenialReadRejectsWrongCallerBindingAndMalformedOriginalBeforeOwner() { verifyNoInteractions(owner); } + @Test + void admissionOutcomeReadRejectsWrongCallerBindingAndMalformedOriginalBeforeOwner() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + AccountTenantCapacityOwner owner = mock(); + try (var guards = + retainedOutcomeReader("spiffe://firemud/ns/prod/sa/world-management-service")) { + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityAdmissionOutcome(wire, observer); + assertFailure(observer, Failure.PERMISSION_DENIED); + } + try (var guards = retainedOutcomeReader(CapacityAdmissionTestFixture.PEER)) { + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityAdmissionOutcome( + wire.toBuilder().setCapacityDelta(0).build(), observer); + assertFailure(observer, Failure.INVALID_ARGUMENT); + } + verifyNoInteractions(owner); + } + + @ParameterizedTest + @EnumSource(RetainedOutcome.class) + void admissionOutcomeReadReturnsOnlyAnExactRetainedOutcome(RetainedOutcome retainedOutcome) + throws Exception { + var request = CapacityAdmissionTestFixture.playerRequest(); + UUID decisionId = UUID.randomUUID(); + DSLContext dsl = mock(); + Connection connection = mock(); + when(connection.isReadOnly()) + .thenReturn(retainedOutcome != RetainedOutcome.WRITABLE_CONNECTION); + when(connection.getAutoCommit()) + .thenReturn(retainedOutcome == RetainedOutcome.AUTOCOMMIT_CONNECTION); + doAnswer( + invocation -> { + invocation.getArgument(0, ConnectionRunnable.class).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + + String reservationSql = + "SELECT * FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?"; + Object[] reservationKey = { + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId() + }; + Record reservation = null; + if (retainedOutcome == RetainedOutcome.EXACT_POSITIVE + || retainedOutcome == RetainedOutcome.MISMATCHED_POSITIVE + || retainedOutcome == RetainedOutcome.MISMATCHED_ATTEMPT + || retainedOutcome == RetainedOutcome.MISMATCHED_CANONICAL_PAYLOAD) { + reservation = mock(Record.class); + when(reservation.get("mutation_digest", String.class)) + .thenReturn( + retainedOutcome == RetainedOutcome.MISMATCHED_POSITIVE + ? "wrong-digest" + : request.mutationDigest()); + when(reservation.get("admission_attempt_id", UUID.class)) + .thenReturn( + retainedOutcome == RetainedOutcome.MISMATCHED_ATTEMPT + ? UUID.randomUUID() + : request.admissionAttemptId()); + when(reservation.get("capacity_rearm_fence", Long.class)).thenReturn(1L); + when(reservation.get("canonical_payload", byte[].class)) + .thenReturn( + retainedOutcome == RetainedOutcome.MISMATCHED_CANONICAL_PAYLOAD + ? new byte[] {0} + : CapacityAdmissionDigest.preimage(request)); + when(reservation.get("caller_workload", String.class)) + .thenReturn(request.evidence().callerWorkload()); + if (retainedOutcome == RetainedOutcome.EXACT_POSITIVE) { + when(reservation.get("tenant_uuid", UUID.class)).thenReturn(request.identity().tenantId()); + when(reservation.get("request_id", UUID.class)).thenReturn(request.identity().requestId()); + when(reservation.get("admission_id", UUID.class)) + .thenReturn(request.identity().admissionId()); + when(reservation.get("reservation_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(reservation.get("reservation_fence", Long.class)).thenReturn(1L); + when(reservation.get("expires_at", OffsetDateTime.class)) + .thenReturn( + request + .evidence() + .expiresAt() + .truncatedTo(java.time.temporal.ChronoUnit.MICROS) + .atOffset(java.time.ZoneOffset.UTC)); + when(reservation.get("state", String.class)).thenReturn("RESERVED"); + when(reservation.get("evaluation_identity", String.class)) + .thenReturn(request.evidence().evaluationIdentity()); + } + } + when(dsl.fetchOne(reservationSql, reservationKey)).thenReturn(reservation); + + String denialSql = + "SELECT * FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND capacity_rearm_fence = ?"; + Object[] denialKey = { + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence() + }; + Record denial = null; + if (retainedOutcome == RetainedOutcome.EXACT_QUOTA_DENIAL + || retainedOutcome == RetainedOutcome.GENERIC_NO_ACCEPT) { + denial = mock(Record.class); + when(denial.get("admission_attempt_id", UUID.class)).thenReturn(request.admissionAttemptId()); + when(denial.get("mutation_digest", String.class)).thenReturn(request.mutationDigest()); + when(denial.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(request)); + when(denial.get("decision_id", UUID.class)).thenReturn(decisionId); + when(denial.get("decision", String.class)).thenReturn("NO_ACCEPT"); + when(denial.get("refusal_code", String.class)) + .thenReturn( + retainedOutcome == RetainedOutcome.EXACT_QUOTA_DENIAL + ? Failure.CAPACITY_QUOTA_EXCEEDED.name() + : null); + } + when(dsl.fetchOne(denialSql, denialKey)).thenReturn(denial); + + String evaluationSql = + "SELECT snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?"; + Record evaluation = mock(Record.class); + when(evaluation.get("snapshot_identity", String.class)) + .thenReturn(request.evidence().snapshotIdentity()); + when(dsl.fetchOne(evaluationSql, request.evidence().evaluationIdentity())) + .thenReturn(evaluation); + + PlatformTransactionManager transactions = mock(); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(invocation -> { + var definition = invocation.getArgument(0, TransactionDefinition.class); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getTimeout()).isEqualTo(5); + assertThat(definition.isReadOnly()).isTrue(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + return new SimpleTransactionStatus(); + }); + var owner = + new AccountTenantCapacityOwner( + dsl, + mock(AccountRepository.class), + mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class), + mock(AccountGameplayDelegationIssuanceRepository.class), + mock(AccountConnectScopeRepository.class), + transactions, + mock(Clock.class), + "prod"); + StreamObserver observer = mock(); + try (var guards = retainedOutcomeReader(CapacityAdmissionTestFixture.PEER)) { + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityAdmissionOutcome( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + if (retainedOutcome == RetainedOutcome.EXACT_POSITIVE) { + var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); + var ordered = inOrder(observer); + ordered.verify(observer).onNext(response.capture()); + assertThat(TenantCapacityAdmissionGrpcCodec.requireResponse(request, response.getValue())) + .isNotNull(); + ordered.verify(observer).onCompleted(); + verify(dsl).fetchOne(evaluationSql, request.evidence().evaluationIdentity()); + } else if (retainedOutcome == RetainedOutcome.EXACT_QUOTA_DENIAL) { + var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); + var ordered = inOrder(observer); + ordered.verify(observer).onNext(response.capture()); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response.getValue())) + .contains(new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + ordered.verify(observer).onCompleted(); + verify(dsl).fetchOne(denialSql, denialKey); + } else { + assertFailure(observer, Failure.ENTITLEMENT_UNAVAILABLE); + } + verify(dsl).connection(any(ConnectionRunnable.class)); + boolean connectionRejected = + retainedOutcome == RetainedOutcome.WRITABLE_CONNECTION + || retainedOutcome == RetainedOutcome.AUTOCOMMIT_CONNECTION; + if (connectionRejected) verify(dsl, never()).fetchOne(reservationSql, reservationKey); + else verify(dsl).fetchOne(reservationSql, reservationKey); + if (retainedOutcome == RetainedOutcome.EXACT_POSITIVE) { + verify(dsl, never()).fetchOne(denialSql, denialKey); + } else if (!connectionRejected + && retainedOutcome != RetainedOutcome.MISMATCHED_POSITIVE + && retainedOutcome != RetainedOutcome.MISMATCHED_ATTEMPT + && retainedOutcome != RetainedOutcome.MISMATCHED_CANONICAL_PAYLOAD + && (retainedOutcome == RetainedOutcome.EXACT_QUOTA_DENIAL + || retainedOutcome == RetainedOutcome.ABSENT + || retainedOutcome == RetainedOutcome.GENERIC_NO_ACCEPT)) { + verify(dsl).fetchOne(denialSql, denialKey); + } else { + verify(dsl, never()).fetchOne(denialSql, denialKey); + } + verifyNoMoreInteractions(observer); + verifyNoMoreInteractions(dsl); + } + private static Stream ownerUnavailableFailures() { return Stream.of( new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE), @@ -353,11 +569,14 @@ private static MockedConstruction authentica when(guard.requireAuthenticatedCaller()).thenReturn(CapacityAdmissionTestFixture.PEER)); } - private static MockedConstruction quotaDenialReader( + private static MockedConstruction retainedOutcomeReader( String peer) { return mockConstruction( AccountTenantCapacityWorkloadGuard.class, - (guard, context) -> when(guard.requireQuotaDenialReader()).thenReturn(peer)); + (guard, context) -> { + when(guard.requireQuotaDenialReader()).thenReturn(peer); + when(guard.requireAdmissionOutcomeReader()).thenReturn(peer); + }); } private static void assertFailure( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index 13892d755d..f8ded2fc83 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -13,6 +13,7 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; +import java.util.function.Supplier; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AccountServiceGrpc.AccountServiceBlockingStub; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; @@ -74,6 +75,38 @@ public Result commit(Request request, long absoluteDeadlineMillis) { request, absoluteDeadlineMillis, AccountServiceBlockingStub::commitTenantCapacityAdmission); + return readCommitResult(request, response); + } + + public enum SendDisposition { + AUTHORIZE_NEW, + READ_RETAINED, + EXPIRED_UNSENT + } + + /** Selects exactly one creating send only after its durable local claim has committed. */ + public Result commitWithSendBoundary( + Request request, long absoluteDeadlineMillis, Supplier authorize) { + var response = + invoke( + request, + absoluteDeadlineMillis, + (stub, wire) -> { + SendDisposition disposition = authorize.get(); + if (stub.getCallOptions().getDeadline().isExpired()) { + throw Status.DEADLINE_EXCEEDED.asRuntimeException(); + } + return switch (disposition) { + case AUTHORIZE_NEW -> stub.commitTenantCapacityAdmission(wire); + case READ_RETAINED -> stub.readTenantCapacityAdmissionOutcome(wire); + case EXPIRED_UNSENT -> throw Status.DEADLINE_EXCEEDED.asRuntimeException(); + }; + }); + return readCommitResult(request, response); + } + + private static Result readCommitResult( + Request request, CommitTenantCapacityAdmissionResponse response) { try { var refusal = TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response); if (refusal.isPresent()) throw new CapacityRefusedException(refusal.orElseThrow()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java index e5d19c84aa..9def1df219 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java @@ -1,10 +1,13 @@ package net.firedevops.firemud.gamesession.repository; import java.time.Clock; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.UUID; import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient.SendDisposition; import org.jooq.DSLContext; import org.jooq.exception.DataAccessException; @@ -39,13 +42,25 @@ static UUID precharge( if (now.isBefore(request.evidence().evaluatedAt()) || !now.isBefore(request.evidence().expiresAt().truncatedTo(ChronoUnit.MICROS))) throw unavailable(); + // A fresh charge needs one slot. Retire at most one expired positively unsent + // charge in the tenant, even if its original region owner has since moved. + tx.execute( + "WITH candidate AS (SELECT admission_attempt_id FROM game_session_capacity_evidence_charge" + + " WHERE tenant_id=? AND account_send_state='UNCLAIMED'" + + " AND account_send_evidence_expires_at <= statement_timestamp()" + + " ORDER BY account_send_evidence_expires_at,admission_attempt_id LIMIT 1)" + + " UPDATE game_session_capacity_evidence_charge c SET account_send_state='RELEASED_UNSENT'" + + " FROM candidate WHERE c.admission_attempt_id=candidate.admission_attempt_id" + + " AND c.account_send_state='UNCLAIMED'", + identity.tenantId()); try { int inserted = tx.execute( "INSERT INTO game_session_capacity_evidence_charge (admission_attempt_id,tenant_id," + " request_id,admission_id,capacity_rearm_fence,mutation_digest,candidate_digest," - + " selected_owner_id,selected_owner_fence,reserved_binding_bytes)" - + " VALUES (?,?,?,?,?,?,?,?,?,1048576)", + + " selected_owner_id,selected_owner_fence,reserved_binding_bytes," + + " account_send_state,account_send_evidence_expires_at)" + + " VALUES (?,?,?,?,?,?,?,?,?,1048576,'UNCLAIMED',CAST(? AS timestamptz))", request.admissionAttemptId(), identity.tenantId(), identity.requestId(), @@ -54,7 +69,9 @@ static UUID precharge( request.mutationDigest(), candidateDigest, selected.instanceId(), - selected.fence()); + selected.fence(), + OffsetDateTime.ofInstant( + request.evidence().expiresAt().truncatedTo(ChronoUnit.MICROS), ZoneOffset.UTC)); if (inserted != 1) throw unavailable(); return null; } catch (DataAccessException failure) { @@ -64,6 +81,63 @@ static UUID precharge( } } + static SendDisposition authorizeAccountSend( + DSLContext tx, + Request request, + String candidateDigest, + CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner selected, + String tag) { + lockBudget(tx, request, tag); + var charge = exactCharge(tx, request, candidateDigest, selected, tag); + if (charge == null) throw unavailable(); + if (charge.get("account_denial_id", UUID.class) != null) return SendDisposition.READ_RETAINED; + String state = charge.get("account_send_state", String.class); + if (state == null || "MAY_HAVE_SENT".equals(state)) return SendDisposition.READ_RETAINED; + if (!"UNCLAIMED".equals(state) && !"RELEASED_UNSENT".equals(state)) throw unavailable(); + + var expiry = charge.get("account_send_evidence_expires_at", OffsetDateTime.class); + var sqlNow = tx.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class); + if (expiry == null) throw unavailable(); + if (!expiry.isAfter(sqlNow)) { + // The tenant and region owner locks serialize this still-unsent proof against first send. + if ("UNCLAIMED".equals(state)) { + transitionSendState(tx, request.admissionAttemptId(), state, "RELEASED_UNSENT"); + } + return SendDisposition.EXPIRED_UNSENT; + } + transitionSendState(tx, request.admissionAttemptId(), state, "MAY_HAVE_SENT"); + return SendDisposition.AUTHORIZE_NEW; + } + + private static void transitionSendState( + DSLContext tx, UUID attemptId, String before, String after) { + if (tx.execute( + "UPDATE game_session_capacity_evidence_charge SET account_send_state=?" + + " WHERE admission_attempt_id=? AND account_send_state=?", + after, + attemptId, + before) + != 1) { + throw unavailable(); + } + } + + static boolean hasUnsettledPossibleSend( + DSLContext tx, + Request request, + String candidateDigest, + CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner selected, + String tag) { + var charge = exactCharge(tx, request, candidateDigest, selected, tag); + if (charge == null || charge.get("account_denial_id", UUID.class) != null) return false; + String state = charge.get("account_send_state", String.class); + return (state == null || "MAY_HAVE_SENT".equals(state)) + && tx.fetchOne( + "SELECT 1 FROM game_session_original_new_capacity_execution WHERE admission_attempt_id=?", + request.admissionAttemptId()) + == null; + } + static void settleDenied( DSLContext tx, Request request, @@ -121,7 +195,8 @@ private static org.jooq.Record exactCharge( var prior = tx.fetchOne( "SELECT c.tenant_id,c.request_id,c.admission_id,c.capacity_rearm_fence,c.mutation_digest," - + " c.candidate_digest,c.selected_owner_id,c.selected_owner_fence,t.tenant_gameplay_tag,c.account_denial_id" + + " c.candidate_digest,c.selected_owner_id,c.selected_owner_fence,t.tenant_gameplay_tag," + + " c.account_denial_id,c.account_send_state,c.account_send_evidence_expires_at" + " FROM game_session_capacity_evidence_charge c" + " JOIN game_session_canonical_tenant_gameplay_tag t USING (tenant_id)" + " WHERE c.admission_attempt_id=?", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 7cb0195fa8..65065b039d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -263,6 +263,55 @@ UUID precharge( }); } + net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient.SendDisposition + authorizeAccountSend( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + Request request, + CurrentOwner selected, + long deadline) { + if (budget == null) { + return within( + deadline, owner -> owner.authorizeAccountSend(source, request, selected, deadline)); + } + budget.check(); + OriginalNewCapacityExecution.requireOriginalNewRequest(request); + var candidate = source.candidate(); + var assignment = scopedTags().assignmentForTransition(candidate.bindingDecisionId()); + return sql() + .transactionResult(configuration -> { + var tx = DSL.using(configuration); + requireSelectedOwner(tx, candidate, selected); + return CanonicalGameplayCapacityEvidenceBudget.authorizeAccountSend( + tx, request, source.candidateDigest(), selected, assignment.tenantGameplayTag()); + }); + } + + boolean hasUnsettledPossibleSend( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + Request request, + CurrentOwner selected, + long deadline) { + return within( + deadline, + owner -> { + var candidate = source.candidate(); + var assignment = + owner.scopedTags().assignmentForTransition(candidate.bindingDecisionId()); + return owner + .sql() + .transactionResult(configuration -> { + var tx = DSL.using(configuration); + requireSelectedOwner(tx, candidate, selected); + return CanonicalGameplayCapacityEvidenceBudget.hasUnsettledPossibleSend( + tx, + request, + source.candidateDigest(), + selected, + assignment.tenantGameplayTag()); + }); + }); + } + void settleDeniedCharge( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, Request request, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index 436e376e63..f62d41c9f1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -115,7 +115,17 @@ FinalAdmissionResult completeOriginalNew( requireOriginalSource(source, originalDecision); var selectedOwner = capacityExecution.requireRequestBinding(source, capacityRequest, absoluteDeadlineMillis); - Currentness beforeEffects = currentness(source, privateRegionInstallation); + Currentness beforeEffects; + try { + beforeEffects = currentness(source, privateRegionInstallation); + } catch (RuntimeException failure) { + if (source.transitionStatus() + == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + && capacityRequest.evidence().permitsCreation()) { + reconcileDeniedCharge(source, capacityRequest, selectedOwner, absoluteDeadlineMillis); + } + throw failure; + } CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource currentSource = readSameSource(source, originalDecision, false); source = currentSource; @@ -180,10 +190,20 @@ FinalAdmissionResult completeOriginalNew( } final TenantCapacityAdmission.Result reservation; try { - reservation = - recoveredConfirmation == null - ? capacityClient.commit(capacityRequest, absoluteDeadlineMillis) - : recoveredConfirmation.committedCapacityResult(); + if (recoveredConfirmation != null) { + reservation = recoveredConfirmation.committedCapacityResult(); + } else if (precharge) { + var sendSource = source; + reservation = + capacityClient.commitWithSendBoundary( + capacityRequest, + absoluteDeadlineMillis, + () -> + capacityExecution.authorizeAccountSend( + sendSource, capacityRequest, selectedOwner, absoluteDeadlineMillis)); + } else { + reservation = capacityClient.commit(capacityRequest, absoluteDeadlineMillis); + } } catch (CapacityRefusedException refusal) { if (precharge && refusal.durableDenialId() != null) { try { @@ -311,6 +331,21 @@ FinalAdmissionResult completeOriginalNew( } } + private void reconcileDeniedCharge( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + TenantCapacityAdmission.Request request, + CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner selected, + long deadline) { + try { + if (!capacityExecution.hasUnsettledPossibleSend(source, request, selected, deadline)) return; + var denialId = capacityClient.readRetainedQuotaDenial(request, deadline); + capacityExecution.settleDeniedCharge(source, request, selected, denialId, deadline); + } catch (RuntimeException indeterminate) { + // Missing proof, changed owner or failed settlement leaves the charge held. The original + // currentness refusal is returned even when bookkeeping can reconcile the durable denial. + } + } + private Currentness currentness( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, CanonicalGameplayRegionLeaseOwner.Installation privateRegionInstallation) { diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.17__retain_capacity_send_boundary.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.17__retain_capacity_send_boundary.sql new file mode 100644 index 0000000000..7f55a8ea22 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.17__retain_capacity_send_boundary.sql @@ -0,0 +1,258 @@ +-- The charge remains the Game Session storage budget and grants no Account settlement authority. +-- Existing null send states mean transmission was possible. Never infer an unsent legacy charge. +-- Keep existing budget rows immutable. New rows must explicitly qualify retained history. +-- [jooq ignore start] +ALTER TABLE game_session_capacity_evidence_budget + ADD CONSTRAINT gs_capacity_evidence_budget_retained_limit_required + CHECK (maximum_retained_records IS NOT NULL) NOT VALID; +-- [jooq ignore stop] + +ALTER TABLE game_session_capacity_evidence_charge + ADD COLUMN account_send_state TEXT, + ADD COLUMN account_send_evidence_expires_at TIMESTAMP WITH TIME ZONE, + ADD COLUMN account_unsent_released_at TIMESTAMP WITH TIME ZONE, + ADD CONSTRAINT gs_capacity_evidence_send_state CHECK ( + (account_send_state IS NULL AND account_send_evidence_expires_at IS NULL + AND account_unsent_released_at IS NULL) + OR (account_send_state IS NOT NULL + AND account_send_state IN ('UNCLAIMED','MAY_HAVE_SENT','RELEASED_UNSENT') + AND account_send_evidence_expires_at IS NOT NULL AND isfinite(account_send_evidence_expires_at) + AND (account_unsent_released_at IS NULL OR isfinite(account_unsent_released_at)) + AND (account_send_state <> 'UNCLAIMED' OR account_unsent_released_at IS NULL) + AND (account_send_state <> 'RELEASED_UNSENT' OR account_unsent_released_at IS NOT NULL) + AND (account_denial_id IS NULL OR account_send_state='MAY_HAVE_SENT')) + ); + +DROP INDEX gs_capacity_evidence_charge_active; +CREATE INDEX gs_capacity_evidence_charge_active + ON game_session_capacity_evidence_charge(tenant_id, admission_attempt_id) + WHERE account_denial_id IS NULL AND account_send_state IS DISTINCT FROM 'RELEASED_UNSENT'; +CREATE INDEX gs_capacity_evidence_charge_unclaimed_expiry + ON game_session_capacity_evidence_charge(tenant_id, account_send_evidence_expires_at, admission_attempt_id) + WHERE account_send_state='UNCLAIMED'; + +-- [jooq ignore start] +-- Callers lock the current region owner before the tenant budget and before the exact charge CAS. +CREATE FUNCTION require_gs_capacity_send_owner( + p_tenant UUID, p_admission UUID, p_owner TEXT, p_fence BIGINT +) RETURNS VOID LANGUAGE plpgsql AS $$ +DECLARE scope RECORD; current_owner RECORD; +BEGIN + SELECT DISTINCT b.tenant_id,b.game_instance_id,b.region_id,b.region_epoch + INTO STRICT scope + FROM game_session_canonical_binding_region_bridge_obligation b + WHERE b.transition_id=p_admission; + SELECT r.owner_instance_id,r.executor_fence,r.owner_service,r.paused + INTO current_owner FROM game_session_region_runtime_status r + WHERE r.tenant_id=scope.tenant_id AND r.game_instance_id=scope.game_instance_id + AND r.region_id=scope.region_id AND r.region_epoch=scope.region_epoch + FOR UPDATE; + IF NOT FOUND OR scope.tenant_id IS DISTINCT FROM p_tenant + OR current_owner.owner_service IS DISTINCT FROM 'game-session-service' + OR current_owner.paused IS DISTINCT FROM false + OR current_owner.owner_instance_id IS DISTINCT FROM p_owner + OR current_owner.executor_fence IS DISTINCT FROM p_fence + OR EXISTS (SELECT 1 FROM game_session_region_owner_transfer t + WHERE t.tenant_id=scope.tenant_id AND t.game_instance_id=scope.game_instance_id + AND t.region_id=scope.region_id AND (t.state='FROZEN' + OR (t.state='COMPLETED' AND t.old_owner_id=p_owner AND t.old_owner_fence=p_fence))) THEN + RAISE EXCEPTION 'Capacity send boundary requires the exact current selected owner' USING ERRCODE='23514'; + END IF; +END; +$$; + +-- The active bound is shared by fresh insert and same-row reacquisition. +CREATE FUNCTION require_gs_capacity_evidence_active_room( + p_tenant UUID, p_records INTEGER, p_binding_bytes BIGINT, p_reserved_bytes INTEGER +) RETURNS VOID LANGUAGE plpgsql AS $$ +DECLARE used_records BIGINT; record_limit BIGINT; +BEGIN + record_limit := least(p_records,p_binding_bytes / p_reserved_bytes); + SELECT count(*) INTO used_records FROM ( + SELECT 1 FROM game_session_capacity_evidence_charge + WHERE tenant_id=p_tenant AND account_denial_id IS NULL + AND account_send_state IS DISTINCT FROM 'RELEASED_UNSENT' + LIMIT record_limit + ) active; + IF used_records >= record_limit THEN + RAISE EXCEPTION 'Capacity evidence budget is exhausted' USING ERRCODE='23514'; + END IF; +END; +$$; + +CREATE OR REPLACE FUNCTION guard_gs_capacity_evidence_charge() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE limits game_session_capacity_evidence_budget%ROWTYPE; used_records BIGINT; checked_at TIMESTAMP WITH TIME ZONE; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR NEW.reserved_binding_bytes IS DISTINCT FROM 1048576 + OR NEW.account_send_state IS DISTINCT FROM 'UNCLAIMED' + OR NEW.account_unsent_released_at IS NOT NULL OR NEW.account_denial_id IS NOT NULL THEN + RAISE EXCEPTION 'Capacity evidence requires a fresh unclaimed charge and READ COMMITTED' USING ERRCODE='23514'; + END IF; + PERFORM require_gs_capacity_send_owner(NEW.tenant_id,NEW.admission_id,NEW.selected_owner_id,NEW.selected_owner_fence); + SELECT * INTO limits FROM game_session_capacity_evidence_budget + WHERE tenant_id=NEW.tenant_id FOR UPDATE; + IF NOT FOUND OR limits.maximum_retained_records IS NULL THEN + RAISE EXCEPTION 'Active and retained capacity evidence budgets are required' USING ERRCODE='23514'; + END IF; + IF NOT EXISTS (SELECT 1 FROM game_session_canonical_binding_transition t + WHERE t.transition_id=NEW.admission_id AND t.tenant_id=NEW.tenant_id + AND t.status='PROVISIONAL' AND t.original_new_candidate_digest=NEW.candidate_digest) + OR EXISTS (SELECT 1 FROM game_session_original_new_capacity_execution e + WHERE e.tenant_id=NEW.tenant_id AND NOT EXISTS ( + SELECT 1 FROM game_session_capacity_evidence_charge c + WHERE c.admission_attempt_id=e.admission_attempt_id)) THEN + RAISE EXCEPTION 'Capacity evidence source or predecessor coverage is unavailable' USING ERRCODE='23514'; + END IF; + checked_at := clock_timestamp(); + IF NEW.account_send_evidence_expires_at IS NULL + OR NEW.account_send_evidence_expires_at <= checked_at + OR NEW.account_send_evidence_expires_at > checked_at + INTERVAL '15 seconds' THEN + RAISE EXCEPTION 'Fresh capacity evidence expiry is outside its original freshness bound' USING ERRCODE='23514'; + END IF; + PERFORM require_gs_capacity_evidence_active_room( + NEW.tenant_id,limits.maximum_records,limits.maximum_binding_bytes,NEW.reserved_binding_bytes); + SELECT count(*) INTO used_records FROM ( + SELECT 1 FROM game_session_capacity_evidence_charge + WHERE tenant_id=NEW.tenant_id LIMIT limits.maximum_retained_records + ) retained; + IF used_records >= limits.maximum_retained_records THEN + RAISE EXCEPTION 'Retained capacity evidence history is exhausted' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION require_gs_capacity_evidence_charge() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Capacity evidence dispatch requires READ COMMITTED' USING ERRCODE='23514'; + END IF; + PERFORM 1 FROM game_session_capacity_evidence_budget WHERE tenant_id=NEW.tenant_id FOR UPDATE; + IF NOT FOUND OR NOT EXISTS ( + SELECT 1 FROM game_session_capacity_evidence_charge c + JOIN game_session_canonical_tenant_gameplay_tag t ON t.tenant_id=c.tenant_id + WHERE c.admission_attempt_id=NEW.admission_attempt_id AND c.tenant_id=NEW.tenant_id + AND c.request_id=NEW.request_id AND c.admission_id=NEW.admission_id + AND NEW.transition_id=c.admission_id AND c.capacity_rearm_fence=NEW.capacity_rearm_fence + AND c.mutation_digest=NEW.mutation_digest AND c.selected_owner_id=NEW.selected_owner_id + AND c.selected_owner_fence=NEW.selected_owner_fence + AND c.account_denial_id IS NULL AND t.tenant_gameplay_tag=NEW.tenant_gameplay_tag + AND (c.account_send_state IS NULL OR c.account_send_state='MAY_HAVE_SENT') + AND octet_length(NEW.canonical_execution)<=c.reserved_binding_bytes + AND (convert_from(NEW.canonical_execution, 'UTF8')::jsonb)->>'candidateDigest'=c.candidate_digest + ) THEN + RAISE EXCEPTION 'Exact retained capacity evidence charge required' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION settle_gs_capacity_evidence_charge() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE limits game_session_capacity_evidence_budget%ROWTYPE; +BEGIN + IF TG_OP <> 'UPDATE' OR current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Capacity evidence charge history is retained' USING ERRCODE='23514'; + END IF; + IF OLD.account_denial_id IS NOT NULL + OR NEW.account_unsent_released_at IS DISTINCT FROM OLD.account_unsent_released_at + OR (to_jsonb(NEW) - 'account_send_state' - 'account_denial_id') + IS DISTINCT FROM (to_jsonb(OLD) - 'account_send_state' - 'account_denial_id') THEN + RAISE EXCEPTION 'Capacity evidence charge identity and settlement history are immutable' USING ERRCODE='23514'; + END IF; + -- Once the original send window expires, the Game Session tenant budget can return a + -- still-unclaimed slot even after its original region owner moved. No Account decision + -- is inferred. The terminal expiry and exact SQL state exclude a first or concurrent send. + IF OLD.account_send_state='UNCLAIMED' AND NEW.account_send_state='RELEASED_UNSENT' + AND NEW.account_denial_id IS NULL AND OLD.account_send_evidence_expires_at <= clock_timestamp() THEN + PERFORM 1 FROM game_session_capacity_evidence_budget WHERE tenant_id=OLD.tenant_id FOR UPDATE; + IF NOT FOUND OR EXISTS ( + SELECT 1 FROM game_session_original_new_capacity_execution + WHERE admission_attempt_id=OLD.admission_attempt_id + ) THEN + RAISE EXCEPTION 'Execution custody prevents capacity evidence charge changes' USING ERRCODE='23514'; + END IF; + NEW.account_unsent_released_at := clock_timestamp(); + RETURN NEW; + END IF; + PERFORM require_gs_capacity_send_owner(OLD.tenant_id,OLD.admission_id,OLD.selected_owner_id,OLD.selected_owner_fence); + SELECT * INTO limits FROM game_session_capacity_evidence_budget + WHERE tenant_id=OLD.tenant_id FOR UPDATE; + IF NOT FOUND OR EXISTS ( + SELECT 1 FROM game_session_original_new_capacity_execution + WHERE admission_attempt_id=OLD.admission_attempt_id + ) THEN + RAISE EXCEPTION 'Execution custody prevents capacity evidence charge changes' USING ERRCODE='23514'; + END IF; + + IF NEW.account_denial_id IS NOT NULL + AND NEW.account_send_state IS NOT DISTINCT FROM OLD.account_send_state + AND (OLD.account_send_state IS NULL OR OLD.account_send_state='MAY_HAVE_SENT') THEN + -- Only the owner supplies an exact authenticated durable Account denial. + RETURN NEW; + END IF; + IF NEW.account_denial_id IS NOT NULL OR limits.maximum_retained_records IS NULL THEN + RAISE EXCEPTION 'Invalid capacity evidence send transition' USING ERRCODE='23514'; + END IF; + IF OLD.account_send_state='UNCLAIMED' AND NEW.account_send_state='RELEASED_UNSENT' THEN + -- Winning this CAS excludes the first permission to invoke Account on this charge. + NEW.account_unsent_released_at := clock_timestamp(); + RETURN NEW; + END IF; + IF OLD.account_send_state IN ('UNCLAIMED','RELEASED_UNSENT') AND NEW.account_send_state='MAY_HAVE_SENT' THEN + IF OLD.account_send_evidence_expires_at <= clock_timestamp() + OR NOT EXISTS (SELECT 1 FROM game_session_canonical_binding_transition t + WHERE t.tenant_id=OLD.tenant_id AND t.transition_id=OLD.admission_id + AND t.status='PROVISIONAL' AND t.original_new_candidate_digest=OLD.candidate_digest) THEN + RAISE EXCEPTION 'Capacity send requires still-current original evidence' USING ERRCODE='23514'; + END IF; + IF OLD.account_send_state='RELEASED_UNSENT' THEN + PERFORM require_gs_capacity_evidence_active_room( + OLD.tenant_id,limits.maximum_records,limits.maximum_binding_bytes,OLD.reserved_binding_bytes); + END IF; + RETURN NEW; + END IF; + RAISE EXCEPTION 'Invalid capacity evidence send transition' USING ERRCODE='23514'; +END; +$$; +-- [jooq ignore stop] + +-- Runtime-family catalog registration +-- [jooq ignore start] +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1065.0.16' + ) AND ($needle$; + replacement := $replacement$WHERE version='1065.0.16' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.17__retain_capacity_send_boundary.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.17' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.16'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.17'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.16','V1065.0.16__retain_exact_initial_timeline_no_write_release.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.17'',''V1065.0.17__retain_capacity_send_boundary.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java index 2a38365524..b557152c65 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java @@ -273,10 +273,10 @@ void activeRecordCeilingRefusesADifferentOriginBelowTheRetainedCeilings() throws "INSERT INTO game_session_capacity_evidence_charge (admission_attempt_id, tenant_id," + " request_id, admission_id, capacity_rearm_fence, mutation_digest," + " candidate_digest, selected_owner_id, selected_owner_fence," - + " reserved_binding_bytes)" + + " reserved_binding_bytes, account_send_state, account_send_evidence_expires_at)" + " SELECT ?, tenant_id, ?, admission_id, capacity_rearm_fence, mutation_digest," + " candidate_digest, selected_owner_id, selected_owner_fence," - + " reserved_binding_bytes FROM game_session_capacity_evidence_charge" + + " reserved_binding_bytes, 'UNCLAIMED', clock_timestamp() + INTERVAL '10 seconds' FROM game_session_capacity_evidence_charge" + " WHERE admission_attempt_id = ?", otherAttempt, otherRequest, @@ -310,6 +310,7 @@ void lastPrechargedCapacityEvidenceSlotSurvivesFullBudgetAndSameAttemptReplay( // The initial charge happened in bridge(); the exact replay is idempotent even at capacity. owner.precharge(source, controlledCapacity.request(), selected, deadline()); + authorizeKnownAccountSend(source); var original = controlledCapacity.request(); var unsupported = new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( @@ -453,6 +454,7 @@ void failedInstallConnectRetainsDispatchAndNeverPermitsReinstallationOrNegativeP repairAccountMember(); bridge(false); var source = inventory.readOriginalNewFinalAdmissionSource(decision); + authorizeKnownAccountSend(source); RedisClient failedClient = mock(RedisClient.class); when(failedClient.connect(ByteArrayCodec.INSTANCE)) .thenThrow(new IllegalStateException("Controlled connection failure")); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java index 7cb65e0eff..da6264188a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java @@ -774,6 +774,28 @@ public Receipt complete( capacityRequest); } + public Receipt completeAfterInitialOpenWindow( + AccountGameplayAdmissionLeaseClient account, + AccountPublicJwksCache jwks, + String originalLoginJwt, + net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient capacityClient, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request + capacityRequest) { + // The controlled attestor can refresh its 30-second proof on each read. Advance only the + // admission coordinator, so it evaluates even that fresh readback beyond its OPEN window. + var expiredClock = Clock.offset(CLOCK, Duration.ofMinutes(2)); + return complete( + decision, + regionInstallation, + account, + jwks, + originalLoginJwt, + Math.max(System.currentTimeMillis(), expiredClock.millis()) + 10_000L, + capacityClient, + capacityRequest, + expiredClock); + } + private Receipt complete( CanonicalGameplayAdmissionDecision admission, CanonicalGameplayRegionLeaseOwner.Installation installation, @@ -784,6 +806,29 @@ private Receipt complete( net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient capacityClient, net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request capacityRequest) { + return complete( + admission, + installation, + account, + jwks, + originalLoginJwt, + deadline, + capacityClient, + capacityRequest, + CLOCK); + } + + private Receipt complete( + CanonicalGameplayAdmissionDecision admission, + CanonicalGameplayRegionLeaseOwner.Installation installation, + AccountGameplayAdmissionLeaseClient account, + AccountPublicJwksCache jwks, + String originalLoginJwt, + long deadline, + net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient capacityClient, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request + capacityRequest, + Clock coordinatorClock) { // Recreate the coordinator and its SQL/INITIAL/issuer/final owners on every invocation. var issuerSource = binding.currentIssuerSource(); var issuer = @@ -803,7 +848,7 @@ private Receipt complete( new CanonicalGameplayOriginalNewBoundCredentialVerifier(jwks, CLOCK), new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( coordination, scripts, CLOCK, tags), - CLOCK, + coordinatorClock, capacityClient, new CanonicalGameplayOriginalNewCapacityExecutionOwner( binding.dsl(), coordination, scripts, CLOCK, tags)); @@ -839,7 +884,11 @@ public Candidate candidate() { binding.dsl(), coordination, scripts, CLOCK, tags); var selected = executionOwner.requireRequestBinding(source, request, deadline); executionOwner.precharge(source, request, selected, deadline); - var reservation = capacityClient.commit(request, deadline); + var reservation = + capacityClient.commitWithSendBoundary( + request, + deadline, + () -> executionOwner.authorizeAccountSend(source, request, selected, deadline)); var execution = executionOwner.bind(source, request, reservation, deadline, selected); var issuerSource = binding.currentIssuerSource(); var issuer = @@ -942,7 +991,11 @@ public OwnerMovementFault commitThenMoveSelectedOwnerForFault( binding.dsl(), coordination, scripts, CLOCK, tags); var selected = executionOwner.requireRequestBinding(source, request, deadline); executionOwner.precharge(source, request, selected, deadline); - var result = client.commit(request, deadline); + var result = + client.commitWithSendBoundary( + request, + deadline, + () -> executionOwner.authorizeAccountSend(source, request, selected, deadline)); var identity = source.candidate().bindingIdentity(); if (binding .dsl() diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java index 657855386c..786a5e1f91 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java @@ -176,7 +176,7 @@ void bridge(boolean authorizeCapacity) { } void bridge(boolean authorizeCapacity, int maximumRecords, long maximumBindingBytes) { - bridge(authorizeCapacity, maximumRecords, maximumBindingBytes, null); + bridge(authorizeCapacity, maximumRecords, maximumBindingBytes, maximumRecords * 2); } void bridge( @@ -230,6 +230,16 @@ void bridge( controlledCapacity.selectedOwnerId(), controlledCapacity.selectedOwnerFence()), deadline()); if (!authorizeCapacity) return; + authorizeKnownAccountSend(source); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT account_send_state FROM game_session_capacity_evidence_charge" + + " WHERE admission_attempt_id=?", + controlledCapacity.request().admissionAttemptId()) + .get(0, String.class)) + .isEqualTo("MAY_HAVE_SENT"); try (var credential = new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); var raw = credential.template(); @@ -248,6 +258,23 @@ void bridge( } } + void authorizeKnownAccountSend( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source) { + assertThat( + capacityOwner() + .authorizeAccountSend( + source, + controlledCapacity.request(), + new CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner( + controlledCapacity.selectedOwnerId(), + controlledCapacity.selectedOwnerFence()), + deadline())) + .as("synthetic known send must retain the exact positive SQL send witness") + .isEqualTo( + net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient.SendDisposition + .AUTHORIZE_NEW); + } + void initializeCapacityEvidenceBudget( UUID tenantId, int maximumRecords, long maximumBindingBytes, Integer maximumRetainedRecords) { fixture diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java index 87c1016427..612d876b99 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java @@ -584,7 +584,35 @@ void seedUndeliveredDispatch(OriginalNewCapacityExecution original) { insertExecution(original, "INSTALL_DISPATCHED", null); } + net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient.SendDisposition + authorizeAccountSend(OriginalNewCapacityExecution original) { + var assignment = tags.assignmentForTransition(original.transitionId()); + var disposition = + capacity(sql) + .authorizeAccountSend( + admission, + original.request(), + new CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner( + original.selectedOwnerId(), original.selectedOwnerFence()), + transferDeadline()); + var sendState = + sql.fetchSingle( + "SELECT account_send_state,selected_owner_id,selected_owner_fence,candidate_digest" + + " FROM game_session_capacity_evidence_charge WHERE admission_attempt_id=?", + original.request().admissionAttemptId()) + .intoMap(); + if ("MAY_HAVE_SENT".equals(sendState.get("account_send_state")) + && original.selectedOwnerId().equals(sendState.get("selected_owner_id")) + && Long.valueOf(original.selectedOwnerFence()) + .equals(sendState.get("selected_owner_fence")) + && original.candidateDigest().equals(sendState.get("candidate_digest")) + && assignment.tenantId().equals(original.request().identity().tenantId())) + return disposition; + throw new IllegalStateException("Controlled known send lacks its exact positive SQL witness"); + } + void settle(OriginalNewCapacityExecution original, UUID denial) { + authorizeAccountSend(original); var assignment = tags.assignmentForTransition(original.transitionId()); sql.transaction(configuration -> CanonicalGameplayCapacityEvidenceBudget.settleDenied( @@ -611,9 +639,7 @@ void precharge(OriginalNewCapacityExecution original) { transferDeadline()); } - /** - * Exact test charge for the post-transfer raw INSERT refusal case, after source is retained. - */ + /** Exact controlled charge for raw dispatch before and after region transfer. */ void retainExactChargeForControlledSeed(OriginalNewCapacityExecution original) { if (!admission.candidateDigest().equals(original.candidateDigest()) || !admission.candidate().bindingDecisionId().equals(original.transitionId())) @@ -627,8 +653,9 @@ void retainExactChargeForControlledSeed(OriginalNewCapacityExecution original) { sql.execute( "INSERT INTO game_session_capacity_evidence_charge" + " (admission_attempt_id,tenant_id,request_id,admission_id,capacity_rearm_fence," - + " mutation_digest,candidate_digest,selected_owner_id,selected_owner_fence,reserved_binding_bytes)" - + " VALUES (?,?,?,?,?,?,?,?,?,1048576)", + + " mutation_digest,candidate_digest,selected_owner_id,selected_owner_fence,reserved_binding_bytes," + + " account_send_state,account_send_evidence_expires_at)" + + " VALUES (?,?,?,?,?,?,?,?,?,1048576,'UNCLAIMED',CAST(? AS timestamptz))", request.admissionAttemptId(), identity.tenantId(), identity.requestId(), @@ -637,11 +664,19 @@ void retainExactChargeForControlledSeed(OriginalNewCapacityExecution original) { request.mutationDigest(), original.candidateDigest(), original.selectedOwnerId(), - original.selectedOwnerFence()); + original.selectedOwnerFence(), + java.time.OffsetDateTime.ofInstant( + request.evidence().expiresAt().truncatedTo(java.time.temporal.ChronoUnit.MICROS), + java.time.ZoneOffset.UTC)); } void insertExecution( OriginalNewCapacityExecution original, String status, byte[] terminalReadback) { + var disposition = authorizeAccountSend(original); + if (disposition + == net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient.SendDisposition + .EXPIRED_UNSENT) + throw new IllegalStateException("Controlled known send expired before its send witness"); insertExecution(sql, original, status, terminalReadback); } @@ -650,6 +685,19 @@ void insertExecution( OriginalNewCapacityExecution original, String status, byte[] terminalReadback) { + var sendWitness = + context.fetchOne( + "SELECT account_send_state,selected_owner_id,selected_owner_fence,candidate_digest" + + " FROM game_session_capacity_evidence_charge WHERE admission_attempt_id=?", + original.request().admissionAttemptId()); + if (sendWitness == null + || !"MAY_HAVE_SENT".equals(sendWitness.get("account_send_state", String.class)) + || !original.selectedOwnerId().equals(sendWitness.get("selected_owner_id", String.class)) + || !Long.valueOf(original.selectedOwnerFence()) + .equals(sendWitness.get("selected_owner_fence", Long.class)) + || !original.candidateDigest().equals(sendWitness.get("candidate_digest", String.class))) + throw new IllegalStateException( + "Controlled execution seed requires the exact positive SQL send witness"); context.execute( "INSERT INTO game_session_original_new_capacity_execution" + " (tenant_id,request_id,admission_id,admission_attempt_id,transition_id,capacity_rearm_fence," diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 73d1f6af2d..bc287f84e5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -528,6 +528,179 @@ void chargedAbsentExecutionCanStillBeFencedWhenEitherBudgetDimensionIsFull( } } + @Test + void unsentChargeCanBeReleasedButPossibleSendNeedsExactAccountDenial() throws Exception { + try (var proof = new TransferSqlProof()) { + var execution = proof.execution; + UUID attemptId = execution.request().admissionAttemptId(); + String retainedIdentity = + proof + .sql + .fetchSingle( + "SELECT (to_jsonb(c) - 'account_send_state' - 'account_unsent_released_at'" + + " - 'account_denial_id')::text FROM game_session_capacity_evidence_charge c" + + " WHERE admission_attempt_id=?", + attemptId) + .get(0, String.class); + assertThat( + proof + .sql + .fetchSingle( + "SELECT account_send_state FROM game_session_capacity_evidence_charge" + + " WHERE admission_attempt_id=?", + attemptId) + .get(0, String.class)) + .isEqualTo("UNCLAIMED"); + + // Controlled SQL proof of the owner-recorded no-send transition; no Account RPC occurs. + assertThat( + proof.sql.execute( + "UPDATE game_session_capacity_evidence_charge" + + " SET account_send_state='RELEASED_UNSENT'" + + " WHERE admission_attempt_id=? AND account_send_state='UNCLAIMED'", + attemptId)) + .isEqualTo(1); + assertThat( + proof + .sql + .fetchSingle( + "SELECT account_send_state,account_unsent_released_at" + + " FROM game_session_capacity_evidence_charge" + + " WHERE admission_attempt_id=?", + attemptId) + .intoMap()) + .containsEntry("account_send_state", "RELEASED_UNSENT") + .satisfies(row -> assertThat(row.get("account_unsent_released_at")).isNotNull()); + assertThat( + proof + .sql + .fetchSingle( + "SELECT (to_jsonb(c) - 'account_send_state' - 'account_unsent_released_at'" + + " - 'account_denial_id')::text FROM game_session_capacity_evidence_charge c" + + " WHERE admission_attempt_id=?", + attemptId) + .get(0, String.class)) + .isEqualTo(retainedIdentity); + assertThat(proof.physicalExecutionExists(execution)).isFalse(); + + var selected = + new CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner( + execution.selectedOwnerId(), execution.selectedOwnerFence()); + assertThat( + proof + .capacity(proof.sql) + .authorizeAccountSend( + proof.admission, execution.request(), selected, transferDeadline())) + .isEqualTo( + net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient.SendDisposition + .AUTHORIZE_NEW); + assertThat( + proof + .sql + .fetchSingle( + "SELECT account_send_state FROM game_session_capacity_evidence_charge" + + " WHERE admission_attempt_id=?", + attemptId) + .get(0, String.class)) + .isEqualTo("MAY_HAVE_SENT"); + + assertThatThrownBy(() -> + proof.sql.execute( + "UPDATE game_session_capacity_evidence_charge" + + " SET account_send_state='RELEASED_UNSENT'" + + " WHERE admission_attempt_id=?", + attemptId)) + .rootCause() + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getMessage()) + .contains("Invalid capacity evidence send transition"); + }); + assertThat( + proof + .sql + .fetchSingle( + "SELECT (to_jsonb(c) - 'account_send_state' - 'account_unsent_released_at'" + + " - 'account_denial_id')::text FROM game_session_capacity_evidence_charge c" + + " WHERE admission_attempt_id=?", + attemptId) + .get(0, String.class)) + .isEqualTo(retainedIdentity); + assertThat( + proof + .sql + .fetchSingle( + "SELECT account_send_state,account_denial_id" + + " FROM game_session_capacity_evidence_charge WHERE admission_attempt_id=?", + attemptId) + .intoMap()) + .containsEntry("account_send_state", "MAY_HAVE_SENT") + .containsEntry("account_denial_id", null); + + UUID exactDenial = UUID.randomUUID(); + proof.settle(execution, exactDenial); + assertThat( + proof + .sql + .fetchSingle( + "SELECT account_send_state,account_denial_id" + + " FROM game_session_capacity_evidence_charge" + + " WHERE admission_attempt_id=?", + attemptId) + .intoMap()) + .containsEntry("account_send_state", "MAY_HAVE_SENT") + .containsEntry("account_denial_id", exactDenial); + assertThat( + proof + .sql + .fetchSingle( + "SELECT (to_jsonb(c) - 'account_send_state' - 'account_unsent_released_at'" + + " - 'account_denial_id')::text FROM game_session_capacity_evidence_charge c" + + " WHERE admission_attempt_id=?", + attemptId) + .get(0, String.class)) + .isEqualTo(retainedIdentity); + } + } + + @Test + void freshPrechargeReclaimsOneExpiredUnclaimedSlotWithoutTouchingAccount() throws Exception { + try (var proof = new TransferSqlProof(1, 1_048_576L, 3)) { + UUID expiredAttempt = proof.execution.request().admissionAttemptId(); + proof.sql.fetchSingle( + "SELECT pg_sleep(greatest(0,extract(epoch FROM account_send_evidence_expires_at" + + " - clock_timestamp()))) FROM game_session_capacity_evidence_charge" + + " WHERE admission_attempt_id=?", + expiredAttempt); + var fresh = proof.newIndependentControlledOriginExecution(); + proof.precharge(fresh); + assertThat( + proof + .sql + .fetchSingle( + "SELECT account_send_state,account_denial_id,account_unsent_released_at" + + " FROM game_session_capacity_evidence_charge WHERE admission_attempt_id=?", + expiredAttempt) + .intoMap()) + .containsEntry("account_send_state", "RELEASED_UNSENT") + .containsEntry("account_denial_id", null) + .satisfies(row -> assertThat(row.get("account_unsent_released_at")).isNotNull()); + assertThat( + proof + .sql + .fetchSingle( + "SELECT account_send_state FROM game_session_capacity_evidence_charge" + + " WHERE admission_attempt_id=?", + fresh.request().admissionAttemptId()) + .get(0, String.class)) + .isEqualTo("UNCLAIMED"); + assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); + assertThat(proof.physicalExecutionExists(fresh)).isFalse(); + } + } + @Test void retainedDenialReleasesTheLastSlotAndCannotRaceAStoredDispatch() throws Exception { try (var proof = new TransferSqlProof(1, 1_048_576L, 3)) { @@ -546,7 +719,7 @@ void retainedDenialReleasesTheLastSlotAndCannotRaceAStoredDispatch() throws Exce proof.seedUndeliveredDispatch(later); assertThatThrownBy(() -> proof.settle(later, UUID.randomUUID())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining("Execution custody prevents capacity evidence settlement"); + .hasMessageContaining("Execution custody prevents capacity evidence charge changes"); assertThat(proof.executionState(later)).isEqualTo("INSTALL_DISPATCHED"); assertThat(proof.executionState(original)).isNull(); assertThat(proof.physicalExecutionExists(original)).isFalse(); @@ -1590,6 +1763,9 @@ void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throw .hasMessage("Normal region owner transfer is held"); assertThat(proof.currentOwner()).isEqualTo(proof.prior); proof.seedUndeliveredDispatch(proof.execution); + var lateExecution = proof.newControlledExecution(); + proof.retainExactChargeForControlledSeed(lateExecution); + proof.authorizeAccountSend(lateExecution); String original = proof.originalImage(); assertSqlGuard(() -> proof.rawReplaceOwner("unretained-successor", "e".repeat(64))); String forgedOwner = "forged-successor"; @@ -1662,9 +1838,12 @@ void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throw var installed = proof.install(id); String completed = proof.transferImage(id); assertSqlGuard(() -> proof.rawReplaceOwner("different-successor", "f".repeat(64))); - var lateExecution = proof.newControlledExecution(); - proof.retainExactChargeForControlledSeed(lateExecution); - assertThatThrownBy(() -> proof.seedUndeliveredDispatch(lateExecution)) + var newCharge = proof.newControlledExecution(); + assertThatThrownBy(() -> proof.retainExactChargeForControlledSeed(newCharge)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Capacity send boundary requires the exact current selected owner"); + assertThatThrownBy( + () -> proof.insertExecution(proof.sql, lateExecution, "INSTALL_DISPATCHED", null)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Region dispatch requires the exact current selected owner"); assertThat(proof.currentOwner()).isEqualTo(installed); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java index a9676624e2..dcbab59cd5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferSerializationIntegrationTest.java @@ -68,6 +68,10 @@ void ownerInstallUsesFreshReadCommittedSnapshotAfterWaitingForAdvisoryLock( postgresContainer().getUsername(), postgresContainer().getPassword())) { var dispatched = proof.newIndependentControlledOriginExecution(); + if (dispatchWhileWaiting) { + proof.precharge(dispatched); + proof.authorizeAccountSend(dispatched); + } String tag = CanonicalGameplayRegionRedisKeys.tenantRegionTag( proof.scope.tenantId(), proof.scope.gameInstanceId(), proof.scope.regionId()); @@ -151,7 +155,8 @@ public void executeStart(ExecuteContext context) { assertDatabaseWaitsFor(proof.sql, blockerPid); assertThat(installIsolation.get()).isEqualTo(Connection.TRANSACTION_READ_COMMITTED); assertThat(custodyReads.get()).isZero(); - if (dispatchWhileWaiting) proof.seedUndeliveredDispatch(dispatched); + if (dispatchWhileWaiting) + proof.insertExecution(proof.sql, dispatched, "INSTALL_DISPATCHED", null); } finally { blocker.commit(); } @@ -189,6 +194,7 @@ void actualAuthorizationHoldingRegionRowMakesFreezeWaitAndRetainsThatOriginal() ExecutorService executor = Executors.newFixedThreadPool(2)) { var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); Future authorization = executor.submit(() -> proof @@ -229,7 +235,7 @@ void actualAuthorizationHoldingRegionRowMakesFreezeWaitAndRetainsThatOriginal() void denialSettlementRequiresTheCurrentSelectedOwner(boolean ownerReplaced) throws Exception { try (var proof = new TransferSqlProof()) { var original = proof.execution; - proof.precharge(original); + proof.authorizeAccountSend(original); var selected = new CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner( original.selectedOwnerId(), original.selectedOwnerFence()); @@ -298,6 +304,7 @@ void settlementWaitsForUncommittedDispatchAndPreservesItsActiveCharge() throws E try (var proof = new TransferSqlProof(1, 1_048_576L, 3); ExecutorService executor = Executors.newFixedThreadPool(2)) { var original = proof.execution; + proof.authorizeAccountSend(original); var dispatched = new CountDownLatch(1); var release = new CountDownLatch(1); var blockerPid = new AtomicInteger(); @@ -329,7 +336,7 @@ void settlementWaitsForUncommittedDispatchAndPreservesItsActiveCharge() throws E assertThatThrownBy(() -> proof.settle(original, denial)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining( - "Execution custody prevents capacity evidence settlement")); + "Execution custody prevents capacity evidence charge changes")); assertDatabaseWaitsFor(proof.sql, blockerPid.get()); assertThat(settlement.isDone()).isFalse(); release.countDown(); @@ -363,6 +370,7 @@ void actualFreezeUsesReadCommittedWithRepeatableReadDatasourceAfterAuthorization ExecutorService executor = Executors.newFixedThreadPool(2)) { var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); Future authorization = executor.submit(() -> proof @@ -444,6 +452,7 @@ void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch( proof.seedUndeliveredDispatch(seeded); var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); var freezing = proof.transfers(gate.attach(proof.sql)); Future freeze = executor.submit(() -> @@ -479,7 +488,8 @@ void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch( assertThat(proof.executionState(seeded)).isEqualTo("INSTALL_DISPATCHED"); assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); // The INSERT trigger independently takes the same row lock and rejects raw late dispatch. - assertSqlGuard(() -> proof.seedUndeliveredDispatch(proof.execution)); + assertSqlGuard( + () -> proof.insertExecution(proof.sql, proof.execution, "INSTALL_DISPATCHED", null)); List captured = proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); assertThat(captured) @@ -575,6 +585,7 @@ void rawFrozenTransferInsertWaitsForActualDispatchAndRetainsIt() throws Exceptio ExecutorService executor = Executors.newFixedThreadPool(2)) { var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); Future authorization = executor.submit(() -> proof @@ -626,6 +637,7 @@ void rawFrozenTransferInsertWaitsForActualDispatchAndRetainsIt() throws Exceptio @Test void rawFrozenInsertAndCapacityDispatchRejectRepeatableRead() throws Exception { try (var proof = new TransferSqlProof()) { + proof.authorizeAccountSend(proof.execution); assertThatThrownBy(() -> proof.sql.transaction(configuration -> { DSLContext tx = DSL.using(configuration); @@ -800,6 +812,7 @@ void acknowledgedBridgeRetryWaitsBeforeTransitionWhileAuthorizationOwnsRegion() ExecutorService executor = Executors.newFixedThreadPool(2)) { var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); Future authorization = executor.submit(() -> proof diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 762bddf004..8b9280a928 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(25); + assertThat(catalog.catalogEpoch()).isEqualTo(26); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -218,7 +218,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1065.0.13", "catalog-installation:1065.0.14", "catalog-installation:1065.0.15", - "catalog-installation:1065.0.16") + "catalog-installation:1065.0.16", + "catalog-installation:1065.0.17") .noneMatch(identity -> identity.contains(":1057:") || identity.contains(":1058:") @@ -244,7 +245,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1065.0.13:") || identity.contains(":1065.0.14:") || identity.contains(":1065.0.15:") - || identity.contains(":1065.0.16:")); + || identity.contains(":1065.0.16:") + || identity.contains(":1065.0.17:")); assertThat( f.dsl .fetchSingle( @@ -781,7 +783,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(25); + assertThat(original.catalog().catalogEpoch()).isEqualTo(26); assertThat(original.catalog().schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_probe_view")) @@ -939,7 +941,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.13", "1065.0.14", "1065.0.15", - "1065.0.16")) { + "1065.0.16", + "1065.0.17")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -992,7 +995,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.13", "1065.0.14", "1065.0.15", - "1065.0.16")) { + "1065.0.16", + "1065.0.17")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -1989,6 +1993,107 @@ void projectionRepairUpgradePreservesPopulatedCatalogAtEpochTwentyTwo() { } } + @Test + void genuineV1065Point0Point16UpgradeRetainsCatalogAndSealsCapacitySendBoundary() { + try (Fixture f = fixture("1065.0.16")) { + f.populatePredecessor(); + var original = f.owner().capture(request()); + assertThat(original.catalog().catalogEpoch()).isEqualTo(25); + var rowsBefore = f.rows(f.tables()); + rowsBefore.remove(f.history); + rowsBefore.remove(EPOCHS); + var classificationsBefore = f.classificationRows(); + var epochsBefore = + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e ORDER BY catalog_epoch") + .getValues(0, String.class); + var snapshotsBefore = + f.dsl + .fetch( + "SELECT to_jsonb(s)::text||':'||xmin::text FROM " + + SNAPSHOTS + + " s ORDER BY read_request_id") + .getValues(0, String.class); + var historyBefore = f.historyRows(false); + byte[] evidenceBefore = f.evidence(original.request()); + + migration(f.source, f.schema, f.history, "1065.0.17").migrate(); + + assertThat(f.rows(rowsBefore.keySet())).isEqualTo(rowsBefore); + assertThat(f.classificationRows()).isEqualTo(classificationsBefore); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e WHERE catalog_epoch<=25 ORDER BY catalog_epoch") + .getValues(0, String.class)) + .isEqualTo(epochsBefore); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(s)::text||':'||xmin::text FROM " + + SNAPSHOTS + + " s ORDER BY read_request_id") + .getValues(0, String.class)) + .isEqualTo(snapshotsBefore); + assertThat(f.historyRows(false)).hasSize(historyBefore.size() + 1); + assertThat(f.historyRows(false).subList(0, historyBefore.size())).isEqualTo(historyBefore); + var installed = + f.dsl.fetchSingle( + "SELECT count(*),min(type),min(script),bool_and(success) FROM " + + f.history + + " WHERE version='1065.0.17'"); + assertThat(installed.get(0, Long.class)).isEqualTo(1L); + assertThat(installed.get(1, String.class)).isEqualTo("SQL"); + assertThat(installed.get(2, String.class)) + .isEqualTo("V1065.0.17__retain_capacity_send_boundary.sql"); + assertThat(installed.get(3, Boolean.class)).isTrue(); + assertThat(f.evidence(original.request())).isEqualTo(evidenceBefore); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + + assertThat( + f.constraints() + .get( + "game_session_capacity_evidence_budget.gs_capacity_evidence_budget_retained_limit_required")) + .contains("maximum_retained_records IS NOT NULL"); + assertThat(f.indexes().get("gs_capacity_evidence_charge_unclaimed_expiry")) + .contains("account_send_evidence_expires_at"); + var sendStateConstraint = + f.constraints() + .get("game_session_capacity_evidence_charge.gs_capacity_evidence_send_state"); + assertThat(sendStateConstraint) + .contains("account_send_state IS NULL") + .contains("UNCLAIMED") + .contains("MAY_HAVE_SENT") + .contains("RELEASED_UNSENT") + .contains("account_unsent_released_at IS NOT NULL"); + assertThat(f.indexes().get("gs_capacity_evidence_charge_active")) + .contains("account_send_state IS DISTINCT FROM 'RELEASED_UNSENT'"); + assertThat(f.routines().get("settle_gs_capacity_evidence_charge()")) + .contains( + "OLD.account_send_state='UNCLAIMED' AND NEW.account_send_state='RELEASED_UNSENT'") + .contains("Execution custody prevents capacity evidence charge changes"); + + var current = f.owner().capture(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(26); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes=gs_runtime_family_catalog_bytes(26) FROM " + + EPOCHS + + " WHERE catalog_epoch=26") + .get(0, Boolean.class)) + .isTrue(); + migration(f.source, f.schema, f.history, "1065.0.17").validate(); + } + } + private static void assertCapacityCatalogGuardUpgrade( Fixture f, String target, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java index 923bcd9d8c..9dd6f02752 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java @@ -610,9 +610,9 @@ void timelineInitializationUsesPreparedPermitWhileOtherBackgroundSlotIsOccupied( "controlled-image"); var permitConstructor = CanonicalGameplayRegionRuntimeStatusRepository.InitialInitializationPermit.class - .getDeclaredConstructor(UUID.class, String.class); + .getDeclaredConstructor(UUID.class, String.class, long.class); permitConstructor.setAccessible(true); - var permit = permitConstructor.newInstance(operationId, sourceDigest); + var permit = permitConstructor.newInstance(operationId, sourceDigest, 1L); long handoffDeadline = CLOCK.millis() + 4000; Semaphore operations = (Semaphore) From 271192ada970641262656c5472b8254edc8a130e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 06:23:09 +1300 Subject: [PATCH 41/51] Bind transfer receipts and repair capacity CI fixtures --- .../game-session-service/runtime-and-data.md | 2 + ...untRuntimeStubServerCompatibilityTest.java | 14 +- ..._exact_region_transfer_receipt_custody.sql | 209 +++++++++++++++ ...onHandoffLeaseDeadlineIntegrationTest.java | 2 + ...meplayRegionLeaseOwnerIntegrationTest.java | 248 ++++++++++-------- ...ransferCapacityCustodyIntegrationTest.java | 5 + ...eFamilyCatalogPostgresIntegrationTest.java | 38 ++- 7 files changed, 405 insertions(+), 113 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.18__require_exact_region_transfer_receipt_custody.sql 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 9d0c82ef1a..9c53d07a51 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -48,6 +48,8 @@ An observed `COMMITTED` hash is not a transfer exemption: the existing positive An exact retained first-NEW Account-aborted original remains part of the transfer inventory, whether abort preceded capture or completed while the transfer was frozen. Its topology lookup verifies the retained definitive abort and existing immutable mapping without restoring provisional admission authority. First negative closure still requires the complete physical candidate/index proof; already-retained CLOSED replay uses its exact permanent tombstone. Unknown history remains fenced and indeterminate, never discarded because Account or SQL records an abort. +Transfer enrollment verifies the immutable tenant allocation version. The owning SQL transaction retains receipts only for the bound parent incarnation and verifies that any existing dispatch for the exact execution belongs to that incarnation. Completion repeats the custody check against retained evidence. A replacement must advance the executor fence. + A Game Session tenant transfer-history budget bounds retained transfer parents and reserves one slot for each unresolved execution before the freeze commits. Each item slot accounts for both the canonical execution and its fence readback at their maximum size. A transfer with an existing reservation can capture, complete and replay at exhaustion. An insufficient budget refuses a new freeze while preserving predecessor evidence and Account holds. V1065 retains the transfer control and per-original receipt families, their immutable source and completion guards, and the next owner catalog epoch. Their retention hold is not a cleanup horizon. The composition remains manual and unregistered. Controlled signed-source fixtures do not establish operational attestor custody, storage continuity, deployed recovery, runtime activation or player admission. diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index f2a5cded47..71b12ae50d 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -50,7 +50,10 @@ class AccountRuntimeStubServerCompatibilityTest { "VerifyEmailLoginOtp"); // Private capacity RPCs require their actual bounded mTLS owner. private static final Set UNIMPLEMENTED_RUNTIME_METHODS = - Set.of("CommitTenantCapacityAdmission", "ReadTenantCapacityQuotaDenial"); + Set.of( + "CommitTenantCapacityAdmission", + "ReadTenantCapacityQuotaDenial", + "ReadTenantCapacityAdmissionOutcome"); @Test void accountServiceMethodSetIsFullyCategorized() { @@ -75,7 +78,7 @@ void accountServiceMethodSetIsFullyCategorized() { @Test void privateCapacityRpcsRemainUnimplementedOnSharedFakeRuntimeServer() throws Exception { assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) - .doesNotContain("CommitTenantCapacityAdmission", "ReadTenantCapacityQuotaDenial"); + .doesNotContainAnyElementsOf(UNIMPLEMENTED_RUNTIME_METHODS); try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); @@ -94,6 +97,13 @@ void privateCapacityRpcsRemainUnimplementedOnSharedFakeRuntimeServer() throws Ex StatusRuntimeException.class, failure -> assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNIMPLEMENTED)); + assertThatThrownBy(() -> + stub.withDeadlineAfter(2, TimeUnit.SECONDS) + .readTenantCapacityAdmissionOutcome(request)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNIMPLEMENTED)); } finally { channel.shutdownNow(); } diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.18__require_exact_region_transfer_receipt_custody.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.18__require_exact_region_transfer_receipt_custody.sql new file mode 100644 index 0000000000..2ffccda22f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.18__require_exact_region_transfer_receipt_custody.sql @@ -0,0 +1,209 @@ +-- Preserve retained transfer history while strengthening the custody required for new writes. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_gs_region_owner_transfer_item() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE parent game_session_region_owner_transfer%ROWTYPE; +BEGIN + IF TG_OP='DELETE' THEN + RAISE EXCEPTION 'Region transfer item is retained' USING ERRCODE='23514'; + END IF; + IF TG_OP='INSERT' OR NEW.fence_readback IS NOT NULL THEN + SELECT * INTO STRICT parent FROM game_session_region_owner_transfer WHERE transfer_id=NEW.transfer_id FOR UPDATE; + ELSE + SELECT * INTO STRICT parent FROM game_session_region_owner_transfer WHERE transfer_id=NEW.transfer_id; + END IF; + IF parent.state<>'FROZEN' THEN + RAISE EXCEPTION 'Completed transfer cannot acquire or change custody' USING ERRCODE='23514'; + END IF; + -- Advance the parent tuple while holding its lock. A concurrent completion with an older + -- REPEATABLE READ snapshot must fail serialization instead of completing over this child. + IF TG_OP='INSERT' THEN + UPDATE game_session_region_owner_transfer SET state=state + WHERE transfer_id=NEW.transfer_id AND state='FROZEN'; + IF NOT FOUND THEN + RAISE EXCEPTION 'Completed transfer cannot acquire or change custody' USING ERRCODE='23514'; + END IF; + PERFORM 1 FROM game_session_original_new_capacity_execution e + JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=e.transition_id + JOIN game_session_canonical_binding_transition t ON t.transition_id=e.transition_id + JOIN game_session_canonical_tenant_gameplay_tag a ON a.tenant_id=e.tenant_id + WHERE a.tenant_gameplay_tag=NEW.tenant_gameplay_tag AND a.allocation_version=NEW.allocation_version + AND e.execution_digest=NEW.execution_digest AND e.canonical_execution=NEW.canonical_execution + AND e.tenant_gameplay_tag=NEW.tenant_gameplay_tag AND t.original_new_candidate_digest=NEW.candidate_digest + AND b.tenant_id=parent.tenant_id AND b.game_instance_id=parent.game_instance_id AND b.region_id=parent.region_id + AND e.status IN ('INSTALL_DISPATCHED','AUTHORIZED') + FOR SHARE OF e; + IF NOT FOUND THEN + RAISE EXCEPTION 'Transfer item differs from unresolved original region execution or tenant allocation' USING ERRCODE='23514'; + END IF; + END IF; + IF TG_OP='UPDATE' AND ( + ROW(NEW.transfer_id,NEW.target_ordinal,NEW.execution_digest,NEW.canonical_execution,NEW.candidate_digest, + NEW.tenant_gameplay_tag,NEW.workload_namespace,NEW.allocation_version) + IS DISTINCT FROM ROW(OLD.transfer_id,OLD.target_ordinal,OLD.execution_digest,OLD.canonical_execution,OLD.candidate_digest, + OLD.tenant_gameplay_tag,OLD.workload_namespace,OLD.allocation_version) + OR (OLD.fence_readback IS NOT NULL AND ROW(NEW.fence_readback,NEW.incarnation_digest,NEW.before_payload_digest,NEW.after_payload_digest) + IS DISTINCT FROM ROW(OLD.fence_readback,OLD.incarnation_digest,OLD.before_payload_digest,OLD.after_payload_digest)) + OR (OLD.verified_round IS NOT NULL AND NEW.verified_round IS DISTINCT FROM OLD.verified_round)) THEN + RAISE EXCEPTION 'Transfer original and retained fence receipt are immutable' USING ERRCODE='23514'; + END IF; + -- Enrollment and receipt writes share the frozen parent lock with dispatch issuance + -- and completion. Only one transfer for the region can be frozen at a time. + IF NEW.fence_readback IS NOT NULL THEN + IF parent.incarnation_digest IS NULL + OR NEW.incarnation_digest IS DISTINCT FROM parent.incarnation_digest THEN + RAISE EXCEPTION 'Transfer receipt differs from the bound parent incarnation' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_session_region_owner_transfer_item dispatched + WHERE dispatched.execution_digest=NEW.execution_digest AND dispatched.fence_dispatch_id IS NOT NULL + AND dispatched.fence_dispatch_incarnation IS DISTINCT FROM NEW.incarnation_digest + ) THEN + RAISE EXCEPTION 'Transfer receipt differs from the retained dispatch incarnation' USING ERRCODE='23514'; + END IF; + END IF; + IF NEW.verified_round IS NOT NULL AND NEW.verified_round IS DISTINCT FROM parent.verification_round THEN + RAISE EXCEPTION 'Transfer verification round differs from current intent' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION guard_gs_region_owner_transfer() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='DELETE' THEN + RAISE EXCEPTION 'Region owner transfer custody is retained' USING ERRCODE='23514'; + END IF; + IF ROW(NEW.transfer_id,NEW.tenant_id,NEW.game_instance_id,NEW.region_id,NEW.region_epoch, + NEW.old_owner_id,NEW.old_owner_fence,NEW.old_lease_correlation,NEW.source_digest,NEW.intent_digest) + IS DISTINCT FROM ROW(OLD.transfer_id,OLD.tenant_id,OLD.game_instance_id,OLD.region_id,OLD.region_epoch, + OLD.old_owner_id,OLD.old_owner_fence,OLD.old_lease_correlation,OLD.source_digest,OLD.intent_digest) + OR (OLD.state='COMPLETED' AND NEW IS DISTINCT FROM OLD) + OR (OLD.incarnation_digest IS NOT NULL AND NEW.incarnation_digest IS DISTINCT FROM OLD.incarnation_digest) + OR (OLD.verification_round IS NOT NULL AND NEW.verification_round IS DISTINCT FROM OLD.verification_round) + OR NEW.verification_cursor 'read committed' THEN + RAISE EXCEPTION 'Region owner replacement requires READ COMMITTED owner fencing' USING ERRCODE='23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_session_region_owner_transfer t WHERE t.tenant_id=OLD.tenant_id + AND t.game_instance_id=OLD.game_instance_id AND t.region_id=OLD.region_id AND t.state='FROZEN') THEN + RAISE EXCEPTION 'Region transfer must complete with owner installation' USING ERRCODE='23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_session_original_new_capacity_execution e + JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=e.transition_id + WHERE b.tenant_id=OLD.tenant_id AND b.game_instance_id=OLD.game_instance_id AND b.region_id=OLD.region_id + AND e.status IN ('INSTALL_DISPATCHED','AUTHORIZED')) AND NOT EXISTS ( + SELECT 1 FROM game_session_region_owner_transfer t WHERE t.tenant_id=OLD.tenant_id + AND t.game_instance_id=OLD.game_instance_id AND t.region_id=OLD.region_id + AND t.region_epoch=OLD.region_epoch AND t.old_owner_id=OLD.owner_instance_id AND t.old_owner_fence=OLD.executor_fence + AND t.old_lease_correlation=OLD.lease_token_correlation AND t.state='COMPLETED' + AND t.new_owner_id=NEW.owner_instance_id AND t.new_owner_fence=NEW.executor_fence + AND t.new_lease_correlation=NEW.lease_token_correlation AND t.verification_complete + AND OLD.owner_service='game-session-service' AND NEW.owner_service='game-session-service') THEN + RAISE EXCEPTION 'Region owner replacement lacks exact transfer custody' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +-- Runtime-family catalog registration +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1065.0.17' + ) AND ($needle$; + replacement := $replacement$WHERE version='1065.0.17' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.18__require_exact_region_transfer_receipt_custody.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.18' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.17'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.18'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.17','V1065.0.17__retain_capacity_send_boundary.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.18'',''V1065.0.18__require_exact_region_transfer_receipt_custody.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java index a1b33a3577..f773acaf20 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java @@ -338,6 +338,7 @@ public java.sql.Connection getConnection() throws java.sql.SQLException { new CanonicalGameplayOriginalNewCapacityExecutionOwner( stoppingDsl, ownerClient, catalog, CLOCK, tags); var source = inventory.readOriginalNewFinalAdmissionSource(decision); + authorizeKnownAccountSend(source); var accountOpen = controlledAccountOpen(); var issuerOpen = issuerOpen(); try (var credential = @@ -1215,6 +1216,7 @@ private void delayedPredecessorAfterHandoff(boolean installAction) throws Except repairAccountMember(); bridge(!installAction); var source = inventory.readOriginalNewFinalAdmissionSource(decision); + if (installAction) authorizeKnownAccountSend(source); var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); var receiver = new CanonicalGameplayControlledRegionTransferObservationFixture() diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index de6ff702c1..ec7a59179c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1268,65 +1268,72 @@ private void assertOrdinaryCompanionOwnsConnections(boolean inventoryRead) throw var originals = java.util.Collections.synchronizedMap( new java.util.IdentityHashMap()); - var instrumentedProvider = - new org.jooq.ConnectionProvider() { - @Override - public Connection acquire() { - Connection raw = originalProvider.acquire(); - Connection proxy = - (Connection) - java.lang.reflect.Proxy.newProxyInstance( - Connection.class.getClassLoader(), - new Class[] {Connection.class}, - (ignored, method, arguments) -> { - try { - Object value = method.invoke(raw, arguments); - if (value instanceof java.sql.PreparedStatement statement) { - return java.lang.reflect.Proxy.newProxyInstance( - java.sql.PreparedStatement.class.getClassLoader(), - new Class[] {java.sql.PreparedStatement.class}, - (unused, statementMethod, statementArguments) -> { - if (statementMethod.getName().startsWith("execute") - && block.compareAndSet(true, false)) { - entered.countDown(); - boolean done = false; - long stop = - System.nanoTime() + TimeUnit.SECONDS.toNanos(10); - while (!done && System.nanoTime() < stop) { - try { - done = release.await(100, TimeUnit.MILLISECONDS); - } catch (InterruptedException ignoredInterrupt) { - /* blocked provider fixture */ - } - } - if (!done) - throw new AssertionError( - "SQL fixture release not signalled"); - } + class InstrumentedConnectionProvider + implements org.jooq.ConnectionProvider, + CanonicalGameplayOriginalNewCapacityExecutionBudget.ConnectionRetirer { + @Override + public Connection acquire() { + Connection raw = originalProvider.acquire(); + Connection proxy = + (Connection) + java.lang.reflect.Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (ignored, method, arguments) -> { + try { + Object value = method.invoke(raw, arguments); + if (value instanceof java.sql.PreparedStatement statement) { + return java.lang.reflect.Proxy.newProxyInstance( + java.sql.PreparedStatement.class.getClassLoader(), + new Class[] {java.sql.PreparedStatement.class}, + (unused, statementMethod, statementArguments) -> { + if (statementMethod.getName().startsWith("execute") + && block.compareAndSet(true, false)) { + entered.countDown(); + boolean done = false; + long stop = + System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (!done && System.nanoTime() < stop) { try { - return statementMethod.invoke( - statement, statementArguments); - } catch ( - java.lang.reflect.InvocationTargetException error) { - throw error.getCause(); + done = release.await(100, TimeUnit.MILLISECONDS); + } catch (InterruptedException ignoredInterrupt) { + /* blocked provider fixture */ } - }); - } - return value; - } catch (java.lang.reflect.InvocationTargetException error) { - throw error.getCause(); - } - }); - originals.put(proxy, raw); - return proxy; - } + } + if (!done) + throw new AssertionError( + "SQL fixture release not signalled"); + } + try { + return statementMethod.invoke( + statement, statementArguments); + } catch ( + java.lang.reflect.InvocationTargetException error) { + throw error.getCause(); + } + }); + } + return value; + } catch (java.lang.reflect.InvocationTargetException error) { + throw error.getCause(); + } + }); + originals.put(proxy, raw); + return proxy; + } - @Override - public void release(Connection connection) { - releasedConnection.countDown(); - originalProvider.release(originals.remove(connection)); - } - }; + @Override + public void release(Connection connection) { + releasedConnection.countDown(); + originalProvider.release(originals.remove(connection)); + } + + @Override + public void retire(Connection connection) throws java.sql.SQLException { + retireControlledPostgresConnection(originals.get(connection)); + } + } + var instrumentedProvider = new InstrumentedConnectionProvider(); var instrumentedDsl = DSL.using(testSchema.dsl().configuration().derive(instrumentedProvider)); var inventory = new CanonicalGameplayBindingInventoryRepository(instrumentedDsl); @@ -2347,56 +2354,65 @@ void committedClaimCompletionFailureRecoversOnlyAcknowledgedUndispatchedPermit(i redisOwner.requireTimelineAbsent(source, incarnation), NOW); var provider = schema.dsl().configuration().connectionProvider(); - var originals = new java.util.IdentityHashMap(); + var originals = + java.util.Collections.synchronizedMap( + new java.util.IdentityHashMap()); var fault = new java.util.concurrent.atomic.AtomicBoolean(true); var committed = new java.util.concurrent.atomic.AtomicBoolean(); - var failing = - new org.jooq.ConnectionProvider() { - @Override - public Connection acquire() { - Connection raw = provider.acquire(); - Connection wrapped = - (Connection) - java.lang.reflect.Proxy.newProxyInstance( - Connection.class.getClassLoader(), - new Class[] {Connection.class}, - (ignored, method, args) -> { - try { - Object result = method.invoke(raw, args); - if (method.getName().equals("commit")) { - committed.set(true); - if (uncertainCommit && fault.compareAndSet(true, false)) - throw new java.sql.SQLException( - "controlled lost commit acknowledgement"); - } - if (!uncertainCommit - && committed.get() - && method.getName().equals("setAutoCommit") - && Boolean.TRUE.equals(args[0]) - && fault.compareAndSet(true, false)) { - if (lateWorker) { - cleanupEntered.countDown(); - if (!releaseCleanup.await(10, TimeUnit.SECONDS)) - throw new IllegalStateException( - "controlled cleanup release timed out"); - } - throw new java.sql.SQLException( - "controlled post-commit completion failure"); - } - return result; - } catch (java.lang.reflect.InvocationTargetException failure) { - throw failure.getCause(); + class FailingCompletionProvider + implements org.jooq.ConnectionProvider, + CanonicalGameplayOriginalNewCapacityExecutionBudget.ConnectionRetirer { + @Override + public Connection acquire() { + Connection raw = provider.acquire(); + Connection wrapped = + (Connection) + java.lang.reflect.Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (ignored, method, args) -> { + try { + Object result = method.invoke(raw, args); + if (method.getName().equals("commit")) { + committed.set(true); + if (uncertainCommit && fault.compareAndSet(true, false)) + throw new java.sql.SQLException( + "controlled lost commit acknowledgement"); + } + if (!uncertainCommit + && committed.get() + && method.getName().equals("setAutoCommit") + && Boolean.TRUE.equals(args[0]) + && fault.compareAndSet(true, false)) { + if (lateWorker) { + cleanupEntered.countDown(); + if (!releaseCleanup.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException( + "controlled cleanup release timed out"); } - }); - originals.put(wrapped, raw); - return wrapped; - } + throw new java.sql.SQLException( + "controlled post-commit completion failure"); + } + return result; + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + originals.put(wrapped, raw); + return wrapped; + } - @Override - public void release(Connection connection) { - provider.release(originals.remove(connection)); - } - }; + @Override + public void release(Connection connection) { + provider.release(originals.remove(connection)); + } + + @Override + public void retire(Connection connection) throws java.sql.SQLException { + retireControlledPostgresConnection(originals.get(connection)); + } + } + var failing = new FailingCompletionProvider(); var faultRepository = new CanonicalGameplayRegionRuntimeStatusRepository( DSL.using(schema.dsl().configuration().derive(failing))); @@ -2488,9 +2504,20 @@ public void release(Connection connection) { owner.releaseNoWriteRecovery(preparation.operationId(), replacement); assertPreparedTimelineUnchanged(schema.dsl(), repository, redis, source, preparation); var retryPermit = repository.beginInitialTimeline(preparation, NOW).orElseThrow(); - assertThatThrownBy( - () -> repository.releaseInitialTimelineNoWrite(preparation, proof.get(), NOW)) - .isInstanceOf(IllegalStateException.class); + String currentClaim = + "SELECT to_jsonb(p)::text FROM game_session_region_timeline_preparation p" + + " WHERE initialization_operation_id = ?"; + assertThat(retryPermit.claimOrdinal()).isEqualTo(proof.get().claimOrdinal() + 1); + String beforeReplay = + schema.dsl().fetchSingle(currentClaim, preparation.operationId()).get(0, String.class); + repository.releaseInitialTimelineNoWrite(preparation, proof.get(), NOW); + assertThat(proof.get().consumedFor(preparation)).isTrue(); + assertThat( + schema + .dsl() + .fetchSingle(currentClaim, preparation.operationId()) + .get(0, String.class)) + .isEqualTo(beforeReplay); var identity = new RuntimeIdentity( "game-session-service", @@ -4635,5 +4662,16 @@ public void close() { } } + private static void retireControlledPostgresConnection(Connection connection) + throws java.sql.SQLException { + if (connection == null) + throw new java.sql.SQLException("Controlled connection is no longer owned"); + var driver = connection.unwrap(org.postgresql.jdbc.PgConnection.class); + driver.abort(Runnable::run); + if (!driver.isClosed()) { + throw new java.sql.SQLException("Controlled PostgreSQL connection did not close"); + } + } + 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/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index bc287f84e5..3ca1c60e4b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -1141,6 +1141,7 @@ void terminalOnlyTransferRecoversExactCompletedSuccessorAfterOriginalFinalReceip var template = raw.bindCapacityExecution(proof.execution)) { var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); proof .capacity(proof.sql) .authorize( @@ -1438,6 +1439,7 @@ void capturedOriginalThatBecomesTerminalStillRequiresQualifiedTransferCompletion var template = raw.bindCapacityExecution(proof.execution)) { var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); proof .capacity(proof.sql) .authorize( @@ -1528,6 +1530,7 @@ void committedTransferRejectsPhysicalMetadataDrift(String field, String replacem var template = raw.bindCapacityExecution(proof.execution)) { var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); proof .capacity(proof.sql) .authorize( @@ -1900,6 +1903,7 @@ void interruptedFenceRetentionRecoversExactTerminalProofWithoutDispatchingAgain( var template = raw.bindCapacityExecution(proof.execution)) { var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); proof .capacity(proof.sql) .authorize( @@ -1981,6 +1985,7 @@ void interruptedForwardReceiptRecoversExactTerminalProofWithoutReapplying(boolea var template = raw.bindCapacityExecution(proof.execution)) { var account = proof.controlledAccountOpen(); var issuer = proof.issuerOpen(); + proof.authorizeAccountSend(proof.execution); proof .capacity(proof.sql) .authorize( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 8b9280a928..c7f84297e8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(26); + assertThat(catalog.catalogEpoch()).isEqualTo(27); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -219,7 +219,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1065.0.14", "catalog-installation:1065.0.15", "catalog-installation:1065.0.16", - "catalog-installation:1065.0.17") + "catalog-installation:1065.0.17", + "catalog-installation:1065.0.18") .noneMatch(identity -> identity.contains(":1057:") || identity.contains(":1058:") @@ -246,7 +247,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1065.0.14:") || identity.contains(":1065.0.15:") || identity.contains(":1065.0.16:") - || identity.contains(":1065.0.17:")); + || identity.contains(":1065.0.17:") + || identity.contains(":1065.0.18:")); assertThat( f.dsl .fetchSingle( @@ -783,7 +785,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(26); + assertThat(original.catalog().catalogEpoch()).isEqualTo(27); assertThat(original.catalog().schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_probe_view")) @@ -942,7 +944,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.14", "1065.0.15", "1065.0.16", - "1065.0.17")) { + "1065.0.17", + "1065.0.18")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -996,7 +999,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.14", "1065.0.15", "1065.0.16", - "1065.0.17")) { + "1065.0.17", + "1065.0.18")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -2094,6 +2098,28 @@ void genuineV1065Point0Point16UpgradeRetainsCatalogAndSealsCapacitySendBoundary( } } + @Test + void genuineV1065Point0Point17UpgradeRetainsCatalogAndSealsTransferReceiptCustody() { + try (Fixture f = fixture("1065.0.17")) { + assertCapacityCatalogGuardUpgrade( + f, + "1065.0.18", + 26, + "V1065.0.18__require_exact_region_transfer_receipt_custody.sql", + Map.of( + "guard_gs_region_owner_transfer_item()", + List.of( + "a.allocation_version=NEW.allocation_version", + "NEW.incarnation_digest IS DISTINCT FROM parent.incarnation_digest", + "dispatched.fence_dispatch_incarnation IS DISTINCT FROM NEW.incarnation_digest"), + "guard_gs_region_owner_transfer()", + List.of("dispatched.fence_dispatch_incarnation IS DISTINCT FROM i.incarnation_digest"), + "require_gs_region_owner_transfer_custody()", + List.of("NEW.executor_fence <= OLD.executor_fence")), + Map.of()); + } + } + private static void assertCapacityCatalogGuardUpgrade( Fixture f, String target, From ee4f81e1a59b464305a63aa692e46d08010744d7 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 06:52:34 +1300 Subject: [PATCH 42/51] Verify both exact transfer custody refusals --- ...lGameplayRegionLeaseOwnerIntegrationTest.java | 9 +++------ ...onTransferCapacityCustodyIntegrationTest.java | 16 +++++++++++++++- ...timeFamilyCatalogPostgresIntegrationTest.java | 3 ++- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 6003aa408a..0718bfa4a8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1297,8 +1297,7 @@ public Connection acquire() { && block.compareAndSet(true, false)) { entered.countDown(); boolean done = false; - long stop = - System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + long stop = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); while (!done && System.nanoTime() < stop) { try { done = release.await(100, TimeUnit.MILLISECONDS); @@ -1311,10 +1310,8 @@ public Connection acquire() { "SQL fixture release not signalled"); } try { - return statementMethod.invoke( - statement, statementArguments); - } catch ( - java.lang.reflect.InvocationTargetException error) { + return statementMethod.invoke(statement, statementArguments); + } catch (java.lang.reflect.InvocationTargetException error) { throw error.getCause(); } }); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index d076819a7b..58e44a7ed8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -12,6 +12,8 @@ import java.util.List; import java.util.Locale; import java.util.UUID; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; @@ -1696,7 +1698,7 @@ void resumedFenceReceiptCannotChangeDispatchedStorageIncarnation() throws Except id); })) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .hasMessageContaining("gs_region_fence_receipt_dispatch_incarnation"); + .hasMessageContaining("Transfer receipt differs from the bound parent incarnation"); assertThat(proof.itemImage(id)).isEqualTo(dispatched); assertThat(proof.currentOwner()).isEqualTo(proof.prior); assertThat( @@ -1740,6 +1742,18 @@ void terminalTransferCompletionRequiresItsExactInstalledSuccessor() throws Excep proof.scope.gameInstanceId(), proof.scope.regionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Region owner replacement requires an advancing executor fence"); + assertThatThrownBy(() -> + proof.sql.execute( + "UPDATE game_session_region_runtime_status" + + " SET owner_service=?, executor_fence=?" + + " WHERE tenant_id=? AND game_instance_id=? AND region_id=?", + "other-owner-service", + proof.prior.executorFence().longValueExact() + 1, + proof.scope.tenantId(), + proof.scope.gameInstanceId(), + proof.scope.regionId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Region transfer must complete with owner installation"); assertThat(proof.currentOwner()).isEqualTo(proof.prior); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index c7f84297e8..d648f635e0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -2113,7 +2113,8 @@ void genuineV1065Point0Point17UpgradeRetainsCatalogAndSealsTransferReceiptCustod "NEW.incarnation_digest IS DISTINCT FROM parent.incarnation_digest", "dispatched.fence_dispatch_incarnation IS DISTINCT FROM NEW.incarnation_digest"), "guard_gs_region_owner_transfer()", - List.of("dispatched.fence_dispatch_incarnation IS DISTINCT FROM i.incarnation_digest"), + List.of( + "dispatched.fence_dispatch_incarnation IS DISTINCT FROM i.incarnation_digest"), "require_gs_region_owner_transfer_custody()", List.of("NEW.executor_fence <= OLD.executor_fence")), Map.of()); From 24a83521c060f2bdc045b69a749368eba13ec9a6 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 07:00:35 +1300 Subject: [PATCH 43/51] Preserve dependency cache on bounded throttling retries --- .../architecture/system-architecture-cicd.md | 2 +- .../gradle-dependency-recovery-contract.sh | 44 +++++++++++++++++-- .../run-gradle-with-dependency-recovery.sh | 30 ++++++++----- 3 files changed, 62 insertions(+), 14 deletions(-) diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 445b215b40..eb7bffeebd 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -116,7 +116,7 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Runs formatting and lint steps (Spotless, markdownlint, link checks). - On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service and Game Session each use four complete-check partitions, and World Management uses two; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. - Gradle-based Validation and runtime builds, including affected-module checks, controller builds and the source-built Compose boot-jar command, can recover one exact pinned Gradle-wrapper distribution HTTP 429, 500, 502, 503 or 504 failure before any Gradle task starts. The recovery uses only the official Gradle GitHub release-asset API for the same stable version, requires the release asset digest and downloaded bytes to match the repository's SHA-256 pin, checks the exact asset size, and atomically seeds the ordinary wrapper cache without replacing existing bytes. Metadata and asset requests have bounded time/size limits. The unchanged wrapper command then retries once and still verifies/extracts its own archive. No alternate Gradle version, mirror, compiler/test retry or successful runtime claim is introduced; missing, inconsistent, custom-layout, mixed, interrupted or unrecognized evidence retains the original failure. -- Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command with `--refresh-dependencies`; successful commands do not revalidate every dependency. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. +- Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command. A proven HTTP 429 retry uses the existing cache to avoid revalidating unrelated dependencies during throttling. Other recognized cache-resolution failures retry with `--refresh-dependencies`. Successful commands use the restored cache normally. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. - On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service, Game Session, and World Management partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. Account and Game Session validation use disjoint four-partition matrix jobs, World Management uses a two-partition matrix, with remaining modules in a fourth matrix and one shared module-validation recipe. Each service aggregate waits only for its own successful matrix. While unrelated matrix jobs continue uploading artifacts, provenance capture retries whole artifact listings within a fixed bound and accepts only two consecutive identical complete snapshots. Incomplete or shifting pages are discarded; persistent instability or invalid provenance fails closed without publishing a partial snapshot. World partitions balance measured whole-class costs across unit, integration, and cross-service tasks collectively; nested classes stay with their enclosing class, and newly compiled classes receive deterministic assignments. Only partition 1 builds the runtime JAR. Additional runner admission, compilation, and aggregation overhead must be measured before claiming elapsed-time savings. The final Validation Gate requires every selected matrix group and its applicable aggregate; an unaffected group may skip, but a selected skipped, cancelled or failed group cannot pass. - Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account, Game Session, and World Management retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. - Runs the existing module check with Gradle's native `--profile`; Account, Game Session, and World Management partition jobs also profile their existing test-class preparation invocation before class selection. The workflow retains `build/reports/profile/` from the repository root as `gradle-profile----attempt-` for 14 days, including profiles from both invocations when present. These reports expose startup, configuration, dependency and task durations. Profiling does not change the selected checks or recovery behavior; fork concurrency remains controlled by the task configuration above. Missing reports warn rather than supplying timing evidence; cancelled or early-failed runs may not produce a report. Parallel task durations can overlap and must not be summed as elapsed time; JUnit results remain the separate source for individual test costs. diff --git a/dev-tools/tests/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index d8a78b5645..9c173302aa 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -392,6 +392,7 @@ write_jooq_throttled_cause write_jooq_wrapper '' run_case game-logic-service 0 assert_call_count 2 +assert_call 2 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :game-logic-service:check -PfullCheck --profile --info --console=plain" assert_output_contains "refreshed-captured-jooq-resolution" new_case captured-jooq-codegen-mixed-maven-errors @@ -475,7 +476,7 @@ write_annotation_processor_429_cause write_wrapper 'if [[ "$call_count" -eq 1 ]]; then cat "$CASE_DIR/cause.log"; exit 1; fi; echo refreshed-annotation-processors; exit 0' run_case common-platform-core 0 assert_call_count 2 -assert_call 2 "--refresh-dependencies --max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :common-platform-core:check -PfullCheck --profile --info --console=plain" +assert_call 2 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :common-platform-core:check -PfullCheck --profile --info --console=plain" assert_rate_limit_delay for mutation in auth wrong-origin wrong-artifact truncated-chain extra-coordinate compile-started; do @@ -523,6 +524,7 @@ write_compile_classpath_429_cause write_wrapper 'if [[ "$call_count" -eq 1 ]]; then cat "$CASE_DIR/cause.log"; exit 1; fi; echo refreshed-compile-classpath; exit 0' run_case account-service 0 assert_call_count 2 +assert_call 2 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :account-service:check -PfullCheck --profile --info --console=plain" assert_rate_limit_delay assert_output_contains "refreshed-compile-classpath" @@ -540,6 +542,41 @@ for mutation in auth wrong-module compile-started; do assert_no_retry done +# A same-module cross-service test source set has its own compile classpath; +# qualify its JavaCompile boundary without accepting a neighboring config. +write_cross_service_test_429_cause() { + cat > "$CASE_DIR/cause.log" <<'LOG' +FAILURE: Build failed with an exception. +* What went wrong: +Configuration cache state could not be cached: field `classpath` of task `:world-management-service:compileCrossServiceTestJava` of type `org.gradle.api.tasks.compile.JavaCompile`: error writing value of type 'org.gradle.api.internal.artifacts.configurations.DefaultResolvableConfiguration' +> Could not resolve all files for configuration ':world-management-service:crossServiceTestCompileClasspath'. + > Could not download spring-boot-4.2.0.jar (org.springframework.boot:spring-boot:4.2.0) + > Could not get resource 'https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot/4.2.0/spring-boot-4.2.0.jar'. + > Could not GET 'https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot/4.2.0/spring-boot-4.2.0.jar'. + > Received status code 429 from server: Too Many Requests +* Try: +> Run with --stacktrace option for the stack trace. +LOG +} + +new_case cross-service-test-classpath-maven-429 +write_cross_service_test_429_cause +# shellcheck disable=SC2016 +write_wrapper 'if [[ "$call_count" -eq 1 ]]; then cat "$CASE_DIR/cause.log"; exit 1; fi; echo refreshed-cross-service-test-classpath; exit 0' +run_case world-management-service 0 +assert_call_count 2 +assert_call 2 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :world-management-service:check -PfullCheck --profile --info --console=plain" +assert_rate_limit_delay +assert_output_contains "refreshed-cross-service-test-classpath" + +new_case cross-service-test-classpath-maven-429-wrong-configuration +write_cross_service_test_429_cause +sed -i 's/:world-management-service:crossServiceTestCompileClasspath/:world-management-service:testCompileClasspath/' "$CASE_DIR/cause.log" +# shellcheck disable=SC2016 +write_wrapper 'cat "$CASE_DIR/cause.log"; exit 1' +run_case world-management-service 1 +assert_no_retry + # The common-test-support failure carries multiple Maven Central JAR chains # under one test fixtures classpath root, before any fixture compilation. write_test_fixtures_429_cause() { @@ -587,7 +624,7 @@ for retry_after in absent 08; do run_case common-test-support 0 assert_call_count 2 assert_call 1 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :common-test-support:check -PfullCheck --profile --info --console=plain" - assert_call 2 "--refresh-dependencies --max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :common-test-support:check -PfullCheck --profile --info --console=plain" + assert_call 2 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :common-test-support:check -PfullCheck --profile --info --console=plain" if [[ "$retry_after" == absent ]]; then assert_rate_limit_delay else @@ -933,6 +970,7 @@ fi echo "refreshed-http-429-resolved"; exit 0' run_case common-web-support 0 assert_call_count 2 +assert_call 2 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :common-web-support:check -PfullCheck --profile --info --console=plain" [[ "$(cat "$CASE_DIR/sleeps")" == 5 ]] || fail "HTTP 429 did not observe Retry-After" # Retain the PR 3220 buildSrc configuration failure, including the plugin @@ -985,7 +1023,7 @@ write_buildsrc_wrapper run_case logging-admin-service 0 assert_call_count 2 assert_call 1 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :logging-admin-service:check -PfullCheck --profile --info --console=plain" -assert_call 2 "--refresh-dependencies --max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :logging-admin-service:check -PfullCheck --profile --info --console=plain" +assert_call 2 "--max-workers=2 -Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8 :logging-admin-service:check -PfullCheck --profile --info --console=plain" assert_rate_limit_delay assert_output_contains "buildsrc-refresh-result" diff --git a/dev-tools/validation/run-gradle-with-dependency-recovery.sh b/dev-tools/validation/run-gradle-with-dependency-recovery.sh index d0c3b66ee6..d6f3a82b1b 100644 --- a/dev-tools/validation/run-gradle-with-dependency-recovery.sh +++ b/dev-tools/validation/run-gradle-with-dependency-recovery.sh @@ -25,12 +25,12 @@ if ! TEMP_DIR="$(mktemp -d "${TEMP_ROOT%/}/firemud-gradle-check.XXXXXX")"; then fi readonly TEMP_DIR readonly NORMAL_LOG="$TEMP_DIR/normal.log" -readonly REFRESH_LOG="$TEMP_DIR/refresh.log" +readonly RETRY_LOG="$TEMP_DIR/retry.log" # Invoked indirectly by the EXIT trap below. # shellcheck disable=SC2329 cleanup() { - rm -f -- "$NORMAL_LOG" "$REFRESH_LOG" + rm -f -- "$NORMAL_LOG" "$RETRY_LOG" rmdir -- "$TEMP_DIR" } trap cleanup EXIT @@ -300,15 +300,16 @@ classify_failure_body() { cache_cause++ next } - # Gradle 9.9 can surface compileClasspath downloads while serializing - # JavaCompile.classpath. Admit only this typed, same-module wrapper. - if (line ~ /^Configuration cache state could not be cached: field `classpath` of task `:[[:alnum:]-]+:compileJava` of type `org\.gradle\.api\.tasks\.compile\.JavaCompile`: error writing value of type \047org\.gradle\.api\.internal\.artifacts\.configurations\.DefaultResolvableConfiguration\047$/) { + # Gradle 9.9 can resolve main or cross-service classpaths while + # serializing JavaCompile.classpath. Match the exact task and source set. + if (line ~ /^Configuration cache state could not be cached: field `classpath` of task `:[[:alnum:]-]+:compile(Java|CrossServiceTestJava)` of type `org\.gradle\.api\.tasks\.compile\.JavaCompile`: error writing value of type \047org\.gradle\.api\.internal\.artifacts\.configurations\.DefaultResolvableConfiguration\047$/) { module = line sub(/^.* of task `/, "", module) - sub(/:compileJava`.*$/, "", module) + cross_service = module ~ /:compileCrossServiceTestJava`/ + sub(/:compile(Java|CrossServiceTestJava)`.*$/, "", module) if (compile_classpath_module != "" && compile_classpath_module != module) invalid++ compile_classpath_module = module - expected_compile_configuration = module ":compileClasspath" + expected_compile_configuration = module (cross_service ? ":crossServiceTestCompileClasspath" : ":compileClasspath") compile_classpath_wrapper++ next } @@ -780,7 +781,7 @@ fi if recover_wrapper_distribution; then echo "Recovered the pinned wrapper distribution before task execution; retrying the original Gradle command once." - run_gradle_check false "$REFRESH_LOG" + run_gradle_check false "$RETRY_LOG" exit "$GRADLE_EXIT" fi @@ -792,7 +793,16 @@ if ! RETRY_DELAY="$(retry_delay_seconds "$NORMAL_LOG")"; then exit "$GRADLE_EXIT" fi -echo "Recognized Gradle dependency-resolution failure at the bounded pre-substantive boundary; retrying the complete Gradle command once with dependency metadata refresh after ${RETRY_DELAY}s." +# Revalidating the whole cache in a throttled build adds requests to both the +# affected repository and unrelated repositories needed during configuration. +retry_refresh=true +retry_description="with dependency metadata refresh" +if failure_body "$NORMAL_LOG" | grep -E '^[[:space:]]*(> )?Received status code 429 from server: Too Many Requests$' >/dev/null; then + retry_refresh=false + retry_description="with cached dependency metadata" +fi + +echo "Recognized Gradle dependency-resolution failure at the bounded pre-substantive boundary; retrying the complete Gradle command once $retry_description after ${RETRY_DELAY}s." sleep "$RETRY_DELAY" -run_gradle_check true "$REFRESH_LOG" +run_gradle_check "$retry_refresh" "$RETRY_LOG" exit "$GRADLE_EXIT" From 650fe4936d06eaf05255b8bc9300d6144266ab2e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 07:20:30 +1300 Subject: [PATCH 44/51] Bind transfer custody to the exact bridge workload namespace --- .../game-session-service/runtime-and-data.md | 2 +- ...ind_region_transfer_workload_namespace.sql | 180 ++++++++++++++++++ ...iginalNewRegionHandoffIntegrationTest.java | 16 ++ ...eFamilyCatalogPostgresIntegrationTest.java | 33 +++- 4 files changed, 224 insertions(+), 7 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.19__bind_region_transfer_workload_namespace.sql 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 85ba695bbc..2e151305b6 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -48,7 +48,7 @@ An observed `COMMITTED` hash is not a transfer exemption: the existing positive An exact retained first-NEW Account-aborted original remains part of the transfer inventory, whether abort preceded capture or completed while the transfer was frozen. Its topology lookup verifies the retained definitive abort and existing immutable mapping without restoring provisional admission authority. First negative closure still requires the complete physical candidate/index proof; already-retained CLOSED replay uses its exact permanent tombstone. Unknown history remains fenced and indeterminate, never discarded because Account or SQL records an abort. -Transfer enrollment verifies the immutable tenant allocation version. The owning SQL transaction retains receipts only for the bound parent incarnation and verifies that any existing dispatch for the exact execution belongs to that incarnation. Completion repeats the custody check against retained evidence. A replacement must advance the executor fence. +Transfer enrollment verifies the immutable tenant allocation version and binds the item to the exact bridge obligation's workload namespace. Completion verifies that namespace again for every captured item. The owning SQL transaction retains receipts only for the bound parent incarnation and verifies that any existing dispatch for the exact execution belongs to that incarnation. Completion repeats the custody check against retained evidence. A replacement must advance the executor fence. A Game Session tenant transfer-history budget bounds retained transfer parents and reserves one slot for each unresolved execution before the freeze commits. Each item slot accounts for both the canonical execution and its fence readback at their maximum size. A transfer with an existing reservation can capture, complete and replay at exhaustion. An insufficient budget refuses a new freeze while preserving predecessor evidence and Account holds. diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.19__bind_region_transfer_workload_namespace.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.19__bind_region_transfer_workload_namespace.sql new file mode 100644 index 0000000000..970358c4a8 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.19__bind_region_transfer_workload_namespace.sql @@ -0,0 +1,180 @@ +-- Bind each transfer item to the workload namespace of its exact bridge obligation. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_gs_region_owner_transfer_item() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE parent game_session_region_owner_transfer%ROWTYPE; +BEGIN + IF TG_OP='DELETE' THEN + RAISE EXCEPTION 'Region transfer item is retained' USING ERRCODE='23514'; + END IF; + IF TG_OP='INSERT' OR NEW.fence_readback IS NOT NULL THEN + SELECT * INTO STRICT parent FROM game_session_region_owner_transfer WHERE transfer_id=NEW.transfer_id FOR UPDATE; + ELSE + SELECT * INTO STRICT parent FROM game_session_region_owner_transfer WHERE transfer_id=NEW.transfer_id; + END IF; + IF parent.state<>'FROZEN' THEN + RAISE EXCEPTION 'Completed transfer cannot acquire or change custody' USING ERRCODE='23514'; + END IF; + -- Advance the parent tuple while holding its lock. A concurrent completion with an older + -- REPEATABLE READ snapshot must fail serialization instead of completing over this child. + IF TG_OP='INSERT' THEN + UPDATE game_session_region_owner_transfer SET state=state + WHERE transfer_id=NEW.transfer_id AND state='FROZEN'; + IF NOT FOUND THEN + RAISE EXCEPTION 'Completed transfer cannot acquire or change custody' USING ERRCODE='23514'; + END IF; + PERFORM 1 FROM game_session_original_new_capacity_execution e + JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=e.transition_id + JOIN game_session_canonical_binding_transition t ON t.transition_id=e.transition_id + JOIN game_session_canonical_tenant_gameplay_tag a ON a.tenant_id=e.tenant_id + WHERE a.tenant_gameplay_tag=NEW.tenant_gameplay_tag AND a.allocation_version=NEW.allocation_version + AND e.execution_digest=NEW.execution_digest AND e.canonical_execution=NEW.canonical_execution + AND e.tenant_gameplay_tag=NEW.tenant_gameplay_tag AND t.original_new_candidate_digest=NEW.candidate_digest + AND b.tenant_id=parent.tenant_id AND b.game_instance_id=parent.game_instance_id AND b.region_id=parent.region_id + AND b.entity_workload_namespace=NEW.workload_namespace + AND e.status IN ('INSTALL_DISPATCHED','AUTHORIZED') + FOR SHARE OF e; + IF NOT FOUND THEN + RAISE EXCEPTION 'Transfer item differs from unresolved original region execution or tenant allocation' USING ERRCODE='23514'; + END IF; + END IF; + IF TG_OP='UPDATE' AND ( + ROW(NEW.transfer_id,NEW.target_ordinal,NEW.execution_digest,NEW.canonical_execution,NEW.candidate_digest, + NEW.tenant_gameplay_tag,NEW.workload_namespace,NEW.allocation_version) + IS DISTINCT FROM ROW(OLD.transfer_id,OLD.target_ordinal,OLD.execution_digest,OLD.canonical_execution,OLD.candidate_digest, + OLD.tenant_gameplay_tag,OLD.workload_namespace,OLD.allocation_version) + OR (OLD.fence_readback IS NOT NULL AND ROW(NEW.fence_readback,NEW.incarnation_digest,NEW.before_payload_digest,NEW.after_payload_digest) + IS DISTINCT FROM ROW(OLD.fence_readback,OLD.incarnation_digest,OLD.before_payload_digest,OLD.after_payload_digest)) + OR (OLD.verified_round IS NOT NULL AND NEW.verified_round IS DISTINCT FROM OLD.verified_round)) THEN + RAISE EXCEPTION 'Transfer original and retained fence receipt are immutable' USING ERRCODE='23514'; + END IF; + -- Enrollment and receipt writes share the frozen parent lock with dispatch issuance + -- and completion. Only one transfer for the region can be frozen at a time. + IF NEW.fence_readback IS NOT NULL THEN + IF parent.incarnation_digest IS NULL + OR NEW.incarnation_digest IS DISTINCT FROM parent.incarnation_digest THEN + RAISE EXCEPTION 'Transfer receipt differs from the bound parent incarnation' USING ERRCODE='23514'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_session_region_owner_transfer_item dispatched + WHERE dispatched.execution_digest=NEW.execution_digest AND dispatched.fence_dispatch_id IS NOT NULL + AND dispatched.fence_dispatch_incarnation IS DISTINCT FROM NEW.incarnation_digest + ) THEN + RAISE EXCEPTION 'Transfer receipt differs from the retained dispatch incarnation' USING ERRCODE='23514'; + END IF; + END IF; + IF NEW.verified_round IS NOT NULL AND NEW.verified_round IS DISTINCT FROM parent.verification_round THEN + RAISE EXCEPTION 'Transfer verification round differs from current intent' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION guard_gs_region_owner_transfer() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='DELETE' THEN + RAISE EXCEPTION 'Region owner transfer custody is retained' USING ERRCODE='23514'; + END IF; + IF ROW(NEW.transfer_id,NEW.tenant_id,NEW.game_instance_id,NEW.region_id,NEW.region_epoch, + NEW.old_owner_id,NEW.old_owner_fence,NEW.old_lease_correlation,NEW.source_digest,NEW.intent_digest) + IS DISTINCT FROM ROW(OLD.transfer_id,OLD.tenant_id,OLD.game_instance_id,OLD.region_id,OLD.region_epoch, + OLD.old_owner_id,OLD.old_owner_fence,OLD.old_lease_correlation,OLD.source_digest,OLD.intent_digest) + OR (OLD.state='COMPLETED' AND NEW IS DISTINCT FROM OLD) + OR (OLD.incarnation_digest IS NOT NULL AND NEW.incarnation_digest IS DISTINCT FROM OLD.incarnation_digest) + OR (OLD.verification_round IS NOT NULL AND NEW.verification_round IS DISTINCT FROM OLD.verification_round) + OR NEW.verification_cursor1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.18'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.19'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.18','V1065.0.18__require_exact_region_transfer_receipt_custody.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.19'',''V1065.0.19__bind_region_transfer_workload_namespace.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java index 5f616f035f..3d59d27b23 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffIntegrationTest.java @@ -210,6 +210,22 @@ void authorizedUnknownHandoffKeepsOriginalCandidateAndRefusesCompletedMutation() deadline()); var completed = receiver.observeForRegionOwnerTransfer(transferId, 0, deadline()); assertThat(completed.regionOwnerTransferContext().controlState()).isEqualTo("COMPLETED"); + var namespaceCustody = + fixture + .dsl() + .fetchSingle( + "SELECT i.workload_namespace, b.entity_workload_namespace" + + " FROM game_session_region_owner_transfer_item i" + + " JOIN game_session_original_new_capacity_execution e" + + " ON e.execution_digest=i.execution_digest" + + " JOIN game_session_canonical_binding_region_bridge_obligation b" + + " ON b.transition_id=e.transition_id" + + " WHERE i.transfer_id=? AND b.transition_id=?", + transferId, + original.transitionId); + assertThat(namespaceCustody.get("workload_namespace", String.class)) + .isNotBlank() + .isEqualTo(namespaceCustody.get("entity_workload_namespace", String.class)); assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(candidate); assertThatThrownBy( () -> repository.within(deadline(), ignored -> repository.capture(transferId))) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index d648f635e0..c4e19e8a5d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(27); + assertThat(catalog.catalogEpoch()).isEqualTo(28); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -220,7 +220,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1065.0.15", "catalog-installation:1065.0.16", "catalog-installation:1065.0.17", - "catalog-installation:1065.0.18") + "catalog-installation:1065.0.18", + "catalog-installation:1065.0.19") .noneMatch(identity -> identity.contains(":1057:") || identity.contains(":1058:") @@ -248,7 +249,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1065.0.15:") || identity.contains(":1065.0.16:") || identity.contains(":1065.0.17:") - || identity.contains(":1065.0.18:")); + || identity.contains(":1065.0.18:") + || identity.contains(":1065.0.19:")); assertThat( f.dsl .fetchSingle( @@ -785,7 +787,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(27); + assertThat(original.catalog().catalogEpoch()).isEqualTo(28); assertThat(original.catalog().schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_probe_view")) @@ -945,7 +947,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.15", "1065.0.16", "1065.0.17", - "1065.0.18")) { + "1065.0.18", + "1065.0.19")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -1000,7 +1003,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.15", "1065.0.16", "1065.0.17", - "1065.0.18")) { + "1065.0.18", + "1065.0.19")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -2121,6 +2125,23 @@ void genuineV1065Point0Point17UpgradeRetainsCatalogAndSealsTransferReceiptCustod } } + @Test + void genuineV1065Point0Point18UpgradeRetainsCatalogAndSealsTransferNamespaceCustody() { + try (Fixture f = fixture("1065.0.18")) { + assertCapacityCatalogGuardUpgrade( + f, + "1065.0.19", + 27, + "V1065.0.19__bind_region_transfer_workload_namespace.sql", + Map.of( + "guard_gs_region_owner_transfer_item()", + List.of("b.entity_workload_namespace=NEW.workload_namespace"), + "guard_gs_region_owner_transfer()", + List.of("i.workload_namespace IS DISTINCT FROM b.entity_workload_namespace")), + Map.of()); + } + } + private static void assertCapacityCatalogGuardUpgrade( Fixture f, String target, From 5d619ba463ec4abf3bedb36e0c1be84709a572d9 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 08:20:56 +1300 Subject: [PATCH 45/51] Exercise the receiving capacity send and budget guards in integration fixtures --- ...OriginalNewCapacityExecutionOwnerIntegrationTest.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java index 9463afd108..d41adf281e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwnerIntegrationTest.java @@ -71,6 +71,7 @@ GenericContainer redisContainer() { void committedCapacityWithoutExecutionCustodyRemainsIndeterminate() throws Exception { repairAccountMember(); bridge(false); + authorizeKnownAccountSend(inventory.readOriginalNewFinalAdmissionSource(decision)); var before = physicalImage(); assertThat( fixture @@ -428,10 +429,12 @@ void lastPrechargedCapacityEvidenceSlotSurvivesFullBudgetAndSameAttemptReplay( "INSERT INTO game_session_capacity_evidence_charge" + " (admission_attempt_id, tenant_id, request_id, admission_id," + " capacity_rearm_fence, mutation_digest, candidate_digest," - + " selected_owner_id, selected_owner_fence, reserved_binding_bytes)" + + " selected_owner_id, selected_owner_fence, reserved_binding_bytes," + + " account_send_state, account_send_evidence_expires_at)" + " SELECT ?, tenant_id, ?, admission_id, capacity_rearm_fence," + " mutation_digest, candidate_digest, selected_owner_id," - + " selected_owner_fence, reserved_binding_bytes" + + " selected_owner_fence, reserved_binding_bytes," + + " 'UNCLAIMED', clock_timestamp() + INTERVAL '5 seconds'" + " FROM game_session_capacity_evidence_charge" + " WHERE admission_attempt_id = ?", distinctAttempt, @@ -697,6 +700,7 @@ void boundCapacityTemplateFinalizesWhileExecutionRemainsAuthorized() throws Exce repairAccountMember(); bridge(false); var source = inventory.readOriginalNewFinalAdmissionSource(decision); + authorizeKnownAccountSend(source); try (var credential = new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); var raw = credential.template(); @@ -727,6 +731,7 @@ void recreatedCapacityOwnerClosesExactAttemptAndRejectsDelayedFinalCas() throws repairAccountMember(); bridge(false); var source = inventory.readOriginalNewFinalAdmissionSource(decision); + authorizeKnownAccountSend(source); try (var credential = new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); var raw = credential.template(); From c6ff8571c23fe291ffb18cc5066d883f72249a46 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Fri, 27 Nov 2026 17:13:33 +1300 Subject: [PATCH 46/51] Qualify renewed lease expiry at final installation --- ...gionHandoffLeaseDeadlineIntegrationTest.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java index f773acaf20..288b1e94e4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffLeaseDeadlineIntegrationTest.java @@ -263,17 +263,18 @@ public void executeEnd(org.jooq.ExecuteContext context) { .when(transfer) .withStatusRepository( org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.any()); + // Use a grant shorter than the handoff budget to exercise expiry inside the final SQL scope. var owner = - CanonicalGameplayRegionLeaseOwnerFactory.compose( - successorSql, - ownerClient, - ownerUri, - catalog, + new CanonicalGameplayRegionLeaseOwner( + new CanonicalGameplayBindingInventoryRepository(successorSql), + new CanonicalGameplayRegionRuntimeStatusRepository(successorSql), + new CanonicalGameplayRegionLeaseRedisOwner(ownerClient, ownerUri, catalog), scope -> original.incarnation, sources.resolver, deadlineTestIdentity("empty-advance-final-sql"), leaseTtl, - time); + time, + true); long originalFenceSequence = fixture .dsl() @@ -283,7 +284,9 @@ public void executeEnd(org.jooq.ExecuteContext context) { assertThatThrownBy(() -> owner.installForTransition( null, original.transitionId, original.worldRequest, transfer, handoffDeadline)) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(CanonicalGameplayRegionLeaseOwner.TransferCompletionUnconfirmed.class) + .hasRootCauseInstanceOf( + CanonicalGameplayOriginalNewCapacityExecutionBudget.BudgetUnavailable.class); assertThat(finalLockReached).isTrue(); assertThat(installBudget).hasValue(renewedDeadline); assertThat(wall.get()).isLessThan(handoffDeadline); From b8bca591a82a367357141181c812ab4b2191d6bd Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 09:15:04 +1300 Subject: [PATCH 47/51] Hold the region transfer readback connection through installation --- ...ameplayRegionOwnerTransferCoordinator.java | 85 ++++++++++--------- ...ransferCapacityCustodyIntegrationTest.java | 34 ++++++-- 2 files changed, 73 insertions(+), 46 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java index 854190c852..80d2abea7d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import org.jooq.DSLContext; @@ -154,12 +155,12 @@ CanonicalGameplayRegionRuntimeStatus install( ownerInstanceId, clock.instant()); } - var before = observe(first.getFirst(), budget); var owner = capacity.forTransferBudget(budget); - // Stream the entire frozen inventory through bounded pages under this one absolute - // operation budget. Earlier page receipts cannot hide a subsequently lost marker. - // An inventory that cannot be currently proved inside the deadline stays frozen. + var verifiedInstallation = new AtomicReference(); owner.withTransferReadback(reader -> { + var before = observe(first.getFirst(), budget); + // Keep one authenticated non-reconnecting connection through the full inventory + // check, SQL commit and completed readback. var page = first; while (!page.isEmpty()) { budget.check(); @@ -169,31 +170,32 @@ CanonicalGameplayRegionRuntimeStatus install( } page = repository.page(transferId, page.getLast().ordinal()); } + var after = observe(first.getFirst(), budget); + var proof = + repository.qualify(transferId, before, after, budget.absoluteDeadlineMillis()); + var installed = + new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) + .installOwner( + source, + prior.regionEpoch(), + prior, + leaseCorrelation, + ownerService, + ownerInstanceId, + clock.instant(), + proof); + // Completion grants no historical-fence exemption. Recheck the exact committed + // successor and every retained marker before returning a serving capability. + var completed = + repository.completedSuccessor(transferId, ownerInstanceId, leaseCorrelation); + if (!installed.equals(completed.status()) + || !after.incarnationDigest().equals(completed.incarnationDigest())) throw held(); + var completedFirst = repository.completedPage(transferId, -1); + if (completedFirst.isEmpty()) throw held(); + requireCompletedInventory(transferId, completed, completedFirst, budget, reader); + verifiedInstallation.set(installed); }); - var after = observe(first.getFirst(), budget); - var proof = - repository.qualify(transferId, before, after, budget.absoluteDeadlineMillis()); - var installed = - new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) - .installOwner( - source, - prior.regionEpoch(), - prior, - leaseCorrelation, - ownerService, - ownerInstanceId, - clock.instant(), - proof); - // Completion grants no historical-fence exemption. Recheck the exact committed - // successor and every retained marker before returning a serving capability. - var completed = - repository.completedSuccessor(transferId, ownerInstanceId, leaseCorrelation); - if (!installed.equals(completed.status()) - || !after.incarnationDigest().equals(completed.incarnationDigest())) throw held(); - var completedFirst = repository.completedPage(transferId, -1); - if (completedFirst.isEmpty()) throw held(); - requireCompletedInventory(transferId, completed, completedFirst, budget); - return installed; + return verifiedInstallation.get(); }); } @@ -209,7 +211,10 @@ CanonicalGameplayRegionRuntimeStatus recoverCompleted( repository.requireTerminalOnlyCompletion(transferId, completed); return completed.status(); } - requireCompletedInventory(transferId, completed, firstPage, budget); + capacity + .forTransferBudget(budget) + .withTransferReadback(reader -> + requireCompletedInventory(transferId, completed, firstPage, budget, reader)); return completed.status(); }); } @@ -219,22 +224,20 @@ private void requireCompletedInventory( UUID transferId, CanonicalGameplayRegionOwnerTransferRepository.CompletedTransfer completed, List firstPage, - CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + CanonicalGameplayOriginalNewCapacityExecutionBudget budget, + CanonicalGameplayOriginalNewCapacityExecutionOwner reader) { var first = firstPage.getFirst(); var before = observe(first, budget); if (!before.incarnationDigest().equals(completed.incarnationDigest())) throw held(); - var owner = capacity.forTransferBudget(budget); - owner.withTransferReadback(reader -> { - var page = firstPage; - while (!page.isEmpty()) { - for (var item : page) { - budget.check(); - repository.requireRetainedPhysical( - item, reader.readTransferFence(item, budget.absoluteDeadlineMillis())); - } - page = repository.completedPage(transferId, page.getLast().ordinal()); + var page = firstPage; + while (!page.isEmpty()) { + for (var item : page) { + budget.check(); + repository.requireRetainedPhysical( + item, reader.readTransferFence(item, budget.absoluteDeadlineMillis())); } - }); + page = repository.completedPage(transferId, page.getLast().ordinal()); + } var after = observe(first, budget); if (!after.incarnationDigest().equals(completed.incarnationDigest()) || !completed.equals( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 58e44a7ed8..328bfd6b76 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -3,6 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; import io.lettuce.core.codec.ByteArrayCodec; import java.nio.charset.StandardCharsets; import java.time.Clock; @@ -16,6 +18,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException; @@ -1023,7 +1026,10 @@ void finalQualificationRechecksLostFenceBeyondTheFirstPageWithoutRecreatingIt() @Test void installationDoesNotReturnServingCapabilityWhenAnyCompletedMarkerIsLost() throws Exception { - try (var proof = new TransferSqlProof()) { + try (var proof = new TransferSqlProof(); + var administrator = + RedisClient.create(RedisURI.create(REDIS.getHost(), REDIS.getMappedPort(6379))); + var inspection = administrator.connect(ByteArrayCodec.INSTANCE)) { proof.seedUndeliveredDispatch(proof.execution); var secondExecution = proof.newIndependentControlledOriginExecution(); proof.seedUndeliveredDispatch(secondExecution); @@ -1035,20 +1041,30 @@ void installationDoesNotReturnServingCapabilityWhenAnyCompletedMarkerIsLost() th transferDeadline(), ignored -> proof.transfers.finishVerification(id)); assertThat(verificationComplete).isTrue(); + var connectionDuringInstall = new AtomicReference(); + var checkedAfterCommit = new AtomicBoolean(); var lostAfterInstall = new AtomicBoolean(); var listener = new DefaultExecuteListener() { @Override public void executeEnd(ExecuteContext context) { String sql = context.sql(); - if (sql != null - && sql.stripLeading() + if (sql == null) return; + if (sql.stripLeading() .toLowerCase(Locale.ROOT) .startsWith("update game_session_region_runtime_status") && lostAfterInstall.compareAndSet(false, true)) { - // Model a retained marker disappearing after SQL installs the successor but - // before the coordinator can return its serving capability. + connectionDuringInstall.set( + transferReadbackClientId(inspection.sync().clientList())); + // Lose one marker after the successor update, before its SQL commit. proof.losePhysicalExecution(secondExecution); + } else if (connectionDuringInstall.get() != null + && sql.contains("t.state='COMPLETED'") + && checkedAfterCommit.compareAndSet(false, true)) { + // The independent SQL read verifies commit before inspecting the same connection. + assertThat(proof.currentOwner().ownerInstanceId()).isEqualTo("sql-proof-successor"); + assertThat(transferReadbackClientId(inspection.sync().clientList())) + .isEqualTo(connectionDuringInstall.get()); } } }; @@ -1073,6 +1089,7 @@ public void executeEnd(ExecuteContext context) { .isInstanceOf(IllegalStateException.class); assertThat(lostAfterInstall).isTrue(); + assertThat(checkedAfterCommit).isTrue(); assertThat(proof.currentOwner().ownerInstanceId()).isEqualTo("sql-proof-successor"); assertThat(proof.transfers.readCurrent(id, 0).controlState()).isEqualTo("COMPLETED"); assertThat(proof.physicalExecutionExists(proof.execution)).isTrue(); @@ -1084,6 +1101,13 @@ public void executeEnd(ExecuteContext context) { } } + private static String transferReadbackClientId(String clientList) { + var clients = + clientList.lines().filter(line -> line.contains(" user=gamesession_coord_app ")).toList(); + assertThat(clients).hasSize(1); + return clients.getFirst().split(" ", 2)[0]; + } + @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) void missingAppliedReceiptCannotQualifyCurrentTransfer(boolean installedBeforeLoss) From 4993c5deef5ab4f7a87fd5bfdb4ded803dc6a88a Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 11:04:37 +1300 Subject: [PATCH 48/51] Format reconciled capacity and region proof fixtures --- .../security/AccountTenantCapacityWorkloadGuardTest.java | 3 ++- .../service/impl/AccountTenantCapacityGrpcServiceTest.java | 4 ++-- ...alGameplayOriginalNewFinalAdmissionCompositionFixture.java | 4 ++-- .../CanonicalGameplayRegionLeaseOwnerIntegrationTest.java | 3 ++- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java index d74de4c966..93e8451ac4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java @@ -107,7 +107,8 @@ void admissionDenialReadRequiresExactGameSessionTlsWithoutAmbientAuthority() thr } @Test - void admissionReservationReadRequiresExactGameSessionTlsWithoutAmbientAuthority() throws Exception { + void admissionReservationReadRequiresExactGameSessionTlsWithoutAmbientAuthority() + throws Exception { var method = AccountServiceGrpc.getReadTenantCapacityAdmissionReservationMethod(); var gameSession = tls("firemud", "game-session-service"); assertThat(invoke(method, gameSession, "spiffe://firemud/ns/firemud/sa/game-session-service")) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index a162964051..4ee6fcd37e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -364,8 +364,8 @@ void admissionReservationReadRejectsWrongCallerBindingAndMalformedOriginalBefore @ParameterizedTest @EnumSource(RetainedReservation.class) - void admissionReservationReadReturnsOnlyAnExactRetainedReservation(RetainedReservation retainedReservation) - throws Exception { + void admissionReservationReadReturnsOnlyAnExactRetainedReservation( + RetainedReservation retainedReservation) throws Exception { var request = CapacityAdmissionTestFixture.playerRequest(); DSLContext dsl = mock(); Connection connection = mock(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java index 49947cd1c2..d5656dca6e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java @@ -1015,8 +1015,8 @@ public void claimCapacitySendForControlledRecovery( var selectedOwner = owner.requireRequestBinding(source, request, deadline); if (owner.precharge(source, request, selectedOwner, deadline) != null || owner.authorizeAccountSend(source, request, selectedOwner, deadline) - != net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient - .SendDisposition.AUTHORIZE_NEW) { + != net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient.SendDisposition + .AUTHORIZE_NEW) { throw new IllegalStateException("Expected a newly claimed exact Account send"); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 456ebaa3fe..0126ba8349 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -1863,7 +1863,8 @@ void installationReleasesOrRetainsDefinitiveRedisExpiryForExactRetry(boolean ref preparation.operationId()) .get(0, String.class)) .isEqualTo("INITIALIZING"); - awaitRedisTimelineCutoff(redis.admin(), deadlineObservation.probeCutoff()); + awaitRedisTimelineCutoff( + redis.admin(), deadlineObservation.probeCutoff()); return permit; }) .when(claimBoundary) From 775ddbee8d6b84407defed3798cc68d6dcd6c256 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 11:48:01 +1300 Subject: [PATCH 49/51] Qualify prepared timeline budget fixtures with Redis time --- ...riginalNewCapacityExecutionBudgetTest.java | 49 ++++++++++++------- 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java index 9f8887b635..0bba348bd5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionBudgetTest.java @@ -30,6 +30,7 @@ import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.sql.Connection; import java.sql.PreparedStatement; @@ -69,6 +70,7 @@ /** Controlled acquisition/driver behavior, not database or owner-evidence qualification. */ class CanonicalGameplayOriginalNewCapacityExecutionBudgetTest { private static final Clock CLOCK = Clock.systemUTC(); + private static final long REDIS_TIME_MILLIS = 1_700_000_000_123L; @AfterEach void awaitResourceAndCancellationWorkerCleanup() throws InterruptedException { @@ -522,6 +524,7 @@ void preparedTimelineRetainsAdmissionThroughRejectedCallersAsyncClose() throws E } String loadedSha = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(script)); when(scriptLoad.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(loadedSha); + stubTimelineRedisTime(commands); when(connection.closeAsync()).thenReturn(close); RedisFuture probed = mock(); when(commands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) @@ -605,7 +608,6 @@ void timelineInitializationUsesPreparedPermitWhileOtherBackgroundSlotIsOccupied( RedisFuture scriptLoad = mock(); RedisFuture initialized = mock(); CompletableFuture close = new CompletableFuture<>(); - AtomicReference submittedArguments = new AtomicReference<>(); UUID tenantId = UUID.randomUUID(); UUID gameInstanceId = UUID.randomUUID(); UUID regionId = UUID.randomUUID(); @@ -644,16 +646,10 @@ void timelineInitializationUsesPreparedPermitWhileOtherBackgroundSlotIsOccupied( } String loadedSha = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(script)); when(scriptLoad.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(loadedSha); + stubTimelineRedisTime(commands); when(connection.closeAsync()).thenReturn(close); - when(commands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) - .thenAnswer(invocation -> { - byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; - if ("INITIALIZE" - .equals(new String(arguments[1], java.nio.charset.StandardCharsets.US_ASCII))) { - submittedArguments.set(arguments); - } - return initialized; - }); + when(commands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) + .thenReturn(initialized); when(initialized.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(1L); RuntimeIdentity identity = new RuntimeIdentity( @@ -732,15 +728,23 @@ void timelineInitializationUsesPreparedPermitWhileOtherBackgroundSlotIsOccupied( initialization = CompletableFuture.supplyAsync(() -> session.initialize(permit), executor); } + ArgumentCaptor arguments = ArgumentCaptor.forClass(byte[][].class); verify(commands, timeout(1000).times(2)) - .evalsha(any(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + .evalsha(any(), eq(ScriptOutputType.INTEGER), any(byte[][].class), arguments.capture()); verify(connection, timeout(1000)).closeAsync(); - byte[][] arguments = submittedArguments.get(); - assertThat(arguments).isNotNull(); - assertThat(new String(arguments[7], java.nio.charset.StandardCharsets.US_ASCII)) - .isEqualTo("1"); - assertThat(new String(arguments[8], java.nio.charset.StandardCharsets.US_ASCII)) - .isEqualTo(Long.toString(handoffDeadline)); + verify(commands).time(); + byte[][] probeArguments = arguments.getAllValues().get(0); + byte[][] initializeArguments = arguments.getAllValues().get(1); + assertThat(new String(probeArguments[1], StandardCharsets.US_ASCII)).isEqualTo("PROBE"); + assertThat(new String(initializeArguments[1], StandardCharsets.US_ASCII)) + .isEqualTo("INITIALIZE"); + assertThat(new String(initializeArguments[7], StandardCharsets.US_ASCII)).isEqualTo("1"); + assertThat(initializeArguments[8]).isEqualTo(probeArguments[8]); + long redisDeadline = + Long.parseLong(new String(initializeArguments[8], StandardCharsets.US_ASCII)); + assertThat(redisDeadline) + .isGreaterThan(REDIS_TIME_MILLIS) + .isLessThanOrEqualTo(REDIS_TIME_MILLIS + 4000); assertThat(initialization.isDone()).isFalse(); assertThat(background.availablePermits()).isZero(); assertThat(operations.availablePermits()).isEqualTo(operationMaximum - 2); @@ -762,6 +766,17 @@ void timelineInitializationUsesPreparedPermitWhileOtherBackgroundSlotIsOccupied( } } + private static void stubTimelineRedisTime(RedisAsyncCommands commands) + throws Exception { + RedisFuture> time = mock(); + when(commands.time()).thenReturn(time); + when(time.get(anyLong(), eq(TimeUnit.MILLISECONDS))) + .thenReturn( + List.of( + "1700000000".getBytes(StandardCharsets.US_ASCII), + "123000".getBytes(StandardCharsets.US_ASCII))); + } + @Test void successfulTransferReadbackRetainsAdmissionUntilAsyncRedisCloseCompletes() throws Exception { RedisClient redis = mock(); From 8024f83b656cf1fd7cc3335b80678340fa8e19df Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 21:00:59 +1300 Subject: [PATCH 50/51] Settle exact Account denials through the installed region successor --- .../game-session-service/runtime-and-data.md | 2 +- ...alAdmissionCompositionIntegrationTest.java | 228 +++++++++++++++--- ...nonicalGameplayCapacityEvidenceBudget.java | 59 ++++- ...playOriginalNewCapacityExecutionOwner.java | 67 ++++- ...yOriginalNewFinalAdmissionCoordinator.java | 23 ++ ...t_capacity_denial_after_region_handoff.sql | 182 ++++++++++++++ ...alNewFinalAdmissionCompositionFixture.java | 69 +++--- ...ransferCapacityCustodyIntegrationTest.java | 114 +++++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 15 +- 9 files changed, 674 insertions(+), 85 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql 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 fdd340d46c..ddd17acc03 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -6,7 +6,7 @@ V1063 adds retained exact original capacity execution evidence and the final tra The seven-key tenant-slot final script atomically serializes `FINAL` against permanent same-attempt `CLOSE`, retaining the complete attempt envelope, reservation fence/expiry, original owner and actual committed session hash/times. New execution requires the exact persistent `AUTHORIZED` record and an unexpired reservation at Redis `TIME`. Account transition restrictions, coupled to the irreversible closure, exclude a delayed final CAS after release or rearm without relying on a one-time remote current-fence read. Original evidence is immutable and retained without TTL, deletion or truncation. V1063 separately classifies the evidence family and seals the next runtime-family catalog epoch without changing retained predecessor epochs or migration histories. -Game Session bounds the number and retained bytes of original-NEW capacity execution records per tenant allocation. Its durable owner precharges each exact attempt before dispatch so a full budget can refuse new admissions while preserving room to fence an already charged unresolved original whose execution key is absent. The charge covers the largest permitted execution record for that attempt and is shared by installation, same-attempt closure and transfer fencing. Within the fixed 1 MiB charge, PostgreSQL allows up to 1,048,064 bytes for the canonical execution and reserves 512 bytes for terminal readback. An authenticated exact Account denial, either quota exceeded or expired retained evaluation, can return that attempt’s active count and byte reservation only after Account durably excludes acceptance and Game Session matches the current selected owner under the region lock in the transaction that settles the charge. The settlement also serializes against execution insertion. The original charge binding, decision kind and identifier remain durable under a separate finite record limit. Exact denied replays use that receipt without contacting Account, and lost or ambiguous Account responses keep the charge active. Exact retries neither increase the charge nor create a new dispatch. An absent or unqualified charge withholds new effects, preserves the original evidence and leaves the Account reservation held. The first creating Account call requires a committed Game Session send claim under the same exact region and tenant budget locks. An unclaimed attempt can release active count and bytes only when a local transaction proves its send permission was never issued. The retained identity and release receipt still count against total history. A new precharge can reclaim one expired unclaimed slot in the same tenant, under the tenant budget lock, even after the original region moves. A new budget requires an explicit retained-history bound. Older immutable budgets without one cannot admit new charges. Exact reacquisition is permitted only while the original authorization and owner remain current, under the existing active ceiling. With its send permission issued, or with unknown predecessor state, the attempt uses Account’s exact read-only reservation probe while the original Account OPEN remains eligible. An exact positive reservation can continue through ordinary FINAL checks. When the probe cannot establish an eligible reservation or the original OPEN has expired, an exact typed durable denial from Account’s read-only outcome can settle the charge. A missing or ambiguous read does not authorize creation, retirement or settlement. After the original Account OPEN window expires, Game Session can use an exact durable Account denial to settle an existing charge under the current selected region owner if it may have sent the original request. Admission remains unavailable. Activation must first exclude any writer that could call Account without acquiring the durable send claim. The [Coordination reset policy](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) governs storage loss and restore. The bounded preparation retains the full binding and reserves no authority to delete evidence. Fleet sizing, operational qualification and an independently approved retirement policy are activation prerequisites. +Game Session bounds the number and retained bytes of original-NEW capacity execution records per tenant allocation. Its durable owner precharges each exact attempt before dispatch so a full budget can refuse new admissions while preserving room to fence an already charged unresolved original whose execution key is absent. The charge covers the largest permitted execution record for that attempt and is shared by installation, same-attempt closure and transfer fencing. Within the fixed 1 MiB charge, PostgreSQL allows up to 1,048,064 bytes for the canonical execution and reserves 512 bytes for terminal readback. An authenticated exact Account denial, either quota exceeded or expired retained evaluation, can return that attempt’s active count and byte reservation only after Account durably excludes acceptance and Game Session verifies settlement authority under the region lock. The original selected owner can settle while its fence remains current. A successor with a higher installed fence may settle the exact provisional original charge after a read-only Account denial for its recorded request. The successor must prove current ownership of the same protected region and retained original world source under the region and tenant budget locks. The charge must show a possible original send and have no execution record. Settlement retains the original charge binding, the typed denial, and the successor owner, fence and lease correlation. The successor has no authority to issue another send or continue an accepted reservation through this path. The settlement also serializes against execution insertion. The original charge binding, decision kind and identifier remain durable under a separate finite record limit. Exact denied replays use that receipt without contacting Account, and lost or ambiguous Account responses keep the charge active. Exact retries neither increase the charge nor create a new dispatch. An absent or unqualified charge withholds new effects, preserves the original evidence and leaves the Account reservation held. The first creating Account call requires a committed Game Session send claim under the same exact region and tenant budget locks. An unclaimed attempt can release active count and bytes only when a local transaction proves its send permission was never issued. The retained identity and release receipt still count against total history. A new precharge can reclaim one expired unclaimed slot in the same tenant, under the tenant budget lock, even after the original region moves. A new budget requires an explicit retained-history bound. Older immutable budgets without one cannot admit new charges. Exact reacquisition is permitted only while the original authorization and owner remain current, under the existing active ceiling. With its send permission issued, or with unknown predecessor state, the attempt uses Account’s exact read-only reservation probe while the original Account OPEN remains eligible. An exact positive reservation can continue through ordinary FINAL checks. When the probe cannot establish an eligible reservation or the original OPEN has expired, an exact typed durable denial from Account’s read-only outcome can settle the charge. A missing or ambiguous read does not authorize creation, retirement or settlement. After the original Account OPEN window expires, Game Session can still settle a possible send using the exact typed denial and the applicable original or successor settlement authority. Admission remains unavailable. Activation must first exclude any writer that could call Account without acquiring the durable send claim. The [Coordination reset policy](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) governs storage loss and restore. The bounded preparation retains the full binding and reserves no authority to delete evidence. Fleet sizing, operational qualification and an independently approved retirement policy are activation prerequisites. The finalized schema-2 reader requires `capacityExecutionDigest`; predecessor finalized values without it are unsupported by this unregistered preproduction cutover. Before activation or reuse of predecessor-populated storage, establish and resolve retained-data and active original-confirmation or recovery obligations while preserving immutable historical evidence. The [owning tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records this cutover limitation and the unknown inventory of earlier manually persisted data. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 231ddc9ef0..906a6fbb10 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -1083,32 +1083,12 @@ void lostExpiredEvaluationDenialSettlesThroughReadOnlyRecoveryAndReplaysOffline( session.provisionCapacityRefusalBudget(); byte[] candidate = session.gs.physicalSession(); var request = session.capacityRequest; - assertThat(CLOCK.instant()).isBefore(request.evidence().expiresAt()); - session.gs.claimCapacitySendForControlledRecovery( - request, Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC)); - // The creating send claim already committed. Delay delivery of the original request - // until both owner clocks establish expiry of the same retained evaluation. - session.dsl.fetchSingle( - "SELECT pg_sleep_until(?::timestamptz)", request.evidence().expiresAt().toString()); - long clockWaitDeadline = System.nanoTime() + Duration.ofSeconds(5).toNanos(); - while (CLOCK.instant().isBefore(request.evidence().expiresAt()) - && System.nanoTime() < clockWaitDeadline) { - Thread.sleep(10); - } - assertThat(CLOCK.instant()).isAfterOrEqualTo(request.evidence().expiresAt()); - var fault = new DropFirstCapacityDenialResponse(request, Failure.CAPACITY_EVALUATION_EXPIRED); - session.startCapacityClient(fault.channels()); String unchangedCapacity = session.capacityImage(); String transition = session.gsReceiptImage(); String chargeSql = "SELECT account_denial_id, account_denial_kind, mutation_digest" + " FROM game_session_capacity_evidence_charge WHERE admission_attempt_id=?"; - var lost = - assertThrows( - StatusRuntimeException.class, - () -> session.capacityClient.commit(request, CLOCK.millis() + 5_000L)); - assertThat(lost.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(fault.successfullyDropped).isTrue(); + var fault = dropExpiredCapacityDenial(session, request); UUID denialId = fault.observedDenial.get(); assertExactAccountDenial(session, request, Failure.CAPACITY_EVALUATION_EXPIRED, denialId); assertThat(session.gs.dsl().fetchSingle(chargeSql, request.admissionAttemptId()).intoMap()) @@ -1165,6 +1145,173 @@ void lostExpiredEvaluationDenialSettlesThroughReadOnlyRecoveryAndReplaysOffline( } } + @Test + void lostExpiredEvaluationDenialSettlesThroughSuccessorWithoutReadmittingOriginal() + throws Exception { + try (Session session = new Session(CLOCK, 1, 2, true); + OriginalNewCredential credential = session.issue()) { + session.provisionCapacityRefusalBudget(); + byte[] candidate = session.gs.physicalSession(); + var request = session.capacityRequest; + var gsSql = session.gs.dsl(); + var fault = dropExpiredCapacityDenial(session, request); + UUID denialId = fault.observedDenial.get(); + assertExactAccountDenial(session, request, Failure.CAPACITY_EVALUATION_EXPIRED, denialId); + String accountBeforeRecovery = session.capacityImage() + session.capacityDecisionImage(); + String transitionsBeforeRecovery = session.gsReceiptImage(); + + String chargeIdentitySql = + "SELECT tenant_id, request_id, admission_id, admission_attempt_id, capacity_rearm_fence," + + " mutation_digest, candidate_digest, selected_owner_id, selected_owner_fence," + + " reserved_binding_bytes, account_send_state" + + " FROM game_session_capacity_evidence_charge WHERE admission_attempt_id=?"; + String settlementSql = + "SELECT account_denial_id, account_denial_kind, denial_settlement_owner_id," + + " denial_settlement_owner_fence, denial_settlement_lease_correlation" + + " FROM game_session_capacity_evidence_charge WHERE admission_attempt_id=?"; + var charge = gsSql.fetchSingle(chargeIdentitySql, request.admissionAttemptId()); + var unsettled = gsSql.fetchSingle(settlementSql, request.admissionAttemptId()); + assertThat(charge.get("mutation_digest", String.class)).isEqualTo(request.mutationDigest()); + assertThat(charge.get("account_send_state", String.class)).isEqualTo("MAY_HAVE_SENT"); + assertThat(unsettled.intoMap().values()).containsOnlyNulls(); + var chargeTable = DSL.table("game_session_capacity_evidence_charge"); + var executionTable = DSL.table("game_session_original_new_capacity_execution"); + assertThat(gsSql.fetchCount(chargeTable)).isOne(); + assertThat(gsSql.fetchCount(executionTable)).isZero(); + + String regionOwnerSql = + "SELECT owner_instance_id, executor_fence, lease_token_correlation" + + " FROM game_session_region_runtime_status"; + var originalOwner = gsSql.fetchSingle(regionOwnerSql); + assertThat(originalOwner.get("owner_instance_id", String.class)) + .isEqualTo(charge.get("selected_owner_id", String.class)); + assertThat(originalOwner.get("executor_fence", Long.class)) + .isEqualTo(charge.get("selected_owner_fence", Long.class)); + session.gs.handoffOriginalRegion(CLOCK.millis() + 10_000L); + var successor = gsSql.fetchSingle(regionOwnerSql); + assertThat(successor.get("owner_instance_id", String.class)) + .isNotEqualTo(originalOwner.get("owner_instance_id", String.class)); + long successorFence = successor.get("executor_fence", Long.class); + assertThat(successorFence).isGreaterThan(originalOwner.get("executor_fence", Long.class)); + assertThat(successor.get("lease_token_correlation", String.class)) + .isNotEqualTo(originalOwner.get("lease_token_correlation", String.class)); + assertThat(regionFenceImage(session)).containsExactly(successorFence); + assertThat(gsSql.fetchSingle(chargeIdentitySql, request.admissionAttemptId())) + .isEqualTo(charge); + assertThat(gsSql.fetchSingle(settlementSql, request.admissionAttemptId())) + .isEqualTo(unsettled); + + Runnable retry = + () -> + session.gs.completeAfterInitialOpenWindow( + session.client, session.jwks, session.jwt, session.capacityClient, request); + session.stopCapacityServer(); + assertThatThrownBy(retry::run) + .isInstanceOf(IllegalStateException.class) + .isNotInstanceOf(CapacityRefusedException.class); + assertThat(fault.denialReads.get()).isOne(); + assertThat(gsSql.fetchSingle(chargeIdentitySql, request.admissionAttemptId())) + .isEqualTo(charge); + assertThat(gsSql.fetchSingle(settlementSql, request.admissionAttemptId())) + .isEqualTo(unsettled); + + session.capacityOwner = session.account.capacityOwner(CLOCK); + session.startCapacityServer(); + session.startCapacityClient(fault.channels()); + var recovered = assertThrows(CapacityRefusedException.class, retry::run); + assertThat(recovered.code()).isEqualTo(Failure.CAPACITY_EVALUATION_EXPIRED); + assertThat(recovered.durableDenialId()).isEqualTo(denialId); + var settled = gsSql.fetchSingle(settlementSql, request.admissionAttemptId()); + assertThat(settled.intoMap()) + .containsEntry("account_denial_id", denialId) + .containsEntry("account_denial_kind", Failure.CAPACITY_EVALUATION_EXPIRED.name()) + .containsEntry( + "denial_settlement_owner_id", successor.get("owner_instance_id", String.class)) + .containsEntry("denial_settlement_owner_fence", successorFence) + .containsEntry( + "denial_settlement_lease_correlation", + successor.get("lease_token_correlation", String.class)); + assertThat(gsSql.fetchSingle(chargeIdentitySql, request.admissionAttemptId())) + .isEqualTo(charge); + assertThat(gsSql.fetchCount(executionTable)).isZero(); + assertThat(session.capacityImage() + session.capacityDecisionImage()) + .isEqualTo(accountBeforeRecovery); + assertThat(session.gsReceiptImage()).isEqualTo(transitionsBeforeRecovery); + assertThat(session.gs.finalReadCalls()).isZero(); + assertThat(session.genesis().tokenHash()).isEqualTo(credential.tokenSha256()); + assertThat(session.genesis().confirmedAdmissionAtMillis()).isNull(); + assertProvisionalUnchanged(session, candidate); + + session.stopCapacityServer(); + var replay = assertThrows(CapacityRefusedException.class, retry::run); + assertThat(replay.code()).isEqualTo(Failure.CAPACITY_EVALUATION_EXPIRED); + assertThat(replay.durableDenialId()).isEqualTo(denialId); + assertThat(fault.calls.get()).isOne(); + assertThat(fault.denialReads.get()).isEqualTo(2); + assertThat(fault.reservationReads.get()).isZero(); + + session.startCapacityServer(); + var second = session.gs.prepareSecondAdmission(); + var secondRequest = session.prepareSecondCapacityRequest(second); + assertThat(secondRequest.identity().tenantId()).isEqualTo(request.identity().tenantId()); + assertThat(secondRequest.identity().requestId()).isNotEqualTo(request.identity().requestId()); + assertThat(secondRequest.identity().admissionId()) + .isNotEqualTo(request.identity().admissionId()); + assertThat(secondRequest.admissionAttemptId()).isNotEqualTo(request.admissionAttemptId()); + + var receipt = + session.gs.complete( + second, + session.client, + session.jwks, + session.jwt, + CLOCK.millis() + 10_000L, + session.capacityClient, + secondRequest); + assertThat(receipt.transitionId()).isEqualTo(second.decisionId()); + assertPhysicalSession(second.physicalSession(), receipt); + assertThat(gsSql.fetchCount(chargeTable)).isEqualTo(2); + assertThat(gsSql.fetchSingle(chargeIdentitySql, request.admissionAttemptId())) + .isEqualTo(charge); + assertThat(gsSql.fetchSingle(settlementSql, request.admissionAttemptId())).isEqualTo(settled); + assertThat( + gsSql + .fetchSingle( + "SELECT admission_attempt_id, status" + + " FROM game_session_original_new_capacity_execution") + .intoMap()) + .containsEntry("admission_attempt_id", secondRequest.admissionAttemptId()) + .containsEntry("status", "COMMITTED"); + assertProvisionalUnchanged(session, candidate); + } + } + + private static DropFirstCapacityDenialResponse dropExpiredCapacityDenial( + Session session, TenantCapacityAdmission.Request request) throws Exception { + assertThat(CLOCK.instant()).isBefore(request.evidence().expiresAt()); + session.gs.claimCapacitySendForControlledRecovery( + request, Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC)); + // The creating send claim already committed. Delay delivery of the original request + // until both owner clocks establish expiry of the same retained evaluation. + session.dsl.fetchSingle( + "SELECT pg_sleep_until(?::timestamptz)", request.evidence().expiresAt().toString()); + long clockWaitDeadline = System.nanoTime() + Duration.ofSeconds(5).toNanos(); + while (CLOCK.instant().isBefore(request.evidence().expiresAt()) + && System.nanoTime() < clockWaitDeadline) { + Thread.sleep(10); + } + assertThat(CLOCK.instant()).isAfterOrEqualTo(request.evidence().expiresAt()); + var fault = new DropFirstCapacityDenialResponse(request, Failure.CAPACITY_EVALUATION_EXPIRED); + session.startCapacityClient(fault.channels()); + var lost = + assertThrows( + StatusRuntimeException.class, + () -> session.capacityClient.commit(request, CLOCK.millis() + 5_000L)); + assertThat(lost.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(fault.successfullyDropped).isTrue(); + return fault; + } + @Test void accountGeneratedUnavailableKeepsExactGameSessionReserveUnsettled() throws Exception { // Only Account's capacity owner sees the advanced clock. The Game Session request, @@ -1417,25 +1564,7 @@ void authenticatedQuotaDenialFreesTheLastActiveSlotForADistinctAdmission() throw assertThatThrownBy(session.gs::prepareSecondAdmission) .isInstanceOf(IllegalStateException.class) .hasMessage("Second admission has already been prepared"); - var secondLease = - session - .client - .acquire( - second.requestId(), - session.jwt, - second.candidate(), - session.gs.target(), - second.generation()) - .originalLeaseEvidence(); - second.install(secondLease); - var scope = session.account.capacityScope(session.gs.target()); - var secondRequest = - session.evaluateCapacity( - scope, - session.targetSelector(second.requestId(), scope), - second.candidate(), - second.decisionId()); - session.finalizeLease(secondLease, second.decisionId()); + var secondRequest = session.prepareSecondCapacityRequest(second); assertThat(secondRequest.evidence().quota()) .isPositive() .isEqualTo(session.capacityRequest.evidence().quota()); @@ -1897,6 +2026,25 @@ private TenantCapacityAdmission.Request evaluateCapacity( .withDigest(); } + private TenantCapacityAdmission.Request prepareSecondCapacityRequest( + CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.SecondAdmission second) { + var secondLease = + client + .acquire( + second.requestId(), jwt, second.candidate(), gs.target(), second.generation()) + .originalLeaseEvidence(); + second.install(secondLease); + var scope = account.capacityScope(gs.target()); + var secondRequest = + evaluateCapacity( + scope, + targetSelector(second.requestId(), scope), + second.candidate(), + second.decisionId()); + finalizeLease(secondLease, second.decisionId()); + return secondRequest; + } + private void finalizeLease( AccountGameplayAdmissionLeaseEvidence originalLease, UUID decisionId) { var finalized = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java index ef750d4fff..c236bae9c9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient.SendDisposition; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.exception.DataAccessException; @@ -179,6 +180,50 @@ static void settleDenied( if (settled != 1) throw unavailable(); } + static RetainedCharge reconcileSuccessorDenial( + DSLContext tx, + Request request, + String candidateDigest, + String tag, + long originalFence, + CanonicalGameplayRegionRuntimeStatus successor, + Refusal denial) { + lockBudget(tx, request, tag); + var charge = exactChargeIdentity(tx, request, candidateDigest, tag); + if (charge == null + || !Long.valueOf(originalFence).equals(charge.get("selected_owner_fence", Long.class)) + || tx.fetchOne( + "SELECT 1 FROM game_session_original_new_capacity_execution" + + " WHERE admission_attempt_id=? OR transition_id=? LIMIT 1", + request.admissionAttemptId(), + request.identity().admissionId()) + != null) throw unavailable(); + String state = charge.get("account_send_state", String.class); + if (state != null && !"MAY_HAVE_SENT".equals(state)) throw unavailable(); + var retained = retainedDenial(charge); + if (retained != null) { + if (denial != null && !retained.equals(denial)) throw unavailable(); + return new RetainedCharge(retained, false); + } + if (denial == null) return new RetainedCharge(null, true); + if (!denial.code().supportsDurableDenial() || denial.durableDenialId() == null) { + throw unavailable(); + } + if (tx.execute( + "UPDATE game_session_capacity_evidence_charge SET account_denial_id=?," + + " account_denial_kind=?,denial_settlement_owner_id=?," + + " denial_settlement_owner_fence=?,denial_settlement_lease_correlation=?" + + " WHERE admission_attempt_id=? AND account_denial_id IS NULL", + denial.durableDenialId(), + denial.code().name(), + successor.ownerInstanceId(), + successor.executorFence().longValueExact(), + successor.leaseTokenCorrelation(), + request.admissionAttemptId()) + != 1) throw unavailable(); + return new RetainedCharge(denial, false); + } + static void requireCharge(DSLContext tx, OriginalNewCapacityExecution execution, String tag) { var charge = exactCharge( @@ -216,6 +261,18 @@ private static Record exactCharge( String candidateDigest, CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner selected, String tag) { + var prior = exactChargeIdentity(tx, request, candidateDigest, tag); + if (prior != null + && (!selected.instanceId().equals(prior.get("selected_owner_id", String.class)) + || !Long.valueOf(selected.fence()) + .equals(prior.get("selected_owner_fence", Long.class)))) { + throw unavailable(); + } + return prior; + } + + private static Record exactChargeIdentity( + DSLContext tx, Request request, String candidateDigest, String tag) { var identity = request.identity(); var prior = tx.fetchOne( @@ -233,8 +290,6 @@ private static Record exactCharge( || !Long.valueOf(request.capacityRearmFence()).equals(prior.get(3)) || !request.mutationDigest().equals(prior.get(4)) || !candidateDigest.equals(prior.get(5)) - || !selected.instanceId().equals(prior.get(6)) - || !Long.valueOf(selected.fence()).equals(prior.get(7)) || !tag.equals(prior.get(8))) throw unavailable(); return prior; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 7f97c59b97..c2c06c47ab 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -32,6 +32,7 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import org.jooq.DSLContext; import org.jooq.Record; @@ -140,6 +141,16 @@ CurrentOwner requireRequestBinding( if (budget == null) return within(deadline, owner -> owner.requireRequestBinding(source, request, deadline)); budget.check(); + requireExactRequest(source, request); + CurrentOwner selected = currentOwner(source.candidate()); + if (selected.fence() != source.regionAcknowledgement().executorFence().longValueExact()) + throw unavailable(); + return selected; + } + + private static void requireExactRequest( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + Request request) { // Account owns fresh policy denial; coherent non-creating evidence must reach that owner. request.requireStructurallyValid(); var candidate = source.candidate(); @@ -169,10 +180,58 @@ CurrentOwner requireRequestBinding( || !Objects.equals( request.evidence().fields().get("authorityTuple"), candidate.leaseEvidence().carrier().get("authorityTuple"))) throw unavailable(); - CurrentOwner selected = currentOwner(candidate); - if (selected.fence() != source.regionAcknowledgement().executorFence().longValueExact()) - throw unavailable(); - return selected; + } + + CanonicalGameplayCapacityEvidenceBudget.RetainedCharge reconcileSuccessorDenial( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + Request request, + CanonicalGameplayRegionLeaseOwner.Installation installation, + Refusal denial, + long deadline) { + return within( + deadline, + owner -> { + requireExactRequest(source, request); + OriginalNewCapacityExecution.requireOriginalNewRequest(request); + var successor = installation.status; + var original = source.regionAcknowledgement(); + if (source.transitionStatus() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || !request.evidence().permitsCreation() + || !original.tenantId().equals(successor.tenantId()) + || !original.gameInstanceId().equals(successor.gameInstanceId()) + || !original.regionId().equals(successor.regionId()) + || original.regionEpoch().longValueExact() != successor.regionEpoch() + || successor.executorFence().compareTo(original.executorFence()) <= 0) { + throw unavailable(); + } + var assignment = + owner.scopedTags().assignmentForTransition(request.identity().admissionId()); + return owner + .sql() + .transactionResult(configuration -> { + var tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + tx.fetch( + "SELECT require_gs_capacity_denial_successor(?,?,?,?,?,?,?,?)", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + source.candidateDigest(), + original.executorFence().longValueExact(), + successor.ownerInstanceId(), + successor.executorFence().longValueExact(), + successor.leaseTokenCorrelation()); + return CanonicalGameplayCapacityEvidenceBudget.reconcileSuccessorDenial( + tx, + request, + source.candidateDigest(), + assignment.tenantGameplayTag(), + original.executorFence().longValueExact(), + successor, + denial); + }); + }); } /** Checks the caller's complete original request against the execution linked by the receipt. */ diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index dbf6214105..6b3a161b17 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -114,6 +114,29 @@ FinalAdmissionResult completeOriginalNew( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source = inventory.readOriginalNewFinalAdmissionSource(originalDecision); requireOriginalSource(source, originalDecision); + if (source.transitionStatus() == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + && capacityRequest.evidence().permitsCreation() + && privateRegionInstallation + .status + .executorFence() + .compareTo(source.regionAcknowledgement().executorFence()) + > 0) { + var charge = + capacityExecution.reconcileSuccessorDenial( + source, capacityRequest, privateRegionInstallation, null, absoluteDeadlineMillis); + if (charge.accountDenial() != null) { + throw CapacityRefusedException.retainedAdmissionDenial(charge.accountDenial()); + } + requireDeadline(absoluteDeadlineMillis); + Refusal denial = + capacityClient.readRetainedAdmissionDenial(capacityRequest, absoluteDeadlineMillis); + requireDeadline(absoluteDeadlineMillis); + source = readSameSource(source, originalDecision, false); + var settled = + capacityExecution.reconcileSuccessorDenial( + source, capacityRequest, privateRegionInstallation, denial, absoluteDeadlineMillis); + throw CapacityRefusedException.retainedAdmissionDenial(settled.accountDenial()); + } var selectedOwner = capacityExecution.requireRequestBinding(source, capacityRequest, absoluteDeadlineMillis); CanonicalGameplayCapacityEvidenceBudget.RetainedCharge priorCharge = null; diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql new file mode 100644 index 0000000000..e78e7b528f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql @@ -0,0 +1,182 @@ +-- Retain the original charge and record which installed successor settled an exact Account denial. +-- [jooq ignore start] +ALTER TABLE game_session_capacity_evidence_charge + ADD COLUMN denial_settlement_owner_id varchar(120), + ADD COLUMN denial_settlement_owner_fence bigint, + ADD COLUMN denial_settlement_lease_correlation varchar(64), + ADD CONSTRAINT chk_gs_capacity_denial_successor CHECK ( + (denial_settlement_owner_id IS NULL AND denial_settlement_owner_fence IS NULL + AND denial_settlement_lease_correlation IS NULL) + OR (denial_settlement_owner_id IS NOT NULL AND denial_settlement_owner_fence IS NOT NULL + AND denial_settlement_owner_fence > selected_owner_fence + AND denial_settlement_lease_correlation IS NOT NULL + AND denial_settlement_lease_correlation ~ '^[0-9a-f]{64}$' + AND account_denial_id IS NOT NULL AND account_denial_kind IS NOT NULL) + ); + +-- Take the same region lock that serializes dispatch and replacement before locking the budget. +CREATE FUNCTION require_gs_capacity_denial_successor( + p_tenant UUID, p_request UUID, p_admission UUID, p_candidate TEXT, p_original_fence BIGINT, + p_owner TEXT, p_fence BIGINT, p_correlation TEXT +) RETURNS VOID LANGUAGE plpgsql AS $$ +BEGIN + IF p_fence IS NULL OR p_fence <= p_original_fence OR p_correlation IS NULL THEN + RAISE EXCEPTION 'Successor denial requires an advancing installed region owner' USING ERRCODE='23514'; + END IF; + PERFORM require_gs_capacity_send_owner(p_tenant,p_admission,p_owner,p_fence); + PERFORM 1 FROM game_session_canonical_binding_transition t + JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=t.transition_id + JOIN game_session_region_runtime_status r ON r.tenant_id=b.tenant_id + AND r.game_instance_id=b.game_instance_id AND r.region_id=b.region_id + AND r.region_epoch=b.region_epoch + WHERE t.transition_id=p_admission AND t.tenant_id=p_tenant AND b.tenant_id=p_tenant + AND t.admission_request_id=p_request AND t.original_new_candidate_digest=p_candidate + AND t.status='PROVISIONAL' AND b.status='ACKNOWLEDGED' + AND b.executor_fence=p_original_fence + AND r.lease_token_correlation=p_correlation + AND r.canonical_region_id=b.canonical_region_id AND r.lifecycle_epoch=b.world_lifecycle_epoch + AND r.lifecycle_row_version=b.world_lifecycle_row_version AND r.capture_id=b.world_capture_id + AND r.graph_sha256=b.world_graph_sha256 + AND r.preparation_input_digest=b.world_preparation_input_digest + FOR UPDATE OF t; + IF NOT FOUND THEN + RAISE EXCEPTION 'Successor denial requires the exact original bridge and current region source' USING ERRCODE='23514'; + END IF; +END; +$$; + +CREATE OR REPLACE FUNCTION settle_gs_capacity_evidence_charge() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE limits game_session_capacity_evidence_budget%ROWTYPE; +BEGIN + IF TG_OP <> 'UPDATE' OR current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Capacity evidence charge history is retained' USING ERRCODE='23514'; + END IF; + IF OLD.account_denial_id IS NOT NULL + OR NEW.account_unsent_released_at IS DISTINCT FROM OLD.account_unsent_released_at + OR (to_jsonb(NEW) - 'account_send_state' - 'account_denial_id' - 'account_denial_kind' + - 'denial_settlement_owner_id' - 'denial_settlement_owner_fence' + - 'denial_settlement_lease_correlation') + IS DISTINCT FROM (to_jsonb(OLD) - 'account_send_state' - 'account_denial_id' - 'account_denial_kind' + - 'denial_settlement_owner_id' - 'denial_settlement_owner_fence' + - 'denial_settlement_lease_correlation') THEN + RAISE EXCEPTION 'Capacity evidence charge identity and settlement history are immutable' USING ERRCODE='23514'; + END IF; + IF NEW.denial_settlement_owner_id IS NOT NULL THEN + IF NEW.account_denial_id IS NULL + OR NEW.account_denial_kind IS NULL + OR NEW.account_denial_kind NOT IN ('CAPACITY_QUOTA_EXCEEDED', 'CAPACITY_EVALUATION_EXPIRED') + OR NEW.account_send_state IS DISTINCT FROM OLD.account_send_state + OR (OLD.account_send_state IS NOT NULL AND OLD.account_send_state <> 'MAY_HAVE_SENT') THEN + RAISE EXCEPTION 'Successor can settle only an exact denial of a possible send' USING ERRCODE='23514'; + END IF; + PERFORM require_gs_capacity_denial_successor( + OLD.tenant_id,OLD.request_id,OLD.admission_id,OLD.candidate_digest, + OLD.selected_owner_fence,NEW.denial_settlement_owner_id, + NEW.denial_settlement_owner_fence,NEW.denial_settlement_lease_correlation); + PERFORM 1 FROM game_session_capacity_evidence_budget WHERE tenant_id=OLD.tenant_id FOR UPDATE; + IF NOT FOUND OR EXISTS ( + SELECT 1 FROM game_session_original_new_capacity_execution + WHERE admission_attempt_id=OLD.admission_attempt_id OR transition_id=OLD.admission_id + ) THEN + RAISE EXCEPTION 'Successor denial requires a charge without execution custody' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END IF; + -- Once the original send window expires, the Game Session tenant budget can return a + -- still-unclaimed slot even after its original region owner moved. No Account decision + -- is inferred. The terminal expiry and exact SQL state exclude a first or concurrent send. + IF OLD.account_send_state='UNCLAIMED' AND NEW.account_send_state='RELEASED_UNSENT' + AND NEW.account_denial_id IS NULL AND NEW.account_denial_kind IS NULL + AND OLD.account_send_evidence_expires_at <= clock_timestamp() THEN + PERFORM 1 FROM game_session_capacity_evidence_budget WHERE tenant_id=OLD.tenant_id FOR UPDATE; + IF NOT FOUND OR EXISTS ( + SELECT 1 FROM game_session_original_new_capacity_execution + WHERE admission_attempt_id=OLD.admission_attempt_id + ) THEN + RAISE EXCEPTION 'Execution custody prevents capacity evidence charge changes' USING ERRCODE='23514'; + END IF; + NEW.account_unsent_released_at := clock_timestamp(); + RETURN NEW; + END IF; + PERFORM require_gs_capacity_send_owner(OLD.tenant_id,OLD.admission_id,OLD.selected_owner_id,OLD.selected_owner_fence); + SELECT * INTO limits FROM game_session_capacity_evidence_budget + WHERE tenant_id=OLD.tenant_id FOR UPDATE; + IF NOT FOUND OR EXISTS ( + SELECT 1 FROM game_session_original_new_capacity_execution + WHERE admission_attempt_id=OLD.admission_attempt_id + ) THEN + RAISE EXCEPTION 'Execution custody prevents capacity evidence charge changes' USING ERRCODE='23514'; + END IF; + + IF NEW.account_denial_id IS NOT NULL + AND NEW.account_denial_kind IN ('CAPACITY_QUOTA_EXCEEDED', 'CAPACITY_EVALUATION_EXPIRED') + AND NEW.account_send_state IS NOT DISTINCT FROM OLD.account_send_state + AND (OLD.account_send_state IS NULL OR OLD.account_send_state='MAY_HAVE_SENT') THEN + -- Only the owner supplies an exact authenticated durable Account denial. + RETURN NEW; + END IF; + IF NEW.account_denial_id IS NOT NULL OR NEW.account_denial_kind IS NOT NULL + OR limits.maximum_retained_records IS NULL THEN + RAISE EXCEPTION 'Invalid capacity evidence send transition' USING ERRCODE='23514'; + END IF; + IF OLD.account_send_state='UNCLAIMED' AND NEW.account_send_state='RELEASED_UNSENT' THEN + -- Winning this CAS excludes the first permission to invoke Account on this charge. + NEW.account_unsent_released_at := clock_timestamp(); + RETURN NEW; + END IF; + IF OLD.account_send_state IN ('UNCLAIMED','RELEASED_UNSENT') AND NEW.account_send_state='MAY_HAVE_SENT' THEN + IF OLD.account_send_evidence_expires_at <= clock_timestamp() + OR NOT EXISTS (SELECT 1 FROM game_session_canonical_binding_transition t + WHERE t.tenant_id=OLD.tenant_id AND t.transition_id=OLD.admission_id + AND t.admission_request_id=OLD.request_id + AND t.status='PROVISIONAL' AND t.original_new_candidate_digest=OLD.candidate_digest) THEN + RAISE EXCEPTION 'Capacity send requires still-current original evidence' USING ERRCODE='23514'; + END IF; + IF OLD.account_send_state='RELEASED_UNSENT' THEN + PERFORM require_gs_capacity_evidence_active_room( + OLD.tenant_id,limits.maximum_records,limits.maximum_binding_bytes,OLD.reserved_binding_bytes); + END IF; + RETURN NEW; + END IF; + RAISE EXCEPTION 'Invalid capacity evidence send transition' USING ERRCODE='23514'; +END; +$$; + +-- Runtime-family catalog registration +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1065.0.21' + ) AND ($needle$; + replacement := $replacement$WHERE version='1065.0.21' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.22' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1065.0.21'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.22'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.21','V1065.0.21__bind_capacity_evidence_charge_request.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.22'',''V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java index 7a33b4d56c..10073e5858 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java @@ -190,25 +190,8 @@ private void prepare( new CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources( binding.dsl(), binding.originalPreparedDecisionWithControlledAccountLease(), directory); region = - CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( - binding.dsl(), - coordination, - coordinationUri, - scripts, - CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture - ::controlledRegionIncarnation, - sources.resolver, - sources.entity, - new RuntimeIdentity( - "game-session-service", - "actual-final-composition", - "localhost", - Instant.now(), - "test", - "test", - "controlled-test-image"), - Duration.ofSeconds(30), - CLOCK); + new CanonicalGameplayRegionBindingBridgeOwner( + composeRegionLeaseOwner("actual-final-composition"), sources.entity); attestor = new CanonicalGameplayControlledInitialObservationFixture(); initialRepository = new CanonicalGameplayAccountInitialBarrierInitializerRepository(binding.dsl()); @@ -954,27 +937,49 @@ public Candidate candidate() { execution, deadline); } + handoffOriginalRegion(deadline); + return reservation; + } + + /** Replaces the original executor through the real acquire and transfer protocol. */ + public void handoffOriginalRegion(long deadline) throws Exception { var repository = new CanonicalGameplayRegionOwnerTransferRepository(binding.dsl(), CLOCK, tags); var receiver = new CanonicalGameplayControlledRegionTransferObservationFixture() .receiver(repository, tags); + var executionOwner = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + binding.dsl(), coordination, scripts, CLOCK, tags); var transfer = new CanonicalGameplayRegionOwnerTransferCoordinator( binding.dsl(), CLOCK, repository, executionOwner, receiver); - administration.sync().pexpire(ascii(regionInstallation.grant.key()), 0); + var original = regionInstallation; + var successor = composeRegionLeaseOwner("final-owner-handoff"); + administration.sync().pexpire(ascii(original.grant.key()), 0); regionInstallation = - CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( - binding.dsl(), - coordination, - coordinationUri, - scripts, - regionInstallation, - sources.resolver, - CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture - ::controlledRegionIncarnation, - transfer, - deadline); - return reservation; + successor.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline); + region = new CanonicalGameplayRegionBindingBridgeOwner(successor, sources.entity); + } + + private CanonicalGameplayRegionLeaseOwner composeRegionLeaseOwner(String instanceId) { + return CanonicalGameplayRegionLeaseOwnerFactory.compose( + binding.dsl(), + coordination, + coordinationUri, + scripts, + CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture::controlledRegionIncarnation, + sources.resolver, + new RuntimeIdentity( + "game-session-service", + instanceId, + "localhost", + Instant.now(), + "test", + "test", + "controlled-test-image"), + Duration.ofSeconds(30), + CLOCK); } public Target target() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index c0f2923b41..765f282177 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -1732,6 +1732,120 @@ void resumedFenceReceiptCannotChangeDispatchedStorageIncarnation() throws Except } } + @Test + void laterReceiptOnlyItemMustMatchTheRetainedOriginalDispatchIncarnation() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID originalId = proof.begin(); + proof.captureAndFence(originalId); + proof.verifyPage(originalId); + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(originalId)); + var installed = proof.install(originalId); + String original = proof.itemImage(originalId); + var dispatch = + proof.sql.fetchSingle( + "SELECT fence_dispatch_id, fence_dispatch_incarnation" + + " FROM game_session_region_owner_transfer_item WHERE transfer_id=?", + originalId); + assertThat(dispatch.get("fence_dispatch_id", UUID.class)).isNotNull(); + String incarnation = dispatch.get("fence_dispatch_incarnation", String.class); + assertThat(incarnation).isNotBlank(); + + UUID laterId = proof.insertRawFrozenTransfer(proof.sql, proof.scope, installed); + proof.insertRawTransferItem(proof.sql, laterId, 0); + String enrolled = proof.itemImage(laterId); + String pin = + "UPDATE game_session_region_owner_transfer SET incarnation_digest=? WHERE transfer_id=?"; + String retain = + "UPDATE game_session_region_owner_transfer_item later SET" + + " fence_readback=original.fence_readback,incarnation_digest=?," + + " before_payload_digest=original.before_payload_digest," + + " after_payload_digest=original.after_payload_digest" + + " FROM game_session_region_owner_transfer_item original" + + " WHERE later.transfer_id=? AND original.transfer_id=?"; + String changed = "sha256:" + "0".repeat(64); + assertThat(changed).isNotEqualTo(incarnation); + assertThatThrownBy(() -> + proof.sql.transaction(configuration -> { + var transaction = DSL.using(configuration); + transaction.execute(pin, changed, laterId); + transaction.execute(retain, changed, laterId, originalId); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Transfer receipt differs from the retained dispatch incarnation"); + assertThat(proof.itemImage(laterId)).isEqualTo(enrolled); + + proof.sql.transaction(configuration -> { + var transaction = DSL.using(configuration); + assertThat(transaction.execute(pin, incarnation, laterId)).isEqualTo(1); + assertThat(transaction.execute(retain, incarnation, laterId, originalId)).isEqualTo(1); + }); + var receipt = + proof.sql.fetchSingle( + "SELECT fence_dispatch_id, incarnation_digest, fence_readback" + + " FROM game_session_region_owner_transfer_item WHERE transfer_id=?", + laterId); + assertThat(receipt.get("fence_dispatch_id", UUID.class)).isNull(); + assertThat(receipt.get("incarnation_digest", String.class)).isEqualTo(incarnation); + assertThat(receipt.get("fence_readback", byte[].class)).isNotEmpty(); + assertThat(proof.itemImage(originalId)).isEqualTo(original); + assertThat(proof.currentOwner()).isEqualTo(installed); + } + } + + @Test + void committedFenceDispatchKeepsItsParentIncarnationAfterOwnerReload() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + long deadline = transferDeadline(); + var dispatch = + proof.transfers.within( + deadline, + ignored -> + proof.transfers.fenceDispatch( + item, proof.receiver.observeForRegionOwnerTransfer(id, 0, deadline))); + assertThat(dispatch.receiptId()).isNotNull(); + String incarnation = dispatch.incarnationDigest(); + assertThat(incarnation).isNotBlank(); + String dispatched = proof.itemImage(id); + String pinned = proof.transferImage(id); + assertThat(pinned).contains(incarnation); + + proof.recreateTransferOwners(); + var reloaded = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.page(id, -1).getFirst()); + long reloadDeadline = transferDeadline(); + var retained = + proof.transfers.within( + reloadDeadline, + ignored -> + proof.transfers.fenceDispatch( + reloaded, + proof.receiver.observeForRegionOwnerTransfer(id, 0, reloadDeadline))); + assertThat(retained.receiptId()).isEqualTo(dispatch.receiptId()); + assertThat(retained.incarnationDigest()).isEqualTo(incarnation); + String changed = "sha256:" + "0".repeat(64); + assertThat(changed).isNotEqualTo(incarnation); + assertThatThrownBy(() -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer SET incarnation_digest=?" + + " WHERE transfer_id=?", + changed, + id)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Region transfer source and completed custody are immutable"); + assertThat(proof.transferImage(id)).isEqualTo(pinned); + assertThat(proof.itemImage(id)).isEqualTo(dispatched); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + } + } + @Test void terminalTransferCompletionRequiresItsExactInstalledSuccessor() throws Exception { try (var proof = new TransferSqlProof()) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index c13292f42e..a5babc57e2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(34); + assertThat(catalog.catalogEpoch()).isEqualTo(35); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -227,7 +227,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1065.0.18", "catalog-installation:1065.0.19", "catalog-installation:1065.0.20", - "catalog-installation:1065.0.21") + "catalog-installation:1065.0.21", + "catalog-installation:1065.0.22") .noneMatch(identity -> identity.contains(":1057:") || identity.contains(":1058:") @@ -262,7 +263,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1065.0.18:") || identity.contains(":1065.0.19:") || identity.contains(":1065.0.20:") - || identity.contains(":1065.0.21:")); + || identity.contains(":1065.0.21:") + || identity.contains(":1065.0.22:")); assertThat( f.dsl .fetchSingle( @@ -799,7 +801,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(34); + assertThat(original.catalog().catalogEpoch()).isEqualTo(35); assertThat(original.catalog().schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_probe_view")) @@ -977,7 +979,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.0.18", "1065.0.19", "1065.0.20", - "1065.0.21")) { + "1065.0.21", + "1065.0.22")) { String columns = "installed_rank,version,description,type,script,checksum,installed_by,execution_time,success"; var original = @@ -1022,7 +1025,7 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( f.dsl.execute("DELETE FROM " + f.history + " WHERE installed_rank=10000"); } } - assertThat(f.owner().capture(request()).catalog().catalogEpoch()).isEqualTo(34); + assertThat(f.owner().capture(request()).catalog().catalogEpoch()).isEqualTo(35); } } From a4a98d223691b43a25eed307ef8a3ec77f86c867 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 29 Nov 2026 13:52:19 +1300 Subject: [PATCH 51/51] Settle exact Account denials after retained Game Session abort --- .../game-session-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 2 +- ...calGameplayBindingInventoryRepository.java | 67 +++++++- ...nonicalGameplayCapacityEvidenceBudget.java | 47 +++-- ...playOriginalNewCapacityExecutionOwner.java | 93 +++++++++- ...yOriginalNewFinalAdmissionCoordinator.java | 32 +++- ...t_capacity_denial_after_region_handoff.sql | 9 +- ...ransferCapacityCustodyIntegrationTest.java | 162 ++++++++++++++++++ 8 files changed, 389 insertions(+), 25 deletions(-) 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 ddd17acc03..512e6a4d54 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -6,7 +6,7 @@ V1063 adds retained exact original capacity execution evidence and the final tra The seven-key tenant-slot final script atomically serializes `FINAL` against permanent same-attempt `CLOSE`, retaining the complete attempt envelope, reservation fence/expiry, original owner and actual committed session hash/times. New execution requires the exact persistent `AUTHORIZED` record and an unexpired reservation at Redis `TIME`. Account transition restrictions, coupled to the irreversible closure, exclude a delayed final CAS after release or rearm without relying on a one-time remote current-fence read. Original evidence is immutable and retained without TTL, deletion or truncation. V1063 separately classifies the evidence family and seals the next runtime-family catalog epoch without changing retained predecessor epochs or migration histories. -Game Session bounds the number and retained bytes of original-NEW capacity execution records per tenant allocation. Its durable owner precharges each exact attempt before dispatch so a full budget can refuse new admissions while preserving room to fence an already charged unresolved original whose execution key is absent. The charge covers the largest permitted execution record for that attempt and is shared by installation, same-attempt closure and transfer fencing. Within the fixed 1 MiB charge, PostgreSQL allows up to 1,048,064 bytes for the canonical execution and reserves 512 bytes for terminal readback. An authenticated exact Account denial, either quota exceeded or expired retained evaluation, can return that attempt’s active count and byte reservation only after Account durably excludes acceptance and Game Session verifies settlement authority under the region lock. The original selected owner can settle while its fence remains current. A successor with a higher installed fence may settle the exact provisional original charge after a read-only Account denial for its recorded request. The successor must prove current ownership of the same protected region and retained original world source under the region and tenant budget locks. The charge must show a possible original send and have no execution record. Settlement retains the original charge binding, the typed denial, and the successor owner, fence and lease correlation. The successor has no authority to issue another send or continue an accepted reservation through this path. The settlement also serializes against execution insertion. The original charge binding, decision kind and identifier remain durable under a separate finite record limit. Exact denied replays use that receipt without contacting Account, and lost or ambiguous Account responses keep the charge active. Exact retries neither increase the charge nor create a new dispatch. An absent or unqualified charge withholds new effects, preserves the original evidence and leaves the Account reservation held. The first creating Account call requires a committed Game Session send claim under the same exact region and tenant budget locks. An unclaimed attempt can release active count and bytes only when a local transaction proves its send permission was never issued. The retained identity and release receipt still count against total history. A new precharge can reclaim one expired unclaimed slot in the same tenant, under the tenant budget lock, even after the original region moves. A new budget requires an explicit retained-history bound. Older immutable budgets without one cannot admit new charges. Exact reacquisition is permitted only while the original authorization and owner remain current, under the existing active ceiling. With its send permission issued, or with unknown predecessor state, the attempt uses Account’s exact read-only reservation probe while the original Account OPEN remains eligible. An exact positive reservation can continue through ordinary FINAL checks. When the probe cannot establish an eligible reservation or the original OPEN has expired, an exact typed durable denial from Account’s read-only outcome can settle the charge. A missing or ambiguous read does not authorize creation, retirement or settlement. After the original Account OPEN window expires, Game Session can still settle a possible send using the exact typed denial and the applicable original or successor settlement authority. Admission remains unavailable. Activation must first exclude any writer that could call Account without acquiring the durable send claim. The [Coordination reset policy](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) governs storage loss and restore. The bounded preparation retains the full binding and reserves no authority to delete evidence. Fleet sizing, operational qualification and an independently approved retirement policy are activation prerequisites. +Game Session bounds the number and retained bytes of original-NEW capacity execution records per tenant allocation. Its durable owner precharges each exact attempt before dispatch so a full budget can refuse new admissions while preserving room to fence an already charged unresolved original whose execution key is absent. The charge covers the largest permitted execution record for that attempt and is shared by installation, same-attempt closure and transfer fencing. Within the fixed 1 MiB charge, PostgreSQL allows up to 1,048,064 bytes for the canonical execution and reserves 512 bytes for terminal readback. An authenticated exact Account denial, either quota exceeded or expired retained evaluation, can return that attempt’s active count and byte reservation only after Account durably excludes acceptance and Game Session verifies settlement authority under the region lock. The original selected owner can settle while its fence remains current. A successor with a higher installed fence may settle the exact original charge after a read-only Account denial for its recorded request. This includes an original still provisional or already durably aborted with its cleanup identity, provided the current region custody still qualifies. A stopped runtime is eligible only after that exact abort and while settlement authority remains current. The successor must prove current ownership of the same protected region and retained original world source under the region and tenant budget locks. The charge must show a possible original send and have no execution record. Settlement retains the original charge binding, the typed denial, and the successor owner, fence and lease correlation. The successor has no authority to issue another send or continue an accepted reservation through this path. The settlement also serializes against execution insertion. The original charge binding, decision kind and identifier remain durable under a separate finite record limit. Exact denied replays use that receipt without contacting Account, and lost or ambiguous Account responses keep the charge active. Exact retries neither increase the charge nor create a new dispatch. An absent or unqualified charge withholds new effects, preserves the original evidence and leaves the Account reservation held. The first creating Account call requires a committed Game Session send claim under the same exact region and tenant budget locks. An unclaimed attempt can release active count and bytes only when a local transaction proves its send permission was never issued. The retained identity and release receipt still count against total history. A new precharge can reclaim one expired unclaimed slot in the same tenant, under the tenant budget lock, even after the original region moves. A new budget requires an explicit retained-history bound. Older immutable budgets without one cannot admit new charges. Exact reacquisition is permitted only while the original authorization and owner remain current, under the existing active ceiling. With its send permission issued, or with unknown predecessor state, the attempt uses Account’s exact read-only reservation probe while the original Account OPEN remains eligible. An exact positive reservation can continue through ordinary FINAL checks. When the probe cannot establish an eligible reservation or the original OPEN has expired, an exact typed durable denial from Account’s read-only outcome can settle the charge. A missing or ambiguous read does not authorize creation, retirement or settlement. After the original Account OPEN window expires, Game Session can still settle a possible send using the exact typed denial and the applicable original or successor settlement authority. Admission remains unavailable. Activation must first exclude any writer that could call Account without acquiring the durable send claim. The [Coordination reset policy](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) governs storage loss and restore. The bounded preparation retains the full binding and reserves no authority to delete evidence. Fleet sizing, operational qualification and an independently approved retirement policy are activation prerequisites. The finalized schema-2 reader requires `capacityExecutionDigest`; predecessor finalized values without it are unsupported by this unregistered preproduction cutover. Before activation or reuse of predecessor-populated storage, establish and resolve retained-data and active original-confirmation or recovery obligations while preserving immutable historical evidence. The [owning tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records this cutover limitation and the unknown inventory of earlier manually persisted data. 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 f2ae9a5779..c9ead62e8f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -36,7 +36,7 @@ Account capacity activation requires an explicit finite V1040.2 refusal budget f V1065.0.5–V1065.0.7 prepare execution evidence budgets, exact Account denial settlement and transfer inventory reservation under the [Game Session execution owner](../../architecture/microservices/game-session-service/runtime-and-data.md#original-new-capacity-execution-evidence). Physical proof covers independent count and byte exhaustion, concurrent last-slot claims, exact replay, absent-key fencing at capacity, stale or restored Redis evidence, a populated catalog upgrade, and frozen-transfer completion and replay at exhaustion. Production budgets, predecessor backfill, deployment-wide sizing, coordinated restore, retention policy, registration and activation remain open. -Game Session V1065.0.17 and the Account retained-outcome method keep the original exact binding from first send through recovery. The Game Session owner records send permission before the first creating RPC, reclaims expired still-unclaimed active slots without deleting history, and uses authenticated read-only Account evidence after a possible send. A missed-denial settlement can recover after OPEN expiry under the original owner. V1065.0.22 adds an exact denial-only path for the currently installed successor. The disposable Account and Game Session handoff fixture proves that an ambiguous observation holds the original charge and an authenticated expired-evaluation denial frees one slot under the successor while retaining the original history. Accepted-reservation continuation remains open. Live activation requires excluding older writers, qualifying explicit tenant budgets and verifying the deployed Coordination Redis authority. +Game Session V1065.0.17 and the Account retained-outcome method keep the original exact binding from first send through recovery. The Game Session owner records send permission before the first creating RPC, reclaims expired still-unclaimed active slots without deleting history, and uses authenticated read-only Account evidence after a possible send. A missed-denial settlement can recover after OPEN expiry under the original owner. V1065.0.22 adds an exact denial-only path for the currently installed successor. The disposable Account and Game Session handoff fixture proves that an ambiguous observation holds the original charge and an authenticated expired-evaluation denial frees one slot under the successor while retaining the original history. The selected owner and installed successor also recover a durably aborted candidate while the region custody still qualifies, including a runtime stopped after that abort. An absent owner, prior execution, or ambiguous Account read keeps the evidence charge held. Accepted-reservation continuation remains open. Live activation requires excluding older writers, qualifying explicit tenant budgets and verifying the deployed Coordination Redis authority. The Game Session parent slice builds on the Account capacity foundation. It owns original-NEW execution, its exact local read/proof, and normal owner handoff. The authenticated Account recovery read and physical cross-service proof remain in the dependent receiving slice. The selected owner retains its original execution and handoff evidence while registration and admission remain held. 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 acd6e63c41..1afdecc66c 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 @@ -891,6 +891,55 @@ OriginalNewFinalAdmissionSource readOriginalNewFinalAdmissionSource( return readOriginalNewSource(originalDecision, OriginalNewSourcePurpose.FINAL_ADMISSION); } + /** Locks the retained first-NEW abort as denial evidence, with no final-admission capability. */ + static OriginalNewAbortedDenialSource lockOriginalNewAbortedDenialSource( + DSLContext transaction, CanonicalGameplayAdmissionDecision expected) { + UUID transitionId = expected.bindingDecisionId(); + Record row = + transaction.fetchOne( + "SELECT * FROM " + TRANSITION + " WHERE transition_id = ? FOR UPDATE", transitionId); + if (row == null || !"ABORTED".equals(row.get("status", String.class))) return null; + requireNoOriginalNewFinalAdmissionReceipt(row); + if (row.get("original_new_capacity_execution_digest") != null) { + throw conflict("Aborted NEW already has capacity execution evidence"); + } + var aborted = + readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( + transaction, transitionId, false); + requireSameAdmissionDecision(expected, aborted.originalDecision()); + byte[] bytes = row.get("original_new_candidate_bytes", byte[].class); + try { + String digest = row.get("original_new_candidate_digest", String.class); + String readbackDigest = row.get("original_new_candidate_readback_digest", String.class); + if (!"READBACK_CONFIRMED".equals(row.get("original_new_candidate_state", String.class)) + || bytes == null + || bytes.length == 0 + || bytes.length > CanonicalGameplayOriginalNewCandidateCodec.MAX_CANDIDATE_BYTES + || !CanonicalGameplayIssuerMemberV2Codec.sha256(bytes).equals(digest) + || readbackDigest == null + || !readbackDigest.matches("sha256:[0-9a-f]{64}")) { + throw conflict("Aborted NEW lacks its exact retained original candidate"); + } + var candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical(bytes); + if (!candidate.matchesOriginalDecision(expected) + || !sameRegionTransferCandidate(candidate, aborted)) { + throw conflict("Aborted NEW differs from its retained original candidate"); + } + return new OriginalNewAbortedDenialSource( + candidate, + digest, + requireOriginalNewFinalRegionAcknowledgement( + transaction, candidate, aborted.transition(), aborted.candidate())); + } finally { + if (bytes != null) Arrays.fill(bytes, (byte) 0); + } + } + + record OriginalNewAbortedDenialSource( + CanonicalGameplayOriginalNewCandidate candidate, + String candidateDigest, + CanonicalGameplayBindingRegionBridgeObligation regionAcknowledgement) {} + /** * Reads a retained COMMITTED original only as topology input for normal region handoff. * @@ -1970,6 +2019,13 @@ private static BridgeInputs requireBridgeInputs( private static void requireCurrentRegionOwner( DSLContext transaction, CanonicalGameplayRegionRuntimeStatus expected) { + requireCurrentRegionOwner(transaction, expected, true); + } + + static void requireCurrentRegionOwner( + DSLContext transaction, + CanonicalGameplayRegionRuntimeStatus expected, + boolean requireOriginalWatermark) { Record row = transaction.fetchOne( "SELECT * FROM game_session_region_runtime_status" @@ -1998,11 +2054,12 @@ private static void requireCurrentRegionOwner( || !Objects.equals( row.get("preparation_input_digest", String.class), expected.preparationInputDigest()) || !Boolean.FALSE.equals(row.get("paused", Boolean.class)) - || !Objects.equals( - row.get("last_committed_tick_id", Long.class), expected.lastCommittedTickId()) - || !Objects.equals( - row.get("last_committed_tick_batch_id", String.class), - expected.lastCommittedTickBatchId())) { + || (requireOriginalWatermark + && (!Objects.equals( + row.get("last_committed_tick_id", Long.class), expected.lastCommittedTickId()) + || !Objects.equals( + row.get("last_committed_tick_batch_id", String.class), + expected.lastCommittedTickBatchId())))) { throw conflict("Durable region owner, timeline, or executor fence changed"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java index c236bae9c9..01e0116e2c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityEvidenceBudget.java @@ -180,6 +180,26 @@ static void settleDenied( if (settled != 1) throw unavailable(); } + static RetainedCharge reconcileSelectedDenial( + DSLContext tx, + Request request, + String candidateDigest, + CanonicalGameplayOriginalNewCapacityExecutionOwner.CurrentOwner selected, + String tag, + Refusal denial) { + lockBudget(tx, request, tag); + var charge = exactCharge(tx, request, candidateDigest, selected, tag); + requirePossibleSendWithoutExecution(tx, request, charge); + var retained = retainedDenial(charge); + if (retained != null) { + if (denial != null && !retained.equals(denial)) throw unavailable(); + return new RetainedCharge(retained, false); + } + if (denial == null) return new RetainedCharge(null, true); + settleDenied(tx, request, candidateDigest, selected, tag, denial); + return new RetainedCharge(denial, false); + } + static RetainedCharge reconcileSuccessorDenial( DSLContext tx, Request request, @@ -190,16 +210,10 @@ static RetainedCharge reconcileSuccessorDenial( Refusal denial) { lockBudget(tx, request, tag); var charge = exactChargeIdentity(tx, request, candidateDigest, tag); - if (charge == null - || !Long.valueOf(originalFence).equals(charge.get("selected_owner_fence", Long.class)) - || tx.fetchOne( - "SELECT 1 FROM game_session_original_new_capacity_execution" - + " WHERE admission_attempt_id=? OR transition_id=? LIMIT 1", - request.admissionAttemptId(), - request.identity().admissionId()) - != null) throw unavailable(); - String state = charge.get("account_send_state", String.class); - if (state != null && !"MAY_HAVE_SENT".equals(state)) throw unavailable(); + requirePossibleSendWithoutExecution(tx, request, charge); + if (!Long.valueOf(originalFence).equals(charge.get("selected_owner_fence", Long.class))) { + throw unavailable(); + } var retained = retainedDenial(charge); if (retained != null) { if (denial != null && !retained.equals(denial)) throw unavailable(); @@ -224,6 +238,19 @@ static RetainedCharge reconcileSuccessorDenial( return new RetainedCharge(denial, false); } + private static void requirePossibleSendWithoutExecution( + DSLContext tx, Request request, Record charge) { + if (charge == null + || tx.fetchOne( + "SELECT 1 FROM game_session_original_new_capacity_execution" + + " WHERE admission_attempt_id=? OR transition_id=? LIMIT 1", + request.admissionAttemptId(), + request.identity().admissionId()) + != null) throw unavailable(); + String state = charge.get("account_send_state", String.class); + if (state != null && !"MAY_HAVE_SENT".equals(state)) throw unavailable(); + } + static void requireCharge(DSLContext tx, OriginalNewCapacityExecution execution, String tag) { var charge = exactCharge( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 3a11b238d8..36a497bb48 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -33,6 +33,7 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import org.jooq.DSLContext; @@ -142,7 +143,7 @@ CurrentOwner requireRequestBinding( if (budget == null) return within(deadline, owner -> owner.requireRequestBinding(source, request, deadline)); budget.check(); - requireExactRequest(source, request); + requireExactRequest(source.candidate(), request); CurrentOwner selected = currentOwner(source.candidate()); if (selected.fence() != source.regionAcknowledgement().executorFence().longValueExact()) throw unavailable(); @@ -150,11 +151,9 @@ CurrentOwner requireRequestBinding( } private static void requireExactRequest( - CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, - Request request) { + CanonicalGameplayOriginalNewCandidate candidate, Request request) { // Account owns fresh policy denial; coherent non-creating evidence must reach that owner. request.requireStructurallyValid(); - var candidate = source.candidate(); var binding = candidate.bindingIdentity(); var target = candidate.targetEvidence(); if (!(request.context() instanceof PlayerContext player) @@ -192,7 +191,7 @@ CanonicalGameplayCapacityEvidenceBudget.RetainedCharge reconcileSuccessorDenial( return within( deadline, owner -> { - requireExactRequest(source, request); + requireExactRequest(source.candidate(), request); OriginalNewCapacityExecution.requireOriginalNewRequest(request); var successor = installation.status; var original = source.regionAcknowledgement(); @@ -235,6 +234,90 @@ CanonicalGameplayCapacityEvidenceBudget.RetainedCharge reconcileSuccessorDenial( }); } + /** The retained abort only permits reading or settling one possible-send charge. */ + CanonicalGameplayCapacityEvidenceBudget.RetainedCharge reconcileAbortedDenial( + CanonicalGameplayAdmissionDecision decision, + Request request, + CanonicalGameplayRegionLeaseOwner.Installation installation, + Refusal denial, + long deadline) { + OriginalNewCapacityExecution.requireOriginalNewRequest(request); + var installed = installation.status; + var identity = decision.candidate(); + if (!decision.bindingDecisionId().equals(installation.transitionId) + || !identity.tenantId().equals(installed.tenantId()) + || !identity.gameInstanceId().equals(installed.gameInstanceId()) + || !identity.regionId().equals(installed.regionId()) + || identity.regionEpoch().longValueExact() != installed.regionEpoch()) { + throw unavailable(); + } + return within( + deadline, + owner -> + owner + .sql() + .transactionResult(configuration -> { + var tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + var selected = + new CurrentOwner( + installed.ownerInstanceId(), installed.executorFence().longValueExact()); + tx.fetch( + "SELECT require_gs_capacity_send_owner(?,?,?,?)", + identity.tenantId(), + decision.bindingDecisionId(), + selected.instanceId(), + selected.fence()); + var source = + CanonicalGameplayBindingInventoryRepository + .lockOriginalNewAbortedDenialSource(tx, decision); + if (source == null) return null; + + requireExactRequest(source.candidate(), request); + var original = source.regionAcknowledgement(); + long originalFence = original.executorFence().longValueExact(); + if (selected.fence() < originalFence) throw unavailable(); + var assignment = + owner + .scopedTags() + .readAssignmentForRetainedCapacityExecution( + tx, decision.bindingDecisionId()); + if (selected.fence() > originalFence) { + tx.fetch( + "SELECT require_gs_capacity_denial_successor(?,?,?,?,?,?,?,?)", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + source.candidateDigest(), + originalFence, + selected.instanceId(), + selected.fence(), + installed.leaseTokenCorrelation()); + return CanonicalGameplayCapacityEvidenceBudget.reconcileSuccessorDenial( + tx, + request, + source.candidateDigest(), + assignment.tenantGameplayTag(), + originalFence, + installed, + denial); + } + + if (!original.leaseTokenCorrelation().equals(installed.leaseTokenCorrelation())) { + throw unavailable(); + } + CanonicalGameplayBindingInventoryRepository.requireCurrentRegionOwner( + tx, installed, false); + return CanonicalGameplayCapacityEvidenceBudget.reconcileSelectedDenial( + tx, + request, + source.candidateDigest(), + selected, + assignment.tenantGameplayTag(), + denial); + })); + } + /** Checks the caller's complete original request against the execution linked by the receipt. */ CommittedCapacitySource requireCommittedRequest( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index 6b3a161b17..6e9051df90 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -111,8 +111,17 @@ FinalAdmissionResult completeOriginalNew( throw unavailable(); } - CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source = - inventory.readOriginalNewFinalAdmissionSource(originalDecision); + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source; + try { + source = inventory.readOriginalNewFinalAdmissionSource(originalDecision); + } catch (CanonicalGameplayBindingInventoryConflictException finalUnavailable) { + Refusal denial = + reconcileAbortedDenial( + originalDecision, capacityRequest, + privateRegionInstallation, absoluteDeadlineMillis); + if (denial != null) throw CapacityRefusedException.retainedAdmissionDenial(denial); + throw finalUnavailable; + } requireOriginalSource(source, originalDecision); if (source.transitionStatus() == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL && capacityRequest.evidence().permitsCreation() @@ -388,6 +397,25 @@ originalLoginJwt, originalLeaseBytes, operationDeadline(absoluteDeadlineMillis)) } } + private Refusal reconcileAbortedDenial( + CanonicalGameplayAdmissionDecision decision, + TenantCapacityAdmission.Request request, + CanonicalGameplayRegionLeaseOwner.Installation installation, + long deadline) { + if (!request.evidence().permitsCreation()) return null; + var charge = + capacityExecution.reconcileAbortedDenial(decision, request, installation, null, deadline); + if (charge == null) return null; + if (!charge.possibleSend()) return charge.accountDenial(); + var accountDenial = capacityClient.readRetainedAdmissionDenial(request, deadline); + if (accountDenial == null) throw unavailable(); + var settled = + capacityExecution.reconcileAbortedDenial( + decision, request, installation, accountDenial, deadline); + if (settled == null || !accountDenial.equals(settled.accountDenial())) throw unavailable(); + return settled.accountDenial(); + } + private static void requireDenialScope( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, CanonicalGameplayRegionLeaseOwner.Installation installation, diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql index e78e7b528f..fe075aaa58 100644 --- a/services/game-session-service/src/main/resources/db/migration/V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.22__settle_exact_capacity_denial_after_region_handoff.sql @@ -31,7 +31,14 @@ BEGIN AND r.region_epoch=b.region_epoch WHERE t.transition_id=p_admission AND t.tenant_id=p_tenant AND b.tenant_id=p_tenant AND t.admission_request_id=p_request AND t.original_new_candidate_digest=p_candidate - AND t.status='PROVISIONAL' AND b.status='ACKNOWLEDGED' + AND (t.status='PROVISIONAL' + OR (t.status='ABORTED' AND t.admission_orphan_cleanup_id IS NOT NULL)) + AND t.original_new_final_session_sha256 IS NULL + AND t.original_new_capacity_execution_digest IS NULL + AND t.original_new_admission_at_ms IS NULL + AND t.original_new_continuity_expires_at_ms IS NULL + AND t.original_new_session_duration_ms IS NULL + AND b.status='ACKNOWLEDGED' AND b.executor_fence=p_original_fence AND r.lease_token_correlation=p_correlation AND r.canonical_region_id=b.canonical_region_id AND r.lifecycle_epoch=b.world_lifecycle_epoch diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java index 4e40ad951a..2c14bbc140 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java @@ -2,6 +2,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; @@ -20,9 +27,12 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient; +import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient.CapacityRefusedException; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; @@ -121,6 +131,148 @@ void installedSuccessorSettlesOnlyTheExactDurableDenialForPossibleAccountSend() } } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "false,false", + "false,true", + "true,false", + "true,true" + }) + void exactRetainedDenialSettlesAnAbortedOriginalWithTheCurrentOwner( + boolean successor, boolean stopped) throws Exception { + try (var proof = new TransferSqlProof(true)) { + var execution = proof.execution; + var request = execution.request(); + var original = proof.region.installation(); + String tag = proof.tags.assignmentForTransition(execution.transitionId()).tenantGameplayTag(); + assertThat(proof.authorizeAccountSend(execution)) + .isEqualTo(AccountTenantCapacityClient.SendDisposition.AUTHORIZE_NEW); + + var installed = successor ? installSuccessor(proof, proof.begin()) : original; + var abort = proof.fixture.recordOriginalAccountAbort(); + assertThat(abort.isAccountAborted()).isTrue(); + if (stopped) proof.fixture.stopRuntime(); + + var decision = abort.originalDecision(); + var inventory = new CanonicalGameplayBindingInventoryRepository(proof.sql); + assertThatThrownBy(() -> inventory.readOriginalNewFinalAdmissionSource(decision)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + var before = readCharge(proof, execution); + var client = mock(AccountTenantCapacityClient.class); + var coordinator = denialCoordinator(proof, inventory, client); + if (successor) { + assertThatThrownBy(() -> + coordinator.completeOriginalNew( + decision, "unused", original, 120_000L, transferDeadline(), request)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client); + assertThat(readCharge(proof, execution)).isEqualTo(before); + } + + var denial = new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, UUID.randomUUID()); + when(client.readRetainedAdmissionDenial(eq(request), anyLong())).thenReturn(denial); + for (int replay = 0; replay < 2; replay++) { + assertThatThrownBy(() -> + coordinator.completeOriginalNew( + decision, "unused", installed, 120_000L, transferDeadline(), request)) + .isInstanceOfSatisfying( + CapacityRefusedException.class, + failure -> { + assertThat(failure.code()).isEqualTo(denial.code()); + assertThat(failure.durableDenialId()).isEqualTo(denial.durableDenialId()); + }); + } + verify(client).readRetainedAdmissionDenial(eq(request), anyLong()); + verifyNoMoreInteractions(client); + assertThat(readCharge(proof, execution)) + .containsEntry("account_send_state", "MAY_HAVE_SENT") + .containsEntry("account_denial_id", denial.durableDenialId()) + .containsEntry("account_denial_kind", denial.code().name()) + .containsEntry( + "denial_settlement_owner_fence", + successor ? installed.status.executorFence().longValueExact() : null); + assertThat(proof.currentOwner()).isEqualTo(installed.status); + assertThat(proof.executionState(execution)).isNull(); + assertThat(proof.physicalExecutionExists(execution, tag)).isFalse(); + } + } + + @Test + void abortedDenialKeepsTheChargeWithoutExactAttemptOwnerAndAccountDenial() throws Exception { + try (var proof = new TransferSqlProof(true)) { + var original = proof.execution; + var request = original.request(); + var absent = + new Request( + request.identity(), + UUID.randomUUID(), + request.capacityRearmFence(), + request.targetNamespace(), + request.context(), + request.operation(), + request.priorShape(), + request.requestedShape(), + request.evidence(), + request.capacityDelta(), + null) + .withDigest(); + assertThat(proof.authorizeAccountSend(original)) + .isEqualTo(AccountTenantCapacityClient.SendDisposition.AUTHORIZE_NEW); + var decision = proof.fixture.recordOriginalAccountAbort().originalDecision(); + var installation = proof.region.installation(); + var client = mock(AccountTenantCapacityClient.class); + var coordinator = + denialCoordinator( + proof, new CanonicalGameplayBindingInventoryRepository(proof.sql), client); + var before = readCharge(proof, original); + + assertThatThrownBy(() -> + coordinator.completeOriginalNew( + decision, "unused", installation, 120_000L, transferDeadline(), absent)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client); + when(client.readRetainedAdmissionDenial(eq(request), anyLong())) + .thenThrow(io.grpc.Status.UNKNOWN.asRuntimeException()); + assertThatThrownBy(() -> + coordinator.completeOriginalNew( + decision, "unused", installation, 120_000L, transferDeadline(), request)) + .isInstanceOf(IllegalStateException.class); + verify(client).readRetainedAdmissionDenial(eq(request), anyLong()); + assertThat( + proof.sql.execute( + "DELETE FROM game_session_region_runtime_status" + + " WHERE tenant_id=? AND game_instance_id=? AND region_id=?", + installation.status.tenantId(), + installation.status.gameInstanceId(), + installation.status.regionId())) + .isOne(); + assertThatThrownBy(() -> + coordinator.completeOriginalNew( + decision, "unused", installation, 120_000L, transferDeadline(), request)) + .isInstanceOf(IllegalStateException.class); + verifyNoMoreInteractions(client); + assertThat(readCharge(proof, original)).isEqualTo(before); + assertThat(proof.executionState(original)).isNull(); + } + } + + private static CanonicalGameplayOriginalNewFinalAdmissionCoordinator denialCoordinator( + TransferSqlProof proof, + CanonicalGameplayBindingInventoryRepository inventory, + AccountTenantCapacityClient capacity) { + return new CanonicalGameplayOriginalNewFinalAdmissionCoordinator( + inventory, + mock(), + mock(), + mock(), + proof.region.owner(), + mock(), + mock(), + proof.clock, + capacity, + proof.capacity(proof.sql)); + } + @Test void successorCannotSettlePossibleAcceptedEffectWithExecutionCustody() throws Exception { try (var proof = new TransferSqlProof(true)) { @@ -163,6 +315,16 @@ void successorCannotSettlePossibleAcceptedEffectWithExecutionCustody() throws Ex assertThat(failure.getServerErrorMessage().getMessage()) .isEqualTo("Successor denial requires a charge without execution custody"); }); + var decision = proof.fixture.recordOriginalAccountAbort().originalDecision(); + var client = mock(AccountTenantCapacityClient.class); + var coordinator = + denialCoordinator( + proof, new CanonicalGameplayBindingInventoryRepository(proof.sql), client); + assertThatThrownBy(() -> + coordinator.completeOriginalNew( + decision, "unused", installed, 120_000L, transferDeadline(), original.request())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client); assertThat(readCharge(proof, original)).isEqualTo(beforeDenial); assertThat(proof.executionState(original)).isEqualTo("INSTALL_DISPATCHED"); assertThat(proof.currentOwner()).isEqualTo(installed.status);