diff --git a/.github/actions/check-gradle-module/action.yml b/.github/actions/check-gradle-module/action.yml index bbe058f637..bc8e463197 100644 --- a/.github/actions/check-gradle-module/action.yml +++ b/.github/actions/check-gradle-module/action.yml @@ -110,6 +110,15 @@ runs: name: test-logs-${{ inputs.module }}-${{ inputs.partition }}-${{ github.sha }}-attempt-${{ github.run_attempt }} path: ${{ inputs.module == 'load-testing' && 'dev-tools/load-testing/build/reports/tests/' || format('services/{0}/build/reports/tests/', inputs.module) }} + - name: 📤 Upload SpotBugs Reports if Failed + if: ${{ failure() || cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: spotbugs-${{ inputs.module }}-${{ inputs.partition }}-reports-${{ github.sha }}-attempt-${{ github.run_attempt }} + path: ${{ inputs.module == 'load-testing' && 'dev-tools/load-testing/build/reports/spotbugs/' || format('services/{0}/build/reports/spotbugs/', inputs.module) }} + if-no-files-found: warn + retention-days: 14 + - name: 📤 Upload JUnit Test Results if: ${{ always() && inputs.module != 'account-service' && inputs.module != 'game-session-service' && inputs.module != 'world-management-service' }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 diff --git a/build.gradle.kts b/build.gradle.kts index a9413a7d43..2b495aca92 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -352,6 +352,9 @@ subprojects { tasks.withType().configureEach { enabled = fullCheck + reports.create("xml") { + required.set(true) + } excludeFilter.set(rootProject.file("config/spotbugs/spotbugs-exclude.xml")) when (name) { "spotbugsMain" -> dependsOn("compileJava", "processResources") diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index ed22bd13e6..eb752471ce 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -125,9 +125,9 @@ For an initial region timeline whose durable preparation is `INITIALIZING` after - Region-to-instance mapping is flexible and driven by a scheduler or consistent-hashing layer that assigns `` values to Game Session instances. - **Target state:** replacement does not make the runtime mapping a durable playable-state identity. Game Session carries the catalog-derived `{playableStateNamespaceId, playableStateScope}` and, when applicable, the canonical private/playtest lifecycle proof tuple `{playtestLifecycleId, playtestStateGeneration}` with the active `{tenantId, gameInstanceId}` binding and persists the compatibility proof’s exact target World `PREPARING` state/epoch as the activation precondition. World alone CAS-activates that target to `ACTIVE`, then issues one equality-only `cutoverHoldId`/`cutoverHoldFence`; Game Session persists the resulting exact source/target `ACTIVE` state/epochs and hold identity in the execution result. Before the pointer CAS, Game Session commits the source admission/write fence, and every already-admitted durable source write must have authoritative `APPLIED` or `NOT_APPLIED` proof plus a durable retry/recovery record when not applied; vague flush-or-reconcile status is insufficient. It then performs fresh lifecycle, freshness, and hold revalidation; only matching evidence may proceed to that CAS. The request digest covers only known request/preparation inputs, while the idempotent execution result/readback binds the World-issued proofs, hold, namespace/scope tuple, and applicable lifecycle proof tuple. Game Session accepts the pointer move only after owner-local S1/S2/S3 compatibility evidence, exact source/target `ACTIVE` proofs, expected pointer version, hold binding, and idempotent source-cleanup work registration are in the same pointer/audit/prepared-execution/source-cleanup/drain-fence transaction. The post-swap reconciler obtains authoritative pointer/readback confirmation of that same lifecycle-proof-bound cleanup-work registration and source binding before asking World to finalize the hold and requesting World’s `TERMINATING` transition; this is not the all-owner terminal cleanup acknowledgement, which follows in World’s `TERMINATING` workflow before `TERMINATED`. Public production omits both playtest fields and rejects supplied values. A cleanup acknowledgement is not a pointer-CAS substitute. Temporal lifecycle status is coordination evidence; the World Management database row/epoch remains authoritative. The current wire, durable artifact/readback, digest coverage, hold record, and focused proof do not yet provide those complete replacement guarantees; see the [Game Session API contract](./api-contracts.md#world-lifecycle-and-admission-boundary) and [runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). -- To scale out, operators add more Game Session pods and allow the scheduler to assign regions to new instances; each instance acquires leases for its assigned regions. -- To rebalance load, an instance can stop renewing the lease for selected regions and drain in-flight work to a safe point; other instances then acquire those leases and continue tick processing from the existing Redis state. This is target state for a region with an installed original NEW owner: the current acquire/install path refuses its replacement (see [original NEW normal-handoff continuation](#original-new-normal-handoff-continuation)), so do not drain such a region expecting a takeover. -- Combined with region sizing, splitting hot regions and merging cold ones, this lease-based ownership model allows FireMUD to scale horizontally without global downtime. +- **Target-only scaling procedure, not a current operator recovery path:** after the replacement/continuation guarantees above are implemented and qualified, the scheduler is intended to assign regions to additional Game Session pods and each instance to acquire its assigned leases. +- The target rebalance protocol drains selected regions, stops their renewal, and permits a replacement owner to continue only after the complete owner-authority and continuation checks above pass. Current acquire/install refuses replacement of an installed owner. Do not stop renewal and reacquire as a workaround or assume existing Redis state authorizes continuation; keep the affected scope held when current ownership cannot continue safely. +- Region splitting/merging and no-downtime horizontal scaling remain target behavior until those replacement guarantees have measured qualification. - The same externalized-state model supports ADR 0013's bounded ordinary restart recovery. A qualifying single-pod restart targets recovery within 10 seconds without client re-`LOGIN` or re-`PLAY`. If continuation authority cannot be established safely, hidden recovery must terminate immediately; otherwise 30 seconds is the hard maximum before falling back to `1013/backend_unavailable`. Operational proof must cover planned and abrupt real Game Session replacement, retained edge sockets, authority and presence convergence, input-buffer behavior, the early fail-closed authority cutoff, and the elapsed-time cutoff. ## Local Development Path 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 3738206889..7a9c09a2c7 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -96,7 +96,7 @@ The sections below define the target-state runtime contract. Current implementat - Hidden same-type Game Session recovery within ADR 0013's qualifying conditions remains an implementation or proof gap; the target is to preserve the session through upstream rebind rather than require a player-visible re-`LOGIN` / re-`PLAY` cycle. - The live `startSession` path keeps the Game Session row and runtime projection `STARTING` until World confirms its fenced `PREPARING -> ACTIVE` transition, then records `RUNNING`; failures before an activation attempt use the existing pre-activation cleanup. Once activation may have been issued or committed, an activation error or ambiguous result, or a later local runtime-state save/finalization failure, retains both the runtime projection and local owner row as `STARTING`, and never calls stale-epoch `failPrepared` or deletes either record. A failure proven before any World termination request is issued may restore the prior `RUNNING` row and runtime state while the World remains `ACTIVE`; once a termination request may have been issued, an error or ambiguous result leaves the local row `STOPPING` and runtime projection absent. Confirmed World termination retries local `STOPPED` finalization and never restores `RUNNING`. Durable stable lifecycle-operation identity and lifecycle readback/reconciliation remain unimplemented, so these local fail-closed quarantines are not a replacement for the target durable lifecycle cleanup workflow. - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. -- The prepared, unregistered region owner consumes exact World initial-placement/currentness and lifecycle reads plus Entity’s authenticated runtime reference. It durably prepares a non-admitting initial timeline, conditionally installs complete same-slot initial Redis metadata and the actual region lease, installs the matching SQL executor fence, and records the first-NEW region bridge acknowledgement. The timeline begins at `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`); existing or reset state cannot be adopted as a new timeline. Original retries retain the preparation, source and lease evidence. A committed `INITIALIZING` preparation whose Redis initialization never executes remains non-admitting and cannot automatically recover from absent keys; the scope remains fenced under the [operations recovery boundary](./operations.md#initial-region-timeline-recovery-boundary). The controlled authenticated actual-owner composition now has focused local proof; the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-initial-player-location-preparation) records its scope and remaining public qualification. Forward V1043 preserves the original timeline migration while aligning its binding-reference carrier with the existing 6,144-byte physical codec bound; the canonical three-UUID frame is 133 bytes and cannot fit the former 128-byte check. Forward V1044 makes the existing lease-bound runtime fence consume the exact retained Human completion, matching `COMMITTED` initial attempt, current `OPEN` pointer and audit under the existing runtime row lock. The original run-owned checks remain owner-specific; absence of both qualified sources is refused. This is manual owner preparation, not registered tick execution, final player binding or production admission. The [Redis owner contract](../../system-architecture-redis.md#key-naming-and-shard-discipline) remains authoritative for timeline and lease semantics. +- The prepared, unregistered region owner consumes exact World initial-placement/currentness and lifecycle reads plus Entity’s authenticated runtime reference. It durably prepares a non-admitting initial timeline, conditionally installs complete same-slot initial Redis metadata and the actual region lease, installs the matching SQL executor fence, and records the first-NEW region bridge acknowledgement. The timeline begins at `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`); existing or reset state cannot be adopted as a new timeline. Original retries retain the preparation, source and lease evidence. A committed `INITIALIZING` preparation remains non-admitting until the owner completes initialization; otherwise it stays held under the [operations recovery boundary](./operations.md#initial-region-timeline-recovery-boundary). The controlled authenticated actual-owner composition now has focused local proof; the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-initial-player-location-preparation) records its scope and remaining public qualification. Forward V1043 preserves the original timeline migration while aligning its binding-reference carrier with the existing 6,144-byte physical codec bound; the canonical three-UUID frame is 133 bytes and cannot fit the former 128-byte check. Forward V1044 makes the existing lease-bound runtime fence consume the exact retained Human completion, matching `COMMITTED` initial attempt, current `OPEN` pointer and audit under the existing runtime row lock. The original run-owned checks remain owner-specific; absence of both qualified sources is refused. This is manual owner preparation, not registered tick execution, final player binding or production admission. The [Redis owner contract](../../system-architecture-redis.md#key-naming-and-shard-discipline) remains authoritative for timeline and lease semantics. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). - The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. @@ -327,7 +327,9 @@ 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. Before that SQL claim, the owner validates the registered script descriptor and digest-checked bytes, connects, verifies `ACL WHOAMI`, and loads the script on the same 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. 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 is a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for this cut. 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: the `PREPARED`-to-`INITIALIZING` transaction persists a fresh, unpredictable claim generation, and only that transition grants creation of initial Redis metadata from a proved-absent preimage. One registered deadline-bound timeline script serves absence `PROBE`, `INITIALIZE`, and `VERIFY`. Before the prepared probe, Game Session samples Redis `TIME` on the authenticated, non-reconnecting connection it will use for initialization. It adds the remaining local budget measured after the sample returns, rounded down to whole milliseconds, and freezes that server-clock cutoff for both the prepared `PROBE` and `INITIALIZE`. Redis refuses an expired probe before the SQL creation permission is consumed, checks `TIME` and both write permissions before writing either key, refuses an expired initialization before any write, and caps a new lease at the remaining deadline. A `PREPARED` row claims creation only after the prepared `PROBE` proves absence and create permission. The operation independently enforces its local monotonic budget. 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`, `TIME`, 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. Only after those checks succeed does the owner claim the SQL permission and immediately invoke the prepared session once; each permit can dispatch only once. Any failure after the claim, including an expired or permission-refused `INITIALIZE`, a process stop between claim and send, or an ambiguous send/result, leaves the preparation `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 is a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for this cut. 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). + +Manual initial lease installation requires a non-reconnecting Coordination Redis client and a Hikari-backed PostgreSQL datasource whose active connections can be retired. Sampling removes fixed clock offset. Activation remains held pending deployment-owned evidence that the Redis clock and server incarnation preserve the cutoff through dispatch, including across backward clock steps or store restoration. See the [Coordination Redis recovery boundary](../../system-architecture-redis-reset-and-recovery.md#coordination-reset-model). The lease TTL must exceed the installation window, and the initial SQL transaction requires an exact renewed grant that covers its remaining budget. Lost-completion recovery still reads the original grant without renewal. ## Reconnection and Disconnect Handling 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 9a00934f7c..237f7b61a4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,9 +34,15 @@ The Account source/transport foundation contains unregistered TENANT_OPERATION a ### Strict tenant-capacity owner preparation -The [shared capacity-admission/v1 schema](../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json), typed digest, exact-presence RPC and codec prepare the Account commitment boundary. [V1040](../../../services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql) stores immutable hash-bound Account evaluation, stable reservation and attempt identity, fenced recovery evidence, and held and used units. The actual player entitlement owner retains its evaluation in the final source transaction. The exact fresh tenant association and same-transaction creator bootstrap are the only source of initial zero usage. +Account capacity activation requires an explicit finite V1040.2 refusal budget for each supported tenant. The controlled fixtures install their own limit. An unregistered Account-local provisioning/readiness component now accepts an explicit finite lifetime limit and bounded cohort headroom, with same-value idempotency and no reset or limit replacement. Three focused physical cases pass: existing-tenant provisioning preserves the row and xmin on exact retry, mismatched sizing and absent tenant budgets refuse readiness, exhausted budgets remain unchanged, and the actual Account/Game Session coordinator retains and replays the exact quota denial while settling the last active evidence charge. Deployment policy sizing, operator custody and activation remain open. A missing budget leaves the exact attempt and Game Session evidence charge held. -The unregistered Account owner prepares exact initial reservation, replay and conflict. The recovery worker uses an exact selected-owner observation to finalize, release or rearm the original reservation. Missing and ambiguous observations retain the hold through bounded quarantine. Focused Account proof covers the ledger, fresh and historical bootstrap, exact replay, refusal and controlled recovery. The default Account runtime refuses the legacy numeric entitlement route and has no registered capacity receiver or recovery worker. +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. + +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 [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. + +[V1040](../../../services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql) prepares Account's durable evaluation, usage, reservation, attempt-history and recovery-claim storage. The actual player entitlement owner retains its returned bundle inside the final source transaction. A new creator bootstrap establishes both usage dimensions at zero only against the exact fresh association created in that same transaction; importing/replaying an older tenant does not initialize it. Complete deferred reservation-inventory constraints bind held/used units. The owner prepares one-reservation creation, exact replay/conflict, and Account-only fenced finalization/release/rearm. No second reservation or usage increment is created by rearm, and old attempts cannot replay after it. Ambiguous selected-owner execution remains reserved and non-rearmable. The staged [Game Session capacity client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java) is manually composed and unregistered. It accepts only a plain `host:port` or `dns:///host:port` target, on a dedicated channel that ignores resolver service config. A case-insensitive `DNS` scheme and the single-slash `dns:/host:port` spelling are also accepted, and every accepted target is normalized to the canonical `dns:///host:port` form. It requires the exact same-namespace Account mTLS peer before releasing the request body, carries the complete typed request and verifies the exact response binding. Its commit call uses the minimum of the remaining absolute admission budget, incoming deadline and five-second cap, with bounded request/response sizes and no automatic mutation retry. The retained-denial recovery read runs in a forked context, so it ignores the expired admission context and is bounded only by its own absolute deadline and the five-second cap. A timeout, transport failure or inexact response leaves the original commitment indeterminate; the client neither admits gameplay nor performs an owner activation CAS. @@ -46,11 +52,39 @@ Account [V1040.1](../../../services/account-service/src/main/resources/db/migrat Existing focused proof anchors include the [Account owner units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java), [creation/ledger/recovery PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java), [player-owner retained-denial case](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java), [migration/refusal-slot cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java), [shared codec cases](../../../services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java) and [Game Session client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java). These cover controlled owner/storage, exact refusal/replay and separate loopback transport boundaries, not a genuine cross-owner runtime-admission chain. The codec cases now prepare contradictory billing-refusal rejection on both encode and decode while preserving valid non-creating billing evidence and quota-denial invariants. -The unregistered retained-denial read composes the Game Session client, the authenticated Account mTLS receiver, and physical PostgreSQL. The fixture recovers the original decision after quota headroom returns and the original evaluation expires, then verifies unchanged reservation, usage, refusal slot and denial rows. A separate controlled transport test verifies exact readback after an ambiguous commit call (`UNAVAILABLE` or no reply) without issuing another commit; the PostgreSQL fixture remains the proof that Account returns the original retained denial. Recovery from a persisted Game Session reserve after a real process restart still needs proof. Before activation, the Game Session settlement owner must prove that a delayed exact denial cannot mutate the reserve or its charge after its local fence advances, with an unchanged-fence control that settles the original reserve. +The unregistered retained-denial read composes the Game Session client, the authenticated Account mTLS receiver, and physical PostgreSQL. The fixture recovers the original decision after quota headroom returns and the original evaluation expires, then verifies unchanged reservation, usage, refusal slot and denial rows. A separate controlled transport test verifies exact readback after an ambiguous commit call (`UNAVAILABLE` or no reply) without issuing another commit; the PostgreSQL fixture remains the proof that Account returns the original retained denial. A controlled cross-owner composition now also settles the original charged attempt after its observed OPEN proof expires, then replays the same denial with Account offline. The case verifies one original commit and one read-only denial request. The paired delayed-denial fixture exercises both settlement under the unchanged reserve fence and refusal without reserve or charge mutation after a physical fence advance during the authenticated read. Recovery from a persisted Game Session reserve after a real process restart still needs proof. The Account owner can retry a rolled-back PostgreSQL serialization failure up to three times in fresh transactions, with short randomized delays and one retry-admission deadline. The player evaluation transaction rolls back and reports source unavailability when exact retention readback fails. An exact reservation replay in RELEASED or QUARANTINED state cannot authorize original NEW execution. -Game Session original-NEW execution and its authenticated recovery source, normal owner handoff, and the origin and historical FINAL receiving paths remain dependent work. Finalized usage retirement and settlement remain deferred: they require a genuine admitted-session teardown receipt from the selected owner and an exactly-once Account usage transition that preserves finalized replay. Bounded conservation and owner-governed evidence retention remain downstream. Preserve immutable predecessor evidence, deployed source and PKI qualification, and runtime registration, admission and activation holds. +The Account-owned family comprises immutable evaluation, attempt-history, and recovery evidence plus guarded reservations and usage, with replay, restore, and hold dependencies. `PLAYER_ADMISSION` registration remains held. Its category classification and approved finite retention/erasure schedule, reference-safe owner cleanup preserving replay/restore dependencies and holds, and bounded size/health proof remain missing. See the canonical [Account runtime/data capacity retention limitation](../../architecture/microservices/account-service/runtime-and-data.md), [ADR 0050](../../architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md), and [ADR 0163](../../architecture/decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). + +The current positive owner boundary is public SHARED/PRESEEDED new player binding with exact shape `(activeSessions=0, instances=0, storage=0)` to `(1,0,0)` and explicit delta `1`, against exact retained evidence and current Account membership/issuance/scope sources. World lifecycle activation, authoritative prior-shape/zero-delta recovery, and existing-tenant usage import remain held without genuine complete owner sources. The schema and controlled persistence fixtures do not make those paths available. Paid evidence is not converted into DEMO; the separate NEW gameplay lease's currently supported explicit DEMO boundary is unchanged. + +At the earlier preparation checkpoint on base `2e23db82384efa3221a53633dd43b45c62cd6ecc`, focused local validation passed 51 Java cases and two Python vector cases, with zero failures, errors or skips. The Java cases cover the shared digest, strict codec, Account capacity replay/refusal and workload guard, player-evidence retention/rollback, and Game Session loopback mTLS client. Scoped source generation and Java compilation, including Account integration sources, and all named enabled Checkstyle, SpotBugs and Java format tasks pass. Those physical PostgreSQL migration, fresh-bootstrap, retention/rollback, finalization/release and bounded recovery/quarantine definitions were unrun at that checkpoint. The later seven-case Account/Game Session composition below executes fresh bootstrap and authenticated positive finalization; separate closure/race and exhaustion definitions remain unrun. Controlled sources do not qualify genuine World lifecycle, deployed custody or admission. + +Earlier attempts remain failed: R1 stopped on integration-fixture AssertJ inference, R2 and R4 on ignored checked-arithmetic results in test and production code, and R5 on nullable SQL fixture readbacks. Narrow corrections cleared those scopes. R6 cleared the Java scopes and stopped at a denied Harmony CLA link request. At that checkpoint, physical PostgreSQL, concurrency, runtime, admission and finalized-usage retirement proof were still unrun or held. Later physical results are recorded below against the sources that ran them. + +Local source now binds the exact retained original-NEW attempt to the actual seven-key final controller CAS, complete admitted-session capacity digest and SQL final receipt. The Account commitment is obtained at that final boundary. One retained SQL dispatch marker prevents retry-based reinstallation after uncertainty; the permanent tenant-slot original-attempt closure races atomically with the actual final mutation. Qualified negative readback additionally requires immutable SQL CLOSED proof, no contradictory final SQL evidence and fresh current-owner proof under the [Game Session evidence contract](../../architecture/microservices/game-session-service/runtime-and-data.md#original-new-capacity-execution-evidence). The local Game Session exact read remains with this parent; the authenticated Account recovery client belongs to the dependent receiving slice and remains unregistered. V1063 classifies the added evidence and advances the genuine catalog frontier while retaining old epochs. + +This is an intentionally incompatible preproduction cutover of the manually composed, unregistered original-NEW final-admission components. The finalized schema-2 reader requires `capacityExecutionDigest`; predecessor finalized values without that field are unsupported. No production rolling-upgrade or rollback compatibility is claimed. Source inspection establishes no default runtime registration, not whether earlier manual composition populated retained SQL or Redis data. Before activation or reuse of predecessor-populated storage, identify any predecessor-produced finalized sessions and still-active original-confirmation or recovery windows, then resolve their retention and supported recovery obligations under the [objective compatibility gates](../../architecture/decisions/adr-0081-objective-compatibility-gates-for-database-evolution.md) and [Redis compatibility contract](../../architecture/system-architecture-redis-script-rollout-and-compatibility.md). Preserve immutable historical evidence; this cutover authorizes neither deletion, rewriting nor invented capacity commitment proof. + +New definitions cover actual fresh creator bootstrap, retained player evaluation, real Account commitment/client, actual Game Session final CAS, authenticated recovery finalization, exact replay/confirmation loss and missing-capacity refusal. Separate native definitions cover final-CAS versus closure races, lost closure replies, restart closure, changed fences, expiry and reset/absence refusal. Controlled post-retention serving-index removals test durable positive replay and retained CLOSED replay with its exact persistent tombstone, not real teardown ordering. Negative definitions retain refusal for missing tombstones, changed reservation fences, contradictory final-receipt writes and physical closure before SQL proof retention. Local resource definitions cover the complete SQL/Redis operation's absolute deadline, late SQL acquisition without execution, active statement cancellation ordered before pool return, bounded saturation, and canonical tag configuration preservation. Selected physical Account/Game Session composition proof is now recorded below. Separate physical closure/race and exhaustion definitions remain unrun; resource/cancellation execution retains its earlier source-specific limits. Deployed custody and runtime qualification remain pending. + +Receiving from parent `3cfe7a68`, all seven [original-NEW Account/Game Session composition cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java) pass on PostgreSQL/Redis with the actual unregistered owners, controlled upstream sources and test PKI. The completion repair passes 15 Human runtime cases and 20 catalog cases, including V1063-to-V1064 upgrade with retained history, snapshots and epoch-8 readback. The issuer cohort correction passes eight bootstrap cases and 15 other build cases before V1064; its corrected concurrent-upgrade case passes with V1064. These focused results retain unchanged-case attribution and both earlier failed aggregates. Affected jOOQ generation, enabled static analysis and formatting pass. Full CI on the new published comparisons, deployed custody and fresh-image LOGIN → PLAY → LOOK remain unverified. + +On local working postimages based on `fb56d3bc465155644323c472496e91e3a0433853`, the closed phase-one gate passed in 1m24s: all 41 selected Game Session unit cases passed without failures, errors or skips, alongside six unchanged passing shared-codec cases reused by Gradle. Required production/test/integration-source compilation, protobuf and the then-numbered capacity migration's jOOQ generation, and affected Java formatting passed or reused matching inputs. Earlier attempts stopped on an ambiguous generic test assertion, a redundant UUID conversion in the composition fixture, and two cold-first-use deadline fixtures that expired before reaching their intended blocked-resource phase. Those fixtures were corrected; the final two-second cases retain blocked resources and require return below the default five-second budget. The route-matrix check and closed phase-two gate subsequently passed: eight selected SpotBugs tasks, four Java format checks, gRPC transport/public-method and proto-time guards passed or reused matching inputs, and Markdown lint checked 547 files without issues. After the scoped mechanical static-analysis fixes, the identical 41-case Game Session selection passed again in 1m5s with zero failures, errors or skips. This is local controlled unit/source proof, not published-source or deployed-authority qualification. These results predate the parent reconciliation and capacity migration renumbering to V1063; replacement proof for that integrated source remains pending. Buf/generated-documentation checks and physical integration/migration execution remain unrun; deployed source/PKI/Redis custody and runtime qualification remain pending. + +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. Before the first SQL receipt, recovery still needs current Account coverage and the original RUNNING runtime. If a newer Account fence captures the provisional transition or the runtime stops after Redis FINAL, the positive effect remains indeterminate for settlement. See the [Game Session runtime contract](../../architecture/microservices/game-session-service/runtime-and-data.md). 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. The front #3427 checkpoint at `efc47950` retains V1065 storage, exact SQL guards and original execution evidence, but fails closed on owner replacement while unresolved installation or authorization custody remains. Normal handoff remains the target, not a completed front capability. The receiving work in [#3445](https://github.com/benhook1013/FireMUD/pull/3445) must independently qualify protected observations, complete region census and current readback, retained legacy three-field fence evidence, and guarded successor installation on its exact source. Historical component proof below does not qualify that receiving comparison or waive its outstanding findings. An unqualified owner replacement remains 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. + +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. + +Finalized usage retirement and settlement remain deferred. They require a genuine admitted-session teardown receipt from the selected owner and an exactly-once Account usage transition that preserves finalized replay. The admitted-session teardown owner, [Game Session terminal proof](../../architecture/microservices/game-session-service/runtime-and-data.md#finalized-capacity-usage-retirement), protected receipt transport and [Account conservation proof](../../architecture/microservices/account-service/runtime-and-data.md#finalized-capacity-usage-retirement) remain open. Runtime activation stays held. + +The default-registration no-creation proof at base `c8dab91d050082d7c989900b4b2d44d7a812f275`, with [AccountRuntimeEntitlementNoWriteIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java) source SHA-256 `2ee2702944980bc486cae6f9cd74e626085454c4485b5b01987149bc9d199396`, passes five fresh cases without failures, errors or skips. It boots the complete Account application/main policy scan with real Account facade, discovered gRPC service and global certificate interceptor, physical PostgreSQL/Redis and a REQUIRE-mTLS listener; only unrelated Entity/Game Session/Logging Admin clients and mail are mocked. Certificate-authenticated same-namespace Game Session and World numeric requests and exact retries return the protobuf `ENTITLEMENT_UNAVAILABLE` error with no entitlement payload. Wrong-service/cross-namespace certificates and spoofed peer metadata are denied, and no-client-certificate calls fail TLS. The prepared PLAYER_ADMISSION/capacity owner, receiver, repository and recovery beans remain absent. Independent autocommit reads of the same application datasource compare counts and exact JSON/`xmin` images for all five V1040 capacity families after each refusal: their initially empty cohorts remain empty. This proves no durable creation for those requests only; preservation of populated evaluations, usage, reservations, attempt history and recovery evidence is unproved. The combined affected run also passes the separately retained private invoice witness method after a null-safety/canonical-format correction; that dirty witness is a compiled local input, is excluded from this checkpoint, and is not capacity-family preservation proof. Published receiving CI must qualify its own source independently. Retention/erasure, production custody, cleanup and launch/registration holds remain unchanged. ### Controlled player-admission transport composition diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 625bba7f65..edfec1d9cb 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -962,6 +962,34 @@ require_equal( "ci workflow", ) +spotbugs_reports_step = find_step( + module_ci, "build-and-test", "Upload SpotBugs Reports if Failed", "ci workflow" +) +gradle_checks_step = find_step(module_ci, "build-and-test", "Run Gradle Checks", "ci workflow") +module_steps = module_ci["jobs"]["build-and-test"]["steps"] +if module_steps.index(spotbugs_reports_step) <= module_steps.index(gradle_checks_step): + raise AssertionError("ci workflow: SpotBugs reports upload must follow Run Gradle Checks") +require_equal( + spotbugs_reports_step, ("if",), "${{ failure() || cancelled() }}", "ci workflow" +) +require_equal( + spotbugs_reports_step, + ("uses",), + "actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9", + "ci workflow", +) +require_equal( + spotbugs_reports_step, + ("with",), + { + "name": "spotbugs-${{ matrix.module }}-${{ matrix.partition }}-reports-${{ github.sha }}-attempt-${{ github.run_attempt }}", + "path": "${{ matrix.module == 'load-testing' && 'dev-tools/load-testing/build/reports/spotbugs/' || format('services/{0}/build/reports/spotbugs/', matrix.module) }}", + "if-no-files-found": "warn", + "retention-days": "14", + }, + "ci workflow", +) + junit_results_step = find_step( module_ci, "build-and-test", "Upload JUnit Test Results", "ci workflow" ) @@ -1589,6 +1617,49 @@ require_equal( gradle_build = Path(sys.argv[6]).read_text(encoding="utf-8") root_configuration, subproject_configuration = gradle_build.split("subprojects {", 1) +def live_spotbugs_kotlin(source): + # Mask literals as non-syntax tokens, except the exact ordinary XML argument. + # Kotlin block comments can nest and are replaced with separating whitespace. + token = re.compile(r'"""[\s\S]*?"""|"(?:\\.|[^"\\])*"|//[^\n]*|/\*') + cursor = 0 + output = [] + while (match := token.search(source, cursor)) is not None: + output.append(source[cursor:match.start()]) + cursor = match.end() + if match.group() == "/*": + depth = 1 + while depth: + marker = re.search(r"/\*|\*/", source[cursor:]) + if marker is None: + raise AssertionError("Unterminated Kotlin block comment") + cursor += marker.end() + depth += 1 if marker.group() == "/*" else -1 + output.append(" ") + elif match.group().startswith("//"): + output.append(" ") + else: + output.append(match.group() if match.group() == '"xml"' else "\x00") + output.append(source[cursor:]) + return "".join(output) + + +def has_spotbugs_xml_report(source): + return re.search( + r'tasks\.withType\(\)\.configureEach\s*\{\s*' + r'enabled = fullCheck\s*reports\.create\("xml"\)\s*\{\s*' + r'required\.set\(true\)\s*\}', + live_spotbugs_kotlin(source), + ) is not None + + +spotbugs_fixture = 'tasks.withType().configureEach { enabled = fullCheck %s }' +xml_fixture = 'reports.create("xml") { required.set(true) }' +assert has_spotbugs_xml_report(spotbugs_fixture % xml_fixture) +assert not has_spotbugs_xml_report(spotbugs_fixture % ("/* nested /* fixture */ " + xml_fixture + " */")) +assert not has_spotbugs_xml_report('val example = """' + (spotbugs_fixture % xml_fixture) + '"""') +assert not has_spotbugs_xml_report(spotbugs_fixture % ('"""' + xml_fixture + '"""')) +if not has_spotbugs_xml_report(subproject_configuration): + raise SystemExit("Module SpotBugs tasks must emit XML reports for failed CI diagnostics") game_session_build = ( Path(sys.argv[6]).resolve().parent / "services/game-session-service/build.gradle.kts" ) diff --git a/dev-tools/validation/slow_service_ci_test_partition_plan.json b/dev-tools/validation/slow_service_ci_test_partition_plan.json index 3ae54c61c5..c938117b2e 100644 --- a/dev-tools/validation/slow_service_ci_test_partition_plan.json +++ b/dev-tools/validation/slow_service_ci_test_partition_plan.json @@ -1394,8 +1394,8 @@ "weight_seconds": 10.740437860090609 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecyclePostgresIntegrationTest": { - "partition": 4, - "weight_seconds": 304.338 + "partition": 1, + "weight_seconds": 693.235 }, "integration.net.firedevops.firemud.gamesession.repository.GameSessionOriginalStartSessionAssociationReadIntegrationTest": { "partition": 2, @@ -3675,7 +3675,17 @@ "run_id": 41131475765, "source_assessment": "R1308-independent-runner-partition-assessment", "source_head": "38c0da4fe656c07dad184838d8dcadf370a382c3", - "source_option": 2 + "source_option": 2, + "timing_updates": [ + { + "class": "integration.net.firedevops.firemud.gamesession.repository.GameSessionInitialPlaytestLifecyclePostgresIntegrationTest", + "artifact_id": 15144069479, + "run_id": 45871407242, + "run_attempt": 1, + "source_head": "edcfb1884bc38f7fc953bb0eb89818af3a75fe32", + "workflow_sha": "47bc504d94279a1f73ae4df3421f49060e3469d1" + } + ] }, "world-management-service": { "artifact_id": 13604416967, diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java index 630a9116bc..3eeba8f7f2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.common.world; +import io.grpc.Deadline; import io.grpc.ManagedChannel; import java.io.IOException; import java.util.Objects; @@ -23,8 +24,8 @@ public final class WorldCanonicalInstanceLifecycleClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; + private static final String UNAVAILABLE = + "World canonical lifecycle client is not initialized and available"; public WorldCanonicalInstanceLifecycleClient( ServiceEndpointsProperties endpoints, @@ -43,33 +44,37 @@ public WorldCanonicalInstanceLifecycleClient( } /** Initializes only when the owning Game Session service explicitly starts this client. */ - public synchronized void init() throws SSLException, IOException { - if (closed) { - throw new IllegalStateException("World canonical lifecycle client is closed"); - } - if (initialized) { - return; - } - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("World canonical lifecycle client has no gRPC stub"); - } - initialized = true; + public void init() throws SSLException, IOException { + initOnce("World canonical lifecycle client is closed", UNAVAILABLE); } /** Reads and validates World-owned lifecycle evidence for this exact canonical request. */ public WorldCanonicalInstanceLifecycleEvidence read( WorldCanonicalInstanceLifecycleEvidence.Request request) { + return read(request, null); + } + + /** Reads the exact lifecycle owner evidence within the receiving operation's deadline. */ + public WorldCanonicalInstanceLifecycleEvidence read( + WorldCanonicalInstanceLifecycleEvidence.Request request, Deadline operationDeadline) { Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "World canonical lifecycle request must use the configured workload namespace"); } + var wireRequest = WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request); var response = - requireStub() - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - .readWorldCanonicalInstanceLifecycle( - WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request)); + withPublishedInitializedStub( + UNAVAILABLE, + stub -> { + var timedStub = + operationDeadline == null + ? stub.withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + : stub.withDeadline( + operationDeadline.minimum( + Deadline.after(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS))); + return timedStub.readWorldCanonicalInstanceLifecycle(wireRequest); + }); try { return WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(request, response); } catch (IllegalArgumentException invalid) { @@ -100,26 +105,6 @@ protected String defaultTarget() { .withCompression("gzip"); } - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private WorldCanonicalInstanceLifecycleReadServiceGrpc - .WorldCanonicalInstanceLifecycleReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "World canonical lifecycle client is not initialized and available"); - } - return currentStub; - } - private static CommonGrpcClientProperties requireFileBackedMtls( CommonGrpcClientProperties tlsProperties) { return FileBackedGrpcMtlsPolicy.require( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java index ec11bc8382..99a5dbfd52 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.client; +import io.grpc.Deadline; import io.grpc.ManagedChannel; import java.io.IOException; import java.util.Objects; @@ -102,19 +103,33 @@ public CanonicalInitialPlayerLocationResponse readInitialPlayerLocation( /** Reads the fresh current-room region consequence for an exact retained APPLIED placement. */ public CanonicalInitialPlayerLocationRegionResponse readInitialPlayerLocationRegion( CanonicalInitialPlayerLocationRequest request) { + return readInitialPlayerLocationRegion(request, null); + } + + /** Reads region evidence within the remaining deadline of the receiving operation. */ + public CanonicalInitialPlayerLocationRegionResponse readInitialPlayerLocationRegion( + CanonicalInitialPlayerLocationRequest request, Deadline operationDeadline) { requireNoAmbientSql("Initial player location region RPC requires no ambient SQL"); requireRequest(request); if (request.getSerializedSize() > MAX_REGION_REQUEST_BYTES) { throw new IllegalArgumentException( "Initial player location region request exceeds its bound"); } - var stub = - requireInitializedStub("World initial player location client is unavailable") - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) - .withMaxInboundMessageSize(MAX_REGION_RESPONSE_BYTES) - .withMaxOutboundMessageSize(MAX_REGION_REQUEST_BYTES); CanonicalInitialPlayerLocationRegionResponse response = - stub.readInitialPlayerLocationRegion(request); + withPublishedInitializedStub( + "World initial player location client is unavailable", + stub -> { + var bounded = + operationDeadline == null + ? stub.withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + : stub.withDeadline( + operationDeadline.minimum( + Deadline.after(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS))); + return bounded + .withMaxInboundMessageSize(MAX_REGION_RESPONSE_BYTES) + .withMaxOutboundMessageSize(MAX_REGION_REQUEST_BYTES) + .readInitialPlayerLocationRegion(request); + }); requireRegionResponse(request, response); return response; } 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 ab5252f601..ed16b024c3 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 @@ -290,6 +290,28 @@ CanonicalGameplayBindingProvisionalCasEvidence readProvisionalCasEvidence(UUID t }); } + void lockInitialTimelineBindingScope( + DSLContext transaction, CanonicalGameplayBindingProvisionalCasEvidence expected) { + lockInventoryRevision(transaction); + lockLeaseBoundRuntimeBeforeTransition( + transaction, + expected.transition().transitionId(), + expected.candidate().bindingRef().bytes(), + null); + } + + void requireCurrentInitialTimelineBinding( + DSLContext transaction, CanonicalGameplayBindingProvisionalCasEvidence expected) { + var current = + loadProvisionalCasEvidence(transaction, expected.transition().transitionId(), true); + if (current.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || current.expectedPrior() != null) { + throw conflict("Initial timeline claim requires the exact provisional first binding"); + } + requireSameProvisionalSource(expected, current); + } + /** Irreversibly selects one still-PREPARED dispatch claim without inferring any Redis outcome. */ public CanonicalGameplayOriginalNewAbandonmentSource selectOriginalNewAbandonment( UUID transitionId) { 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 1f4cadc526..0dd58cb9da 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 @@ -479,7 +479,8 @@ long remainingMillis() { Deadline operationDeadline() { check(); - return deadline; + // Snapshot the wall-clock bound too, so an exported RPC deadline never outlives the budget. + return deadline.minimum(Deadline.after(remainingNanos(), TimeUnit.NANOSECONDS)); } long absoluteDeadlineMillis() { @@ -511,6 +512,13 @@ void retainUntilAsyncClose(CompletableFuture closeAttempt) { releaseIfFinished(); } }); + // Report a close still pending at the operation deadline even when no caller awaits it. + CompletableFuture.runAsync( + () -> { + if (!closeAttempt.isDone()) recordRedisCloseRetained("timeout"); + }, + CompletableFuture.delayedExecutor( + Math.max(0L, deadline.timeRemaining(TimeUnit.NANOSECONDS)), TimeUnit.NANOSECONDS)); } private void recordRedisCloseRetained(String category) { @@ -759,6 +767,20 @@ private static ConnectionRetirer capturePooledConnection( }; } + static void requireRetireableSql(DSLContext sql) { + if (!(sql.configuration().connectionProvider() + instanceof DataSourceConnectionProvider provider)) { + throw new IllegalArgumentException( + "region lease SQL requires a retireable Hikari data source"); + } + try { + requireHikariDataSource(provider.dataSource()); + } catch (SQLException unsupported) { + throw new IllegalArgumentException( + "region lease SQL requires a retireable Hikari data source", unsupported); + } + } + private static HikariDataSource requireHikariDataSource(DataSource source) throws SQLException { DataSource current = source; while (current instanceof DelegatingDataSource delegating) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java index aa912c61e8..56b361ef55 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.repository; import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; import java.time.Clock; import java.time.Duration; import java.util.Objects; @@ -18,6 +19,7 @@ private CanonicalGameplayRegionBindingBridgeOwnerFactory() {} static CanonicalGameplayRegionBindingBridgeOwner compose( DSLContext dsl, RedisClient coordinationRedis, + RedisURI coordinationUri, RedisScriptCatalog scriptCatalog, CanonicalGameplayRegionIncarnationSource incarnationSource, CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, @@ -28,6 +30,7 @@ static CanonicalGameplayRegionBindingBridgeOwner compose( return compose( dsl, coordinationRedis, + coordinationUri, scriptCatalog, incarnationSource, worldRegionResolver, @@ -41,6 +44,7 @@ static CanonicalGameplayRegionBindingBridgeOwner compose( static CanonicalGameplayRegionBindingBridgeOwner compose( DSLContext dsl, RedisClient coordinationRedis, + RedisURI coordinationUri, RedisScriptCatalog scriptCatalog, CanonicalGameplayRegionIncarnationSource incarnationSource, CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, @@ -54,6 +58,7 @@ static CanonicalGameplayRegionBindingBridgeOwner compose( CanonicalGameplayRegionLeaseOwnerFactory.compose( dsl, coordinationRedis, + coordinationUri, scriptCatalog, incarnationSource, worldRegionResolver, 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 b80b244644..82ad60d06e 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.Deadline; import java.math.BigInteger; import java.time.Clock; import java.time.Duration; @@ -8,6 +9,7 @@ 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.CanonicalGameplayBindingInventoryEntry; @@ -34,6 +36,7 @@ final class CanonicalGameplayRegionLeaseOwner { private final RuntimeIdentity runtimeIdentity; private final Duration leaseTtl; private final Clock clock; + private final boolean deadlineBoundInstallation; CanonicalGameplayRegionLeaseOwner( CanonicalGameplayBindingInventoryRepository bindingInventory, @@ -44,6 +47,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"); @@ -72,11 +98,59 @@ Installation installForTransition( UUID transitionId, CanonicalInitialPlayerLocationRequest worldRequest) { requireNoAmbientTransaction(); + if (!deadlineBoundInstallation) { + return installForTransition( + existingRegionInstallation, + transitionId, + worldRequest, + bindingInventory, + statusRepository, + redisOwner, + null); + } + long maximum = CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_OPERATION_MILLIS; + Deadline monotonicDeadline = Deadline.after(maximum, TimeUnit.MILLISECONDS); + long installationDeadline = deadlineAfter(clock, maximum); + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackgroundWithin( + clock, + installationDeadline, + monotonicDeadline, + budget -> + installForTransition( + existingRegionInstallation, + transitionId, + worldRequest, + bindingInventory.forBudget(budget), + statusRepository.forBudget(budget), + redisOwner.forInstallation(clock, budget), + budget.operationDeadline()), + null); + } + + private static long deadlineAfter(Clock clock, long millis) { + if (millis <= 0) throw unavailable(); + try { + return Math.addExact(clock.millis(), millis); + } catch (ArithmeticException invalid) { + throw unavailable(); + } + } + + private Installation installForTransition( + Installation existingRegionInstallation, + UUID transitionId, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalGameplayBindingInventoryRepository bindingInventory, + CanonicalGameplayRegionRuntimeStatusRepository statusRepository, + CanonicalGameplayRegionLeaseRedisOwner redisOwner, + io.grpc.Deadline operationDeadline) { + requireNoAmbientTransaction(); Objects.requireNonNull(transitionId, "transitionId"); Objects.requireNonNull(worldRequest, "worldRequest"); CanonicalGameplayBindingProvisionalCasEvidence evidence = - readCurrentProvisionalEvidence(transitionId); - ResolvedBridgeSource initialResolved = resolveExactBridgeSource(worldRequest, evidence); + readCurrentProvisionalEvidence(transitionId, bindingInventory); + ResolvedBridgeSource initialResolved = + resolveExactBridgeSource(worldRequest, evidence, operationDeadline); CanonicalGameplayRegionRuntimeStatusRepository.Source source = initialResolved.source; CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation = readCurrentIncarnation(source); @@ -89,6 +163,7 @@ Installation installForTransition( CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; boolean reusingRegionGrant = false; + boolean recoveringInitialGrant = false; if (prior == null) { if (existingRegionInstallation != null) throw unavailable(); preparation = statusRepository.findTimelinePreparation(source).orElse(null); @@ -120,10 +195,10 @@ Installation installForTransition( try (CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization session = redisOwner.prepareTimelineInitialization(preparation, leaseTtl, runtimeIdentity)) { CanonicalGameplayBindingProvisionalCasEvidence beforeClaimEvidence = - readCurrentProvisionalEvidence(transitionId); + readCurrentProvisionalEvidence(transitionId, bindingInventory); bindingInventory.requireSameProvisionalSource(evidence, beforeClaimEvidence); ResolvedBridgeSource beforeClaimWorld = - resolveExactBridgeSource(worldRequest, beforeClaimEvidence); + resolveExactBridgeSource(worldRequest, beforeClaimEvidence, operationDeadline); requireSameSource(source, beforeClaimWorld.source); CanonicalGameplayRegionIncarnationSource.StableEvidence beforeClaimIncarnation = readCurrentIncarnation(source); @@ -137,16 +212,20 @@ Installation installForTransition( beforeClaimIncarnation)) { throw unavailable(); } + // The claim is single-use: any failure after it leaves INITIALIZING held. Optional - permit = statusRepository.beginInitialTimeline(preparation, clock.instant()); + permit = + statusRepository.beginInitialTimeline( + preparation, clock.instant(), bindingInventory, beforeClaimEvidence); grant = session.initialize(permit.orElse(null)); } redisOwner.verifyInitializedTimeline(grant, preparation); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); - ResolvedBridgeSource afterInitWorld = resolveExactBridgeSource(worldRequest, evidence); + ResolvedBridgeSource afterInitWorld = + resolveExactBridgeSource(worldRequest, evidence, operationDeadline); requireSameSource(source, afterInitWorld.source); bindingInventory.requireSameProvisionalSource( - evidence, readCurrentProvisionalEvidence(transitionId)); + evidence, readCurrentProvisionalEvidence(transitionId, bindingInventory)); preparation = statusRepository.markRedisInitialized( preparation, @@ -157,8 +236,6 @@ Installation installForTransition( preparation.sourceDigest()), clock.instant()); } else { - // This slice can reuse current owner custody but cannot issue a replacement grant. - if (existingRegionInstallation == null) throw unavailable(); preparation = statusRepository .findTimelinePreparation(source) @@ -176,18 +253,46 @@ Installation installForTransition( incarnation) : statusRepository.matchesInstalledTimelineInitialization( preparation, source, incarnation); - // An installation handle is issued only after the installed phase is durable. - // A partial SQL/Redis initialization stays held: this path offers no continuation for it. - if (!matchesInitialization - || preparation.phase() - != CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase - .INSTALLED) { + boolean installedPreparation = + preparation.phase() + == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INSTALLED; + // Only a generation-qualified original attempt may finish a partial installation. + boolean recoverableOriginalPreparation = + existingRegionInstallation == null + && sameInitializationAttempt + && preparation.phase() + == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .REDIS_INITIALIZED + && preparation.hasInitializationClaimGeneration(); + if (!matchesInitialization || (!installedPreparation && !recoverableOriginalPreparation)) { throw unavailable(); } - requireReusableRegionGrant( - existingRegionInstallation, source, incarnation, prior, expectedRegionEpoch); - grant = existingRegionInstallation.grant; - reusingRegionGrant = true; + if (existingRegionInstallation == null) { + // Only recover the exact original live grant after a lost installation completion. + // No new token, lease acquisition or durable executor fence is permitted here. + if (!sameInitializationAttempt || expectedRegionEpoch != 1L) throw unavailable(); + grant = redisOwner.readRetainedInitialGrant(preparation, prior, runtimeIdentity); + redisOwner.requireCurrent(grant); + redisOwner.verifyInitializedTimeline(grant, preparation); + if (!prior.equals( + statusRepository + .find(source) + .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable))) { + throw unavailable(); + } + recoveringInitialGrant = true; + } else { + requireReusableRegionGrant( + existingRegionInstallation, + source, + incarnation, + prior, + expectedRegionEpoch, + statusRepository, + redisOwner); + grant = existingRegionInstallation.grant; + reusingRegionGrant = true; + } } if (reusingRegionGrant) { redisOwner.requireGrantScope( @@ -196,23 +301,36 @@ Installation installForTransition( redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); } CanonicalGameplayRegionRuntimeStatusRepository.Source afterAcquire = - resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); + resolveExactSource( + worldRequest, + readCurrentProvisionalEvidence(transitionId, bindingInventory), + operationDeadline); requireSameSource(source, afterAcquire); - redisOwner.renew(grant, leaseTtl); + if (!recoveringInitialGrant) { + if (prior == null && operationDeadline != null) { + // Redis begins the renewal after this local observation. The earlier local deadline + // conservatively bounds how long the grant covers the pending SQL transaction. + Deadline guaranteedRenewal = Deadline.after(leaseTtl.toMillis(), TimeUnit.MILLISECONDS); + if (!operationDeadline.isBefore(guaranteedRenewal)) throw unavailable(); + } + redisOwner.renew(grant, leaseTtl); + } redisOwner.requireCurrent(grant); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); redisOwner.verifyInitializedTimeline(grant, preparation); Instant installedAt = clock.instant(); CanonicalGameplayRegionRuntimeStatus installed = - statusRepository.installOwner( - source, - expectedRegionEpoch, - prior, - grant.tokenCorrelation(), - grant.ownerService(), - grant.ownerInstanceId(), - installedAt); + recoveringInitialGrant + ? prior + : statusRepository.installOwner( + source, + expectedRegionEpoch, + prior, + grant.tokenCorrelation(), + grant.ownerService(), + grant.ownerInstanceId(), + installedAt); redisOwner.requireCurrent(grant); redisOwner.verifyInitializedTimeline(grant, preparation); @@ -220,7 +338,10 @@ Installation installForTransition( statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!installed.equals(observed) || observed.paused()) throw unavailable(); CanonicalGameplayRegionRuntimeStatusRepository.Source afterInstall = - resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); + resolveExactSource( + worldRequest, + readCurrentProvisionalEvidence(transitionId, bindingInventory), + operationDeadline); requireSameSource(source, afterInstall); redisOwner.requireCurrent(grant); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); @@ -230,10 +351,16 @@ Installation installForTransition( redisOwner.verifyInitializedTimeline(grant, preparation); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); requireSameSource( - source, resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId))); + source, + resolveExactSource( + worldRequest, + readCurrentProvisionalEvidence(transitionId, bindingInventory), + operationDeadline)); CanonicalGameplayRegionRuntimeStatus finalStatus = statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!installed.equals(finalStatus) || finalStatus.paused()) throw unavailable(); + // The last World and SQL reads may outlast the recovered grant. Never renew or replace it. + if (recoveringInitialGrant) redisOwner.requireCurrent(grant); return new Installation( transitionId, worldRequest, evidence, source, incarnation, preparation, grant, installed); } @@ -244,6 +371,24 @@ private void requireReusableRegionGrant( CanonicalGameplayRegionIncarnationSource.StableEvidence currentIncarnation, CanonicalGameplayRegionRuntimeStatus currentStatus, long expectedRegionEpoch) { + requireReusableRegionGrant( + existing, + candidateSource, + currentIncarnation, + currentStatus, + expectedRegionEpoch, + statusRepository, + redisOwner); + } + + private void requireReusableRegionGrant( + Installation existing, + CanonicalGameplayRegionRuntimeStatusRepository.Source candidateSource, + CanonicalGameplayRegionIncarnationSource.StableEvidence currentIncarnation, + CanonicalGameplayRegionRuntimeStatus currentStatus, + long expectedRegionEpoch, + CanonicalGameplayRegionRuntimeStatusRepository statusRepository, + CanonicalGameplayRegionLeaseRedisOwner redisOwner) { if (existing == null || !existing.owner.equals(this) || !CanonicalGameplayRegionRuntimeStatusRepository.sameRegionSource( @@ -283,7 +428,7 @@ void revalidateBeforeBridge(Installation installation) { BridgeContext currentBridgeContext(Installation installation) { requireNoAmbientTransaction(); Objects.requireNonNull(installation, "installation"); - if (!installation.owner.equals(this)) throw unavailable(); + if (!installation.owner.equals(this) || installation.evidence == null) throw unavailable(); CanonicalGameplayBindingProvisionalCasEvidence evidence = readCurrentProvisionalEvidence(installation.transitionId); bindingInventory.requireSameProvisionalSource(installation.evidence, evidence); @@ -316,7 +461,7 @@ OriginalNewFinalBindingCurrentProof revalidateOriginalNewFinalBinding( Objects.requireNonNull(installation, "installation"); Objects.requireNonNull(finalAdmissionSource, "finalAdmissionSource"); Objects.requireNonNull(reference, "runtimeReference"); - if (!installation.owner.equals(this)) throw unavailable(); + if (!installation.owner.equals(this) || installation.evidence == null) throw unavailable(); CanonicalGameplayOriginalNewCandidate candidate = finalAdmissionSource.candidate(); CanonicalGameplayBindingRegionBridgeObligation acknowledgement = @@ -642,6 +787,11 @@ private void requireOwnedContext(Installation installation, BridgeContext contex private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvidence( UUID transitionId) { + return readCurrentProvisionalEvidence(transitionId, bindingInventory); + } + + private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvidence( + UUID transitionId, CanonicalGameplayBindingInventoryRepository bindingInventory) { requireNoAmbientTransaction(); CanonicalGameplayBindingProvisionalCasEvidence evidence = bindingInventory.readProvisionalCasEvidence(transitionId); @@ -661,13 +811,21 @@ private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvi private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveExactSource( CanonicalInitialPlayerLocationRequest request, - CanonicalGameplayBindingProvisionalCasEvidence evidence) { - return resolveExactBridgeSource(request, evidence).source; + CanonicalGameplayBindingProvisionalCasEvidence evidence, + io.grpc.Deadline operationDeadline) { + return resolveExactBridgeSource(request, evidence, operationDeadline).source; } private ResolvedBridgeSource resolveExactBridgeSource( CanonicalInitialPlayerLocationRequest request, CanonicalGameplayBindingProvisionalCasEvidence evidence) { + return resolveExactBridgeSource(request, evidence, null); + } + + private ResolvedBridgeSource resolveExactBridgeSource( + CanonicalInitialPlayerLocationRequest request, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + io.grpc.Deadline operationDeadline) { requireNoAmbientTransaction(); var identity = evidence.candidate().identity(); var target = request.getExpectedTarget(); @@ -684,7 +842,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()) 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 c2fbb8305f..878096e977 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.repository; import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; import java.time.Clock; import java.time.Duration; import java.util.Objects; @@ -16,6 +17,7 @@ private CanonicalGameplayRegionLeaseOwnerFactory() {} static CanonicalGameplayRegionLeaseOwner compose( DSLContext dsl, RedisClient coordinationRedis, + RedisURI coordinationUri, RedisScriptCatalog scriptCatalog, CanonicalGameplayRegionIncarnationSource incarnationSource, CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, @@ -24,16 +26,29 @@ static CanonicalGameplayRegionLeaseOwner compose( Clock clock) { Objects.requireNonNull(dsl, "dsl"); Objects.requireNonNull(coordinationRedis, "coordinationRedis"); + var redisOptions = coordinationRedis.getOptions(); + if (redisOptions == null || redisOptions.isAutoReconnect()) { + throw new IllegalArgumentException("coordinationRedis requires autoReconnect=false"); + } Objects.requireNonNull(scriptCatalog, "scriptCatalog"); Objects.requireNonNull(incarnationSource, "incarnationSource"); + long installationMillis = + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_OPERATION_MILLIS; + Objects.requireNonNull(leaseTtl, "leaseTtl"); + if (leaseTtl.compareTo(Duration.ofMillis(installationMillis + 1)) < 0) { + throw new IllegalArgumentException("leaseTtl must exceed the bounded installation window"); + } + CanonicalGameplayOriginalNewCapacityExecutionBudget.requireRetireableSql(dsl); return new CanonicalGameplayRegionLeaseOwner( new CanonicalGameplayBindingInventoryRepository(dsl), new CanonicalGameplayRegionRuntimeStatusRepository(dsl), - new CanonicalGameplayRegionLeaseRedisOwner(coordinationRedis, scriptCatalog), + new CanonicalGameplayRegionLeaseRedisOwner( + coordinationRedis, coordinationUri, scriptCatalog), incarnationSource, Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"), Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"), - Objects.requireNonNull(leaseTtl, "leaseTtl"), - Objects.requireNonNull(clock, "clock")); + leaseTtl, + 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 cac910fb35..5ef6d90ae1 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 @@ -1,7 +1,9 @@ package net.firedevops.firemud.gamesession.repository; +import io.grpc.Context; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisFuture; +import io.lettuce.core.RedisURI; import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.async.RedisAsyncCommands; @@ -11,14 +13,19 @@ import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.time.Clock; import java.time.Duration; +import java.util.Arrays; import java.util.HexFormat; import java.util.List; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.common.runtime.RuntimeIdentity; @@ -31,10 +38,11 @@ final class CanonicalGameplayRegionLeaseRedisOwner { private static final String PRINCIPAL = "gamesession_coord_app"; private static final String SCHEMA = "gs_region_lease/v1"; + private static final String DEADLINE_SCHEMA = "gs_region_lease/v2"; private static final int MAX_SCRIPT_BYTES = 16 * 1024; private static final long COMMAND_TIMEOUT_MILLIS = 5_000L; private static final List LEASE_ARGUMENTS = - List.of("schema", "token", "expectedRegionEpoch", "leaseTtlMs"); + List.of("schema", "token", "expectedRegionEpoch", "leaseTtlMs", "absoluteDeadlineMillis"); private static final List READ_ARGUMENTS = List.of("schema", "token", "expectedRegionEpoch"); private static final List EXPECTED_KEYS = @@ -45,7 +53,9 @@ final class CanonicalGameplayRegionLeaseRedisOwner { RedisScriptDescriptor.HashTagDeclaration.REQUIRED), new RedisScriptDescriptor.KeySpec( "regionMeta", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); - private static final String TIMELINE_SCHEMA = "gs_region_timeline_init/v1"; + private static final String TIMELINE_SCHEMA = "gs_region_timeline_init/v2"; + // Read-only PROBE/VERIFY outside an installation budget pass the largest exact Lua integer. + private static final String NO_TIMELINE_DEADLINE = "9007199254740991"; private static final List TIMELINE_ARGUMENTS = List.of( "schema", @@ -55,7 +65,8 @@ final class CanonicalGameplayRegionLeaseRedisOwner { "initializationOperationId", "preparationDigest", "leaseTtlMs", - "mayCreateFromAbsence"); + "mayCreateFromAbsence", + "absoluteDeadlineMillis"); private static final String BRIDGE_SCHEMA = "gs_region_binding_bridge/v1"; private static final List BRIDGE_ARGUMENTS = List.of( @@ -77,11 +88,75 @@ final class CanonicalGameplayRegionLeaseRedisOwner { "regionSessionBinding", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); private final RedisClient redisClient; + private final RedisURI coordinationUri; private final RedisScriptCatalog catalog; + private final Clock handoffClock; + private final long handoffDeadlineMillis; + private final CanonicalGameplayOriginalNewCapacityExecutionBudget installationBudget; CanonicalGameplayRegionLeaseRedisOwner(RedisClient redisClient, RedisScriptCatalog catalog) { + this(redisClient, null, catalog, null, 0L, null); + } + + CanonicalGameplayRegionLeaseRedisOwner( + RedisClient redisClient, RedisURI coordinationUri, RedisScriptCatalog catalog) { + this(redisClient, Objects.requireNonNull(coordinationUri), catalog, null, 0L, null); + } + + private CanonicalGameplayRegionLeaseRedisOwner( + RedisClient redisClient, + RedisURI coordinationUri, + RedisScriptCatalog catalog, + Clock handoffClock, + long deadline, + CanonicalGameplayOriginalNewCapacityExecutionBudget installationBudget) { + this.installationBudget = installationBudget; this.redisClient = Objects.requireNonNull(redisClient, "Configured Coordination Redis client"); + this.coordinationUri = coordinationUri; this.catalog = Objects.requireNonNull(catalog, "Installed region lease script catalog"); + this.handoffClock = handoffClock; + this.handoffDeadlineMillis = deadline; + } + + CanonicalGameplayRegionLeaseRedisOwner forHandoffDeadline(Clock clock, long deadline) { + return new CanonicalGameplayRegionLeaseRedisOwner( + redisClient, + Objects.requireNonNull(coordinationUri, "Configured Coordination Redis URI"), + catalog, + Objects.requireNonNull(clock), + deadline, + null); + } + + /** Borrow the composed installation's admission and frozen deadline; never reserve again. */ + CanonicalGameplayRegionLeaseRedisOwner forInstallation( + Clock clock, CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + if (coordinationUri == null) return this; + long deadline = budget.absoluteDeadlineMillis(); + if (handoffClock != null && handoffDeadlineMillis < deadline) throw unavailable(); + return new CanonicalGameplayRegionLeaseRedisOwner( + redisClient, coordinationUri, catalog, clock, deadline, budget); + } + + CanonicalGameplayRegionLeaseRedisOwner forInstallation(Clock clock) { + if (coordinationUri == null) throw unavailable(); + 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( @@ -130,8 +205,7 @@ TimelineAbsenceProof requireTimelineAbsent( "PROBE", UUID.randomUUID(), incarnation.digest(), - 1L, - false); + 1L); if (outcome != 1L) throw unavailable(); return new TimelineAbsenceProof( source, @@ -144,6 +218,50 @@ PreparedTimelineInitialization prepareTimelineInitialization( CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, Duration leaseTtl, RuntimeIdentity identity) { + if (installationBudget != null) { + var session = + prepareTimelineInitialization(preparation, leaseTtl, identity, installationBudget); + installationBudget.retainUntilAsyncClose(session.disposal); + return session; + } + if (handoffClock == null) { + return forInstallation(Clock.systemUTC()) + .prepareTimelineInitialization(preparation, leaseTtl, identity); + } + requireNoAmbientTransaction(); + Object handoffLock = new Object(); + AtomicReference prepared = new AtomicReference<>(); + boolean[] callerAbandoned = {false}; + try { + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + handoffClock, + handoffDeadlineMillis, + budget -> { + PreparedTimelineInitialization session = + prepareTimelineInitialization(preparation, leaseTtl, identity, budget); + budget.retainUntilAsyncClose(session.disposal); + synchronized (handoffLock) { + prepared.set(session); + if (!callerAbandoned[0]) return session; + } + session.closeBoundedConnection(); + throw unavailable(); + }); + } catch (RuntimeException failure) { + synchronized (handoffLock) { + callerAbandoned[0] = true; + PreparedTimelineInitialization session = prepared.get(); + if (session != null) session.close(); + } + throw failure; + } + } + + private PreparedTimelineInitialization prepareTimelineInitialization( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + Duration leaseTtl, + RuntimeIdentity identity, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { requireNoAmbientTransaction(); Objects.requireNonNull(preparation, "preparation"); CanonicalGameplayRegionRuntimeStatusRepository.Source source = @@ -163,11 +281,7 @@ PreparedTimelineInitialization prepareTimelineInitialization( UUID.randomUUID().toString(), ownerService, ownerInstance); - RedisScriptDescriptor descriptor = - requireDescriptor( - CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_ID, - CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_PATH, - TIMELINE_ARGUMENTS); + RedisScriptDescriptor descriptor = timelineDescriptor(); byte[] script = scriptSource(descriptor); byte[][] keys = new byte[][] { @@ -187,22 +301,106 @@ PreparedTimelineInitialization prepareTimelineInitialization( ascii(operationId.toString()), ascii(sourceDigest), ascii(Long.toString(ttlMillis)), - ascii("0") + ascii("0"), + null }; - if (arguments.length != TIMELINE_ARGUMENTS.size()) throw unavailable(); StatefulRedisConnection connection = null; try { - connection = redisClient.connect(ByteArrayCodec.INSTANCE); + connection = openConnection(budget); + requireStableConnection(connection); RedisAsyncCommands commands = connection.async(); - requirePrincipal(await(commands.aclWhoami())); - String loadedSha = await(commands.scriptLoad(script)); + requirePrincipal(await(commands::aclWhoami, budget)); + String loadedSha = await(() -> commands.scriptLoad(script), budget); if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); + // Keep one translated cutoff across the probe, source rechecks, SQL claim and dispatch. + arguments[arguments.length - 1] = redisDeadlineArgument(commands, budget); + byte[][] probe = arguments.clone(); + probe[1] = ascii("PROBE"); + Long result = + await(() -> commands.evalsha(loadedSha, ScriptOutputType.INTEGER, keys, probe), budget); + // A PREPARED row may claim creation only after proved absence and create permission. + if (result == null + || (result != 0L && result != 1L) + || (result != 1L + && preparation.phase() + == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .PREPARED)) throw unavailable(); return new PreparedTimelineInitialization( - connection, commands, loadedSha, keys, arguments, grant, preparation); + connection, commands, loadedSha, keys, arguments, grant, preparation, budget); + } catch (RuntimeException failure) { + if (connection != null) { + budget.awaitAsyncClose( + CanonicalGameplayOriginalNewCapacityExecutionBudget.startRedisClose(connection)); + } + throw unavailable(failure); + } + } + + /** 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 (installationBudget != null) { + return readRetainedInitialGrant(preparation, status, installationBudget); + } + 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 = 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) { - if (connection != null) connection.close(); 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)); + } } } @@ -217,7 +415,13 @@ void verifyInitializedTimeline( } long outcome = executeTimeline( - grant, "VERIFY", preparation.operationId(), preparation.sourceDigest(), 1L, false); + grant.source, + grant.regionEpoch, + grant.token, + "VERIFY", + preparation.operationId(), + preparation.sourceDigest(), + 1L); if (outcome != 3L) throw unavailable(); } @@ -263,24 +467,6 @@ void requireCurrent(LeaseGrant grant) { if (outcome != 1L) throw unavailable(); } - private long executeTimeline( - LeaseGrant grant, - String action, - UUID operationId, - String sourceDigest, - long ttlMillis, - boolean mayCreate) { - return executeTimeline( - grant.source, - grant.regionEpoch, - grant.token, - action, - operationId, - sourceDigest, - ttlMillis, - mayCreate); - } - /** * Holds the one ACL-verified connection across the SQL creation-permission claim and its sole * timeline EVALSHA. Closing without initialize leaves the timeline untouched. @@ -293,8 +479,12 @@ static final class PreparedTimelineInitialization implements AutoCloseable { private final byte[][] arguments; private final LeaseGrant grant; private final CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; + private final CanonicalGameplayOriginalNewCapacityExecutionBudget budget; + private final CompletableFuture disposal = new CompletableFuture<>(); private boolean initialized; private boolean closed; + private boolean initializationInFlight; + private CompletableFuture boundedClose; private PreparedTimelineInitialization( StatefulRedisConnection connection, @@ -303,7 +493,8 @@ private PreparedTimelineInitialization( byte[][] keys, byte[][] arguments, LeaseGrant grant, - CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation) { + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { this.connection = connection; this.commands = commands; this.loadedSha = loadedSha; @@ -311,28 +502,65 @@ private PreparedTimelineInitialization( this.arguments = arguments; this.grant = grant; this.preparation = preparation; + this.budget = budget; } - synchronized LeaseGrant initialize( + LeaseGrant initialize( CanonicalGameplayRegionRuntimeStatusRepository.InitialInitializationPermit permit) { - requireNoAmbientTransaction(); - if (closed || initialized) throw unavailable(); - boolean mayCreate = permit != null; - if (mayCreate - && (!permit.operationId().equals(preparation.operationId()) - || !permit.sourceDigest().equals(preparation.sourceDigest()))) { - throw unavailable(); + byte[][] evalArguments; + synchronized (this) { + requireNoAmbientTransaction(); + if (closed || initialized) throw unavailable(); + boolean mayCreate = permit != null; + if (mayCreate + && (!permit.operationId().equals(preparation.operationId()) + || !permit.sourceDigest().equals(preparation.sourceDigest()))) { + throw unavailable(); + } + if (mayCreate && !permit.consumeDispatch()) throw unavailable(); + initialized = true; + evalArguments = arguments.clone(); + evalArguments[TIMELINE_ARGUMENTS.size() - 2] = ascii(mayCreate ? "1" : "0"); + initializationInFlight = true; } - initialized = true; - byte[][] evalArguments = arguments.clone(); - evalArguments[evalArguments.length - 1] = ascii(mayCreate ? "1" : "0"); - Long outcome; + + // Preparation already owns the retained background permit through disposal. Do not + // re-enter runBackground after the durable INITIALIZING claim and request another slot. + Context caller = Context.current(); + AtomicReference> initialization = new AtomicReference<>(); + Context.CancellationListener listener = + ignored -> { + RedisFuture future = initialization.get(); + if (future != null) future.cancel(true); + }; + caller.addListener(listener, Runnable::run); + RuntimeException initializationFailure = null; + Long outcome = null; try { - outcome = await(commands.evalsha(loadedSha, ScriptOutputType.INTEGER, keys, evalArguments)); + long timeout = Math.min(COMMAND_TIMEOUT_MILLIS, budget.remainingMillis()); + RedisFuture future = + commands.evalsha(loadedSha, ScriptOutputType.INTEGER, keys, evalArguments); + initialization.set(future); + if (caller.isCancelled()) future.cancel(true); + outcome = await(future, timeout); } catch (RuntimeException failure) { - throw unavailable(failure); + initializationFailure = failure; + } finally { + try { + caller.removeListener(listener); + CompletableFuture closeAttempt = closeBoundedConnection(); + budget.awaitAsyncClose(closeAttempt); + closeAttempt.join(); + } catch (RuntimeException disposalFailure) { + if (initializationFailure == null) initializationFailure = disposalFailure; + else if (initializationFailure != disposalFailure) + initializationFailure.addSuppressed(disposalFailure); + } } + // Any refusal after the claim, including a definitive -3/-4, leaves INITIALIZING held. + if (initializationFailure != null) throw unavailable(initializationFailure); if (outcome == null || (outcome != 1L && outcome != 2L)) throw unavailable(); + budget.check(); return grant; } @@ -340,8 +568,22 @@ synchronized LeaseGrant initialize( public synchronized void close() { if (!closed) { closed = true; - connection.close(); + if (!initializationInFlight) closeBoundedConnection(); + } + } + + private synchronized CompletableFuture closeBoundedConnection() { + initializationInFlight = false; + closed = true; + if (boundedClose == null) { + boundedClose = + CanonicalGameplayOriginalNewCapacityExecutionBudget.startRedisClose(connection); + boundedClose.whenComplete((ignored, failure) -> { + if (failure == null) disposal.complete(null); + else disposal.completeExceptionally(failure); + }); } + return boundedClose; } } @@ -352,14 +594,10 @@ private long executeTimeline( String action, UUID operationId, String sourceDigest, - long ttlMillis, - boolean mayCreate) { + long ttlMillis) { requireNoAmbientTransaction(); - RedisScriptDescriptor descriptor = - requireDescriptor( - CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_ID, - CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_PATH, - TIMELINE_ARGUMENTS); + boolean deadlineBound = handoffClock != null; + RedisScriptDescriptor descriptor = timelineDescriptor(); byte[] script = scriptSource(descriptor); byte[][] keys = new byte[][] { @@ -379,9 +617,18 @@ private long executeTimeline( ascii(operationId.toString()), ascii(sourceDigest), ascii(Long.toString(ttlMillis)), - ascii(mayCreate ? "1" : "0") + ascii("0"), + ascii(NO_TIMELINE_DEADLINE) }; - return executeInteger(script, keys, arguments); + // A deadline-bound caller replaces the last argument with its Redis TIME cutoff. + return executeInteger(script, keys, arguments, deadlineBound); + } + + private RedisScriptDescriptor timelineDescriptor() { + return requireDescriptor( + CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_ID, + CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_PATH, + TIMELINE_ARGUMENTS); } private static String absenceProofDigest( @@ -562,25 +809,102 @@ private long execute( }; byte[][] arguments = grant.arguments(includeTtl ? ttlMillis : null); if (arguments.length != expectedArguments.size()) throw unavailable(); - return executeInteger(source, keys, arguments); + return executeInteger(source, keys, arguments, includeTtl); } private long executeInteger(byte[] script, byte[][] keys, byte[][] arguments) { + return executeInteger(script, keys, arguments, false); + } + + private long executeInteger( + byte[] script, byte[][] keys, byte[][] arguments, boolean hasDeadlineArgument) { requireNoAmbientTransaction(); - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { + if (installationBudget != null) { + return executeInteger(script, keys, arguments, hasDeadlineArgument, installationBudget); + } + if (handoffClock != null) { + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + handoffClock, + handoffDeadlineMillis, + budget -> executeInteger(script, keys, arguments, hasDeadlineArgument, budget)); + } + return executeInteger(script, keys, arguments, false, null); + } + + private long executeInteger( + byte[] script, + byte[][] keys, + byte[][] arguments, + boolean hasDeadlineArgument, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + if (budget != null) budget.check(); + StatefulRedisConnection connection = openConnection(budget); + try { + if (hasDeadlineArgument) requireStableConnection(connection); RedisAsyncCommands commands = connection.async(); - requirePrincipal(await(commands.aclWhoami())); - String loadedSha = await(commands.scriptLoad(script)); + requirePrincipal(await(commands::aclWhoami, budget)); + String loadedSha = await(() -> commands.scriptLoad(script), budget); if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); - Long result = await(commands.evalsha(loadedSha, ScriptOutputType.INTEGER, keys, arguments)); + if (hasDeadlineArgument) { + // Acquire's Lua script also caps its initial TTL at the remaining Redis time. + arguments[arguments.length - 1] = redisDeadlineArgument(commands, budget); + } + Long result = + await( + () -> commands.evalsha(loadedSha, ScriptOutputType.INTEGER, keys, arguments), budget); if (result == null) throw unavailable(); return result; } catch (RuntimeException failure) { throw unavailable(failure); + } finally { + if (budget == null) connection.close(); + else + budget.awaitAsyncClose( + CanonicalGameplayOriginalNewCapacityExecutionBudget.startRedisClose(connection)); } } + private StatefulRedisConnection openConnection( + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + if (budget == null) { + return coordinationUri == null + ? redisClient.connect(ByteArrayCodec.INSTANCE) + : redisClient.connect(ByteArrayCodec.INSTANCE, coordinationUri); + } + RedisURI uri = Objects.requireNonNull(coordinationUri); + long timeout = Math.min(uri.getTimeout().toMillis(), budget.remainingMillis()); + if (timeout < 1) throw unavailable(); + RedisURI bounded = RedisURI.builder(uri).withTimeout(Duration.ofMillis(timeout)).build(); + var pending = redisClient.connectAsync(ByteArrayCodec.INSTANCE, bounded); + try { + return pending.get(timeout, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + try { + awaitLateConnectionCleanup(pending, budget); + } finally { + Thread.currentThread().interrupt(); + } + throw unavailable(interrupted); + } catch (TimeoutException expired) { + awaitLateConnectionCleanup(pending, budget); + throw unavailable(expired); + } catch (ExecutionException failure) { + throw unavailable(failure); + } + } + + private static void awaitLateConnectionCleanup( + io.lettuce.core.ConnectionFuture> pending, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + // The caller returns at the operation deadline. This worker keeps its admission permit + // until the pending handshake and any late connection close have finished. + var connection = pending.handle((opened, failure) -> opened).join(); + if (connection == null) return; + var close = CanonicalGameplayOriginalNewCapacityExecutionBudget.startRedisClose(connection); + budget.retainUntilAsyncClose(close); + close.handle((ignored, failure) -> null).join(); + } + private RedisScriptDescriptor requireBridgeDescriptor() { try { RedisScriptDescriptor descriptor = @@ -677,9 +1001,50 @@ private static void requirePrincipal(String principal) { if (!PRINCIPAL.equals(principal)) throw unavailable(); } + private static void requireStableConnection(StatefulRedisConnection connection) { + // The TIME sample and script must address the same physical server connection. + if (connection.getOptions() == null || connection.getOptions().isAutoReconnect()) { + throw unavailable(); + } + } + + private static byte[] redisDeadlineArgument( + RedisAsyncCommands commands, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + // Read the remaining budget after TIME returns so sampling latency cannot extend it. + long redisNowMillis = redisTimeMillis(await(commands::time, budget)); + long remainingMillis = TimeUnit.NANOSECONDS.toMillis(budget.remainingNanos()); + if (remainingMillis <= 0) throw unavailable(); + return ascii(Long.toString(Math.addExact(redisNowMillis, remainingMillis))); + } + + private static long redisTimeMillis(List reply) { + if (reply == null || reply.size() != 2 || reply.get(0) == null || reply.get(1) == null) { + throw unavailable(); + } + long seconds = Long.parseLong(new String(reply.get(0), StandardCharsets.US_ASCII)); + long microseconds = Long.parseLong(new String(reply.get(1), StandardCharsets.US_ASCII)); + if (seconds <= 0 || microseconds < 0 || microseconds >= 1_000_000L) throw unavailable(); + return Math.addExact(Math.multiplyExact(seconds, 1_000L), microseconds / 1_000L); + } + private static T await(RedisFuture future) { + return await(future, COMMAND_TIMEOUT_MILLIS); + } + + private static T await( + Supplier> operation, + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + if (budget == null) return await(operation.get()); + long timeout = Math.min(COMMAND_TIMEOUT_MILLIS, budget.remainingMillis()); + T result = await(operation.get(), timeout); + budget.check(); + return result; + } + + private static T await(RedisFuture future, long timeoutMillis) { try { - return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + return future.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); future.cancel(true); @@ -763,7 +1128,11 @@ private byte[][] arguments(Long ttlMillis) { return new byte[][] {ascii(SCHEMA), ascii(token), ascii(Long.toString(regionEpoch))}; } return new byte[][] { - ascii(SCHEMA), ascii(token), ascii(Long.toString(regionEpoch)), ascii(ttlMillis.toString()) + ascii(DEADLINE_SCHEMA), + ascii(token), + ascii(Long.toString(regionEpoch)), + ascii(ttlMillis.toString()), + ascii("0") }; } 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 01799aec41..d6d49e7ad6 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 @@ -10,6 +10,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayActorOrigins; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; @@ -28,13 +29,25 @@ 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 FENCE_SEQUENCE = "game_session_region_executor_fence_seq"; 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; + private final CanonicalGameplayOriginalNewCapacityExecutionBudget installationBudget; + CanonicalGameplayRegionRuntimeStatusRepository(DSLContext dsl) { + this(dsl, null); + } + + private CanonicalGameplayRegionRuntimeStatusRepository( + DSLContext dsl, CanonicalGameplayOriginalNewCapacityExecutionBudget installationBudget) { this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.installationBudget = installationBudget; + } + + CanonicalGameplayRegionRuntimeStatusRepository forBudget( + CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { + return new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl), budget); } static boolean hasFrozenTransfer( @@ -283,11 +296,39 @@ boolean matchesTimelinePreparation( /** The durable PREPARED-to-INITIALIZING transition grants the sole permission to create meta. */ Optional beginInitialTimeline( TimelinePreparation preparation, Instant now) { + return claimInitialTimeline(preparation, now, null, null); + } + + Optional beginInitialTimeline( + TimelinePreparation preparation, + Instant now, + CanonicalGameplayBindingInventoryRepository bindingInventory, + CanonicalGameplayBindingProvisionalCasEvidence expectedBinding) { + Objects.requireNonNull(bindingInventory, "bindingInventory"); + Objects.requireNonNull(expectedBinding, "expectedBinding"); + if (!preparation.transitionId.equals(expectedBinding.transition().transitionId()) + || !Arrays.equals(preparation.bindingRef, expectedBinding.candidate().bindingRef().bytes()) + || !preparation.bindingGeneration.equals(expectedBinding.candidate().bindingGeneration())) { + throw unavailable(); + } + return claimInitialTimeline(preparation, now, bindingInventory, expectedBinding); + } + + private Optional claimInitialTimeline( + TimelinePreparation preparation, + Instant now, + CanonicalGameplayBindingInventoryRepository bindingInventory, + CanonicalGameplayBindingProvisionalCasEvidence expectedBinding) { requireNoAmbientTransaction(); Objects.requireNonNull(preparation, "preparation"); Objects.requireNonNull(now, "now"); + // A failed or ambiguous claim never returns its permit; the INITIALIZING row stays held. return dsl.transactionResult(configuration -> { DSLContext transaction = DSL.using(configuration); + // Match bridge authorization: inventory and instance runtime before region, then binding. + if (bindingInventory != null) { + bindingInventory.lockInitialTimelineBindingScope(transaction, expectedBinding); + } lockRegionScope(transaction, preparation.tenantRegionTag); if (transaction.fetchOne( "SELECT 1 FROM " @@ -308,24 +349,25 @@ Optional beginInitialTimeline( if (row == null) throw unavailable(); TimelinePreparation current = toTimelinePreparation(row); if (!samePreparation(preparation, current)) throw unavailable(); - if (current.phase == TimelinePreparationPhase.INSTALLED) { - return Optional.empty(); - } if (current.phase != TimelinePreparationPhase.PREPARED) return Optional.empty(); - UUID claimGeneration = UUID.randomUUID(); + if (bindingInventory != null) { + bindingInventory.requireCurrentInitialTimelineBinding(transaction, expectedBinding); + } + // Lock waits and source checks cannot consume the installation deadline and still + // grant irreversible permission to create Redis meta. + if (installationBudget != null) installationBudget.check(); + var permit = new InitialInitializationPermit(current.operationId, current.sourceDigest()); int updated = transaction.execute( "UPDATE " + PREPARATION_TABLE - + " SET phase = 'INITIALIZING', initialization_claim_generation = ?," - + " updated_at = ? WHERE initialization_operation_id = ? AND phase = 'PREPARED'", - claimGeneration, + + " SET phase = 'INITIALIZING', initialization_claim_generation = ?, updated_at = ?" + + " WHERE initialization_operation_id = ? AND phase = 'PREPARED'", + permit.generation(), java.sql.Timestamp.from(now), current.operationId); if (updated != 1) throw unavailable(); - return Optional.of( - new InitialInitializationPermit( - current.operationId, current.sourceDigest(), claimGeneration)); + return Optional.of(permit); }); } @@ -415,6 +457,8 @@ private TimelinePreparation updatePreparationAfterRedis( nextPhase = "REDIS_INITIALIZED"; } else { if (currentStatus == null + || !Objects.equals( + preparation.initializationClaimGeneration, current.initializationClaimGeneration) || (current.phase != TimelinePreparationPhase.REDIS_INITIALIZED && current.phase != TimelinePreparationPhase.INSTALLED)) { throw unavailable(); @@ -426,6 +470,12 @@ private TimelinePreparation updatePreparationAfterRedis( || !status.leaseTokenCorrelation().equals(leaseTokenCorrelation)) { throw unavailable(); } + if (current.phase == TimelinePreparationPhase.INSTALLED + && status.executorFence().equals(current.executorFence) + && leaseTokenCorrelation.equals(current.leaseTokenCorrelation) + && redisMetaDigest.equals(current.redisMetaDigest)) { + return current; + } nextPhase = "INSTALLED"; } int updated = @@ -639,6 +689,7 @@ private static TimelinePreparation toTimelinePreparation(Record row) { row.get("region_epoch", Long.class), row.get("last_committed_tick_id", Long.class), TimelinePreparationPhase.valueOf(row.get("phase", String.class)), + row.get("initialization_claim_generation", UUID.class), row.get("lease_token_correlation", String.class), fence == null ? null : BigInteger.valueOf(fence), row.get("redis_meta_digest", String.class), @@ -992,6 +1043,7 @@ static final class TimelinePreparation { private final long regionEpoch; private final long lastCommittedTickId; private final TimelinePreparationPhase phase; + private final UUID initializationClaimGeneration; private final String leaseTokenCorrelation; private final BigInteger executorFence; private final String redisMetaDigest; @@ -1026,6 +1078,7 @@ private TimelinePreparation( long regionEpoch, long lastCommittedTickId, TimelinePreparationPhase phase, + UUID initializationClaimGeneration, String leaseTokenCorrelation, BigInteger executorFence, String redisMetaDigest, @@ -1072,6 +1125,7 @@ private TimelinePreparation( this.regionEpoch = regionEpoch; this.lastCommittedTickId = lastCommittedTickId; this.phase = Objects.requireNonNull(phase, "phase"); + this.initializationClaimGeneration = initializationClaimGeneration; this.leaseTokenCorrelation = leaseTokenCorrelation; this.executorFence = executorFence; this.redisMetaDigest = redisMetaDigest; @@ -1114,6 +1168,11 @@ TimelinePreparationPhase phase() { return phase; } + boolean hasInitializationClaimGeneration() { + return initializationClaimGeneration != null + && !initializationClaimGeneration.equals(new UUID(0L, 0L)); + } + String leaseTokenCorrelation() { return leaseTokenCorrelation; } @@ -1141,25 +1200,28 @@ String absenceProofDigest() { static final class InitialInitializationPermit { private final UUID operationId; private final String sourceDigest; - private final UUID claimGeneration; + private final UUID generation = UUID.randomUUID(); + private final AtomicBoolean dispatched = new AtomicBoolean(); + + boolean consumeDispatch() { + return dispatched.compareAndSet(false, true); + } - private InitialInitializationPermit( - UUID operationId, String sourceDigest, UUID claimGeneration) { + private InitialInitializationPermit(UUID operationId, String sourceDigest) { this.operationId = Objects.requireNonNull(operationId, "operationId"); this.sourceDigest = Objects.requireNonNull(sourceDigest, "sourceDigest"); - this.claimGeneration = Objects.requireNonNull(claimGeneration, "claimGeneration"); } UUID operationId() { return operationId; } - String sourceDigest() { - return sourceDigest; + UUID generation() { + return generation; } - UUID claimGeneration() { - return claimGeneration; + String sourceDigest() { + return sourceDigest; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java index b15fa5baae..c83e68d745 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java @@ -13,10 +13,10 @@ /** Passive descriptor contribution for the manually composed region lease scripts. */ public final class CanonicalGameplayRegionLeaseRedisScriptContribution implements RedisScriptContribution { - public static final String ACQUIRE_ID = "game-session.region-lease-acquire.v1"; - public static final String RENEW_ID = "game-session.region-lease-renew.v1"; + public static final String ACQUIRE_ID = "game-session.region-lease-acquire.v2"; + public static final String RENEW_ID = "game-session.region-lease-renew.v2"; public static final String READ_ID = "game-session.region-lease-read.v1"; - public static final String TIMELINE_INITIALIZE_ID = "game-session.region-timeline-initialize.v1"; + public static final String TIMELINE_INITIALIZE_ID = "game-session.region-timeline-initialize.v2"; public static final String ACQUIRE_PATH = "redis/lua/game-session-region-lease-acquire.lua"; public static final String RENEW_PATH = "redis/lua/game-session-region-lease-renew.lua"; public static final String READ_PATH = "redis/lua/game-session-region-lease-read.lua"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java index 75f1c1cc7d..422059ca95 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Deadline; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; @@ -29,16 +30,26 @@ public CanonicalInitialPlayerLocationRegionResolver( * Reads the exact current initial-room consequence, then revalidates it through World lifecycle. */ public ResolvedRegion resolve(CanonicalInitialPlayerLocationRequest request) { + return resolve(request, null); + } + + /** Shares the receiving operation's deadline across placement and lifecycle reads. */ + public ResolvedRegion resolve( + CanonicalInitialPlayerLocationRequest request, Deadline operationDeadline) { Objects.requireNonNull(request, "request"); CanonicalInitialPlayerLocationRegionResponse observed = - initialLocationClient.readInitialPlayerLocationRegion(request); + operationDeadline == null + ? initialLocationClient.readInitialPlayerLocationRegion(request) + : initialLocationClient.readInitialPlayerLocationRegion(request, operationDeadline); var lifecycle = observed.getLifecycle(); WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest = WorldCanonicalInstanceLifecycleEvidence.Request.fromStored( lifecycle.getCanonicalRequestBytes().toByteArray()); UUID canonicalRegionId = UUID.fromString(observed.getCanonicalRegionInstanceUuid()); CanonicalRegionBootstrapAssignmentResolver.Assignment current = - lifecycleResolver.resolve(lifecycleRequest, canonicalRegionId); + operationDeadline == null + ? lifecycleResolver.resolve(lifecycleRequest, canonicalRegionId) + : lifecycleResolver.resolve(lifecycleRequest, canonicalRegionId, operationDeadline); if (!request.getExpectedTarget().equals(observed.getExpectedTarget()) || !lifecycleRequest.equals(current.request()) || !lifecycle.getLifecycleStatus().equals(current.lifecycleStatus()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java index df94b0de37..add16f1fbc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service; +import io.grpc.Deadline; import java.util.Map; import java.util.Objects; import java.util.UUID; @@ -25,10 +26,20 @@ public CanonicalRegionBootstrapAssignmentResolver( */ public Assignment resolve( WorldCanonicalInstanceLifecycleEvidence.Request request, UUID canonicalRegionId) { + return resolve(request, canonicalRegionId, null); + } + + public Assignment resolve( + WorldCanonicalInstanceLifecycleEvidence.Request request, + UUID canonicalRegionId, + Deadline operationDeadline) { Objects.requireNonNull(request, "request"); requireNonNil(canonicalRegionId, "canonicalRegionId"); - WorldCanonicalInstanceLifecycleEvidence evidence = lifecycleClient.read(request); + WorldCanonicalInstanceLifecycleEvidence evidence = + operationDeadline == null + ? lifecycleClient.read(request) + : lifecycleClient.read(request, operationDeadline); if (evidence == null) { throw new IllegalStateException("World lifecycle client returned no owner evidence"); } diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua index f2dac7a3c5..f3d39a8860 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua @@ -1,10 +1,17 @@ --- Claims only a lease whose separate canonical timeline metadata already matches the expected epoch. +-- Claims a region lease only when the canonical timeline matches the expected epoch. +-- gs_region_lease/v2 caps the initial lease at its Redis TIME deadline. Zero omits the cap. local leaseKey = KEYS[1] local metaKey = KEYS[2] -if #KEYS ~= 2 or #ARGV ~= 4 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end +if #KEYS ~= 2 or #ARGV ~= 5 or ARGV[1] ~= 'gs_region_lease/v2' then return -1 end local token = ARGV[2] local expectedEpoch = ARGV[3] local ttl = ARGV[4] +local deadlineText = ARGV[5] +if deadlineText ~= '0' and (not string.match(deadlineText, '^[1-9][0-9]*$') + or #deadlineText > 16 or (#deadlineText == 16 and deadlineText > '9007199254740991')) then + return -1 +end +local deadline = tonumber(deadlineText) local function validUuid(value) return string.len(value) == 36 @@ -67,6 +74,13 @@ if keyType == 'string' then if redis.call('GET', leaseKey) == token then return 2 end return 0 end +if deadline > 0 then + local now = redis.call('TIME') + local nowMillis = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000) + local remainingMillis = deadline - nowMillis + if remainingMillis <= 0 then return 0 end + ttl = string.format('%.0f', math.min(tonumber(ttl), remainingMillis)) +end local result = redis.call('SET', leaseKey, token, 'PX', ttl, 'NX') if result and result.ok == 'OK' then return 1 end return 0 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua index 49f1609adb..7a9edc3228 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua @@ -1,10 +1,16 @@ -- Renews only the exact live lease and a structurally complete separate metadata epoch. local leaseKey = KEYS[1] local metaKey = KEYS[2] -if #KEYS ~= 2 or #ARGV ~= 4 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end +if #KEYS ~= 2 or #ARGV ~= 5 or ARGV[1] ~= 'gs_region_lease/v2' then return -1 end local token = ARGV[2] local expectedEpoch = ARGV[3] local ttl = ARGV[4] +local deadlineText = ARGV[5] +if deadlineText ~= '0' and (not string.match(deadlineText, '^[1-9][0-9]*$') + or #deadlineText > 16 or (#deadlineText == 16 and deadlineText > '9007199254740991')) then + return -1 +end +local deadline = tonumber(deadlineText) local function validUuid(value) return string.len(value) == 36 @@ -60,5 +66,11 @@ if not validMeta() then return 0 end if redis.call('TYPE', leaseKey).ok ~= 'string' or redis.call('PTTL', leaseKey) <= 0 or redis.call('GET', leaseKey) ~= token then return 0 end +if deadline > 0 then + local now = redis.call('TIME') + if tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000) >= deadline then + return 0 + end +end redis.call('PEXPIRE', leaseKey, ttl) return 1 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua index f489e49d7b..396bb2f552 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua @@ -1,7 +1,8 @@ -- Proves a truly absent timeline, then initializes its complete baseline with the first lease. +-- Redis TIME refuses PROBE/INITIALIZE after the caller's frozen operation deadline. local leaseKey = KEYS[1] local metaKey = KEYS[2] -if #KEYS ~= 2 or #ARGV ~= 8 or ARGV[1] ~= 'gs_region_timeline_init/v1' then return -1 end +if #KEYS ~= 2 or #ARGV ~= 9 or ARGV[1] ~= 'gs_region_timeline_init/v2' then return -1 end local action = ARGV[2] local token = ARGV[3] local expectedEpoch = ARGV[4] @@ -9,6 +10,7 @@ local operationId = ARGV[5] local sourceDigest = ARGV[6] local ttl = ARGV[7] local mayCreate = ARGV[8] +local absoluteDeadlineMillis = ARGV[9] local function validUuid(value) return string.len(value) == 36 @@ -63,15 +65,46 @@ if not tag1 or tag1 ~= tag2 or not validUuid(operationId) or not string.match(sourceDigest, '^[0-9a-f]+$') or string.len(sourceDigest) ~= 64 or not positiveInt64(ttl) - or (mayCreate ~= '0' and mayCreate ~= '1') then return -1 end + or (mayCreate ~= '0' and mayCreate ~= '1') + or not positiveInt64(absoluteDeadlineMillis) + or string.len(absoluteDeadlineMillis) > 16 + or (string.len(absoluteDeadlineMillis) == 16 and absoluteDeadlineMillis > '9007199254740991') + then return -1 end + +-- Check TIME before any mutation. A permission change after PROBE still leaves a +-- definite no-write outcome for this exact initialization claim. +if not redis.acl_check_cmd('TIME') then return -4 end +local redisTime = redis.call('TIME') +local redisNowMillis = tonumber(redisTime[1]) * 1000 + math.floor(tonumber(redisTime[2]) / 1000) +local remainingMillis = tonumber(absoluteDeadlineMillis) - redisNowMillis +if (action == 'PROBE' or action == 'INITIALIZE') and remainingMillis <= 0 then return -3 end +if action == 'INITIALIZE' then + ttl = math.min(tonumber(ttl), remainingMillis) +end local leaseType = redis.call('TYPE', leaseKey).ok local metaType = redis.call('TYPE', metaKey).ok if (leaseType ~= 'none' and leaseType ~= 'string') or (metaType ~= 'none' and metaType ~= 'hash') then return -2 end +local function canCreateMeta() + return redis.acl_check_cmd('HSET', metaKey, + 'region_epoch', expectedEpoch, + 'current_tick_id', '-1', + 'current_tick_state', 'APPLIED', + 'first_timeline_operation_id', operationId, + 'first_timeline_source_digest', sourceDigest) +end + +local function canCreateLease() + return redis.acl_check_cmd('SET', leaseKey, token, 'PX', ttl, 'NX') +end + if action == 'PROBE' then - if leaseType == 'none' and metaType == 'none' then return 1 end + if leaseType == 'none' and metaType == 'none' then + if not canCreateMeta() or not canCreateLease() then return -4 end + return 1 + end return 0 end @@ -85,13 +118,16 @@ end if metaType == 'none' then if leaseType ~= 'none' or mayCreate ~= '1' then return 0 end + -- Validate both writes before either key changes. + if not canCreateMeta() or not canCreateLease() then return -4 end redis.call('HSET', metaKey, 'region_epoch', expectedEpoch, 'current_tick_id', '-1', 'current_tick_state', 'APPLIED', 'first_timeline_operation_id', operationId, 'first_timeline_source_digest', sourceDigest) -elseif not validTimelineMeta() then +elseif not validTimelineMeta() or leaseType == 'none' then + -- Existing metadata without its original live lease cannot authorize a different grant. return 0 end diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json index c00ea1e224..fc1766fd7b 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json @@ -1,7 +1,7 @@ { - "scriptId": "game-session.region-lease-acquire.v1", + "scriptId": "game-session.region-lease-acquire.v2", "resourcePath": "redis/lua/game-session-region-lease-acquire.lua", - "sha256": "eca9c386644d6cb518db2849e2c4dcf8b19dd0fcd2ac53dd7ebe7a7152e543d8", + "sha256": "4029d88915b32f134efbf635a9a78c4b1aabfa252e7dc1c17005e8cb12e13cbe", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -9,7 +9,7 @@ {"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}, {"name": "regionMeta", "ownedPrefix": "tick:", "hashTagDeclaration": "REQUIRED"} ], - "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "expectedRegionEpoch"}, {"name": "leaseTtlMs"}], + "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "expectedRegionEpoch"}, {"name": "leaseTtlMs"}, {"name": "absoluteDeadlineMillis"}], "category": "TICK_LOCK", "outcomes": [ {"code": "LEASE_ACQUIRED", "category": "SUCCESS", "effect": "MUTATING"}, @@ -20,8 +20,8 @@ ], "resetSensitivity": "REGION", "lossClass": "STAGED_EFFECT_OR_RETRY", - "tailLossBehavior": "Lease loss or expiry ends the current owner attempt. The durable region timeline remains authoritative and a successor must acquire a new lease, install a new durable fence, and revalidate that exact grant before any bridge or tick work.", + "tailLossBehavior": "Lease loss or expiry ends the current owner attempt and holds continuation at the initial installation boundary while the durable owner fence remains. Normal handoff requires a qualified successor grant, a new durable fence, and revalidation of the exact grant before bridge or tick work.", "compatibilityLevel": "COMPATIBLE", - "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "none"}], + "supportedCoexistence": [{"callerVersion": "v2", "payloadVersion": "none"}], "legacyPayloadShape": null } diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json index fd6591b131..6a576c3fc1 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json @@ -1,7 +1,7 @@ { - "scriptId": "game-session.region-lease-renew.v1", + "scriptId": "game-session.region-lease-renew.v2", "resourcePath": "redis/lua/game-session-region-lease-renew.lua", - "sha256": "0e7cfd77259c1158e3b32d2b7e0eea1b863a532bada03fd77c7970486f3f2412", + "sha256": "cf4d973ff17b8642e968db06eb9078af947e91675b27674cd9fb160da8c44972", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -9,7 +9,7 @@ {"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}, {"name": "regionMeta", "ownedPrefix": "tick:", "hashTagDeclaration": "REQUIRED"} ], - "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "expectedRegionEpoch"}, {"name": "leaseTtlMs"}], + "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "expectedRegionEpoch"}, {"name": "leaseTtlMs"}, {"name": "absoluteDeadlineMillis"}], "category": "TICK_LOCK", "outcomes": [ {"code": "LEASE_RENEWED", "category": "SUCCESS", "effect": "MUTATING"}, @@ -20,6 +20,6 @@ "lossClass": "STAGED_EFFECT_OR_RETRY", "tailLossBehavior": "Renewal compares the exact grant, scope, source, owner, and epoch. A missing, expired, or changed lease does not renew and ends the current owner attempt; renewal never advances the durable executor fence.", "compatibilityLevel": "COMPATIBLE", - "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "none"}], + "supportedCoexistence": [{"callerVersion": "v2", "payloadVersion": "none"}], "legacyPayloadShape": null } diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json index c8134bc924..71b2059086 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json @@ -1,7 +1,7 @@ { - "scriptId": "game-session.region-timeline-initialize.v1", + "scriptId": "game-session.region-timeline-initialize.v2", "resourcePath": "redis/lua/game-session-region-timeline-initialize.lua", - "sha256": "2a403cd54d2033aff3d12403c0fd01821429bda39fcd8b164d3e8bdc98523325", + "sha256": "d0e60e8100a658da30c4d652e64883a00b784a5354a1a5f25df5ae10c8c1940d", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -12,21 +12,24 @@ "arguments": [ {"name": "schema"}, {"name": "action"}, {"name": "token"}, {"name": "expectedRegionEpoch"}, {"name": "initializationOperationId"}, {"name": "preparationDigest"}, {"name": "leaseTtlMs"}, - {"name": "mayCreateFromAbsence"} + {"name": "mayCreateFromAbsence"}, {"name": "absoluteDeadlineMillis"} ], "category": "TICK_LOCK", "outcomes": [ {"code": "TIMELINE_INITIALIZED", "category": "SUCCESS", "effect": "MUTATING"}, {"code": "INITIALIZATION_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "TIMELINE_VERIFIED", "category": "SUCCESS", "effect": "NON_MUTATING"}, {"code": "TIMELINE_ABSENT", "category": "SUCCESS", "effect": "NON_MUTATING"}, {"code": "EXISTING_OR_CONFLICTING_STATE", "category": "STALE", "effect": "NON_MUTATING"}, {"code": "INVALID_ARGS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, - {"code": "TYPE_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + {"code": "TYPE_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "DEADLINE_EXPIRED", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "CREATE_ACL_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} ], "resetSensitivity": "REGION", "lossClass": "STAGED_EFFECT_OR_RETRY", - "tailLossBehavior": "Only the original durable preparation may establish the complete epoch-1 and tick-minus-one APPLIED baseline. An exact retained marker permits same-operation lease recovery; absent, changed, or partial state never triggers a new initialization.", + "tailLossBehavior": "Only the original durable preparation may establish the complete epoch-1 and tick-minus-one APPLIED baseline. The original single-use SQL creation permission remains required. The deadline-bound PROBE requires TIME and the exact write permissions before the creation permission is consumed. INITIALIZE checks TIME and any required write permissions before writing either key. Once that permission is consumed, every INITIALIZE outcome other than success, including DEADLINE_EXPIRED (-3) and CREATE_ACL_REFUSED (-4), leaves the preparation held. Redis refuses a delayed INITIALIZE mutation after the frozen operation deadline. Exact retained metadata and the matching live original token permit a read-only replay. Absence alone never authorizes creation: only proved absence with the fresh single-use SQL creation permission and a live deadline creates both keys, and a retry without that permission stays held. Missing or expired leases and changed or partial state never authorize replacement.", "compatibilityLevel": "COMPATIBLE", - "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "none"}], + "supportedCoexistence": [{"callerVersion": "v2", "payloadVersion": "none"}], "legacyPayloadShape": null } 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 c0e639d034..c2ed260897 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 @@ -193,6 +193,7 @@ private void prepare( CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( binding.dsl(), coordination, + coordinationUri, scripts, CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture ::controlledRegionIncarnation, 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/CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport.java index 185dfb09f6..f8b030354d 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/CanonicalGameplayOriginalNewFinalAdmissionOwnerTestSupport.java @@ -189,6 +189,7 @@ protected void bridge( CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( fixture.dsl(), ownerClient, + ownerUri, fixture.transitionId(), sources.request, sources.resolver, 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 75d3baa51f..a64303f678 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 @@ -6,6 +6,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.zaxxer.hikari.HikariDataSource; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.TlsServerCredentials; @@ -14,11 +15,16 @@ import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.codec.ByteArrayCodec; -import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.event.command.CommandListener; +import io.lettuce.core.event.command.CommandStartedEvent; +import io.lettuce.core.event.command.CommandSucceededEvent; import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.RedisCommand; +import java.io.InputStream; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Path; @@ -139,22 +145,19 @@ static void certificates() throws Exception { new LoopbackMtlsTestPki.IdentitySpec("entity-server", ENTITY_SERVER_PEER, true)); } - @Test - void composesLeaseInstallRevalidationReuseAndFailClosedSourceChanges() throws Exception { + @org.junit.jupiter.params.ParameterizedTest( + name = "initialization interrupted before SQL install: {0}") + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void composesInitialLeaseAndHoldsReplacementAcrossSourceChanges(boolean recoveryDrift) + throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); - ControlledConnectionFailureDataSource dataSource = dataSource(); - CanonicalGameplayIssuerTestFixtures.migrationConfiguration( - dataSource, - "public", - "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) - .load() - .migrate(); + var schema = newTestSchema(); + var dataSource = new ControlledConnectionFailureDataSource(schema.dataSource()); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(dsl); try (RedisFixture redis = RedisFixture.open()) { - var redisOwner = - new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var redisOwner = org.mockito.Mockito.spy(redis.owner()); WorldFixture world = WorldFixture.open(); ControlledStableIncarnationSource incarnationSource = new ControlledStableIncarnationSource(); var bindingEvidence = provisionalEvidence(world.request()); @@ -256,34 +259,79 @@ void composesLeaseInstallRevalidationReuseAndFailClosedSourceChanges() throws Ex assertThat(redis.admin().type(redisKey)).isEqualTo("none"); assertThat(statusRepository.find(qualifiedSource)).isEmpty(); - // Reads one and two are the initial source read and the new pre-claim revalidation; read - // three runs after EVALSHA, where this case exercises recovery-evidence drift. - world.setAfterRead(3, incarnationSource::changeRecoveryEvidence); - Throwable recoveryDriftFailure = - catchThrowable(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())); - assertThat(recoveryDriftFailure).isInstanceOf(IllegalStateException.class); - assertThat(statusRepository.find(qualifiedSource)).isEmpty(); - Record retainedPreparation = - dsl.fetchOne( - "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", - TRANSITION_ID); - assertThat(retainedPreparation) - .as( - "Timeline preparation must precede recovery drift; original failure: %s", - recoveryDriftFailure.getCause()) - .isNotNull(); - assertThat(retainedPreparation.get("phase", String.class)).isEqualTo("REDIS_INITIALIZED"); - UUID initialTimelineOperationId = - retainedPreparation.get("initialization_operation_id", UUID.class); - String initialTimelineSourceDigest = - retainedPreparation.get("preparation_digest", String.class); - assertThat(redis.admin().hlen(ascii(initialMetaKey))).isEqualTo(5L); - assertThat(redis.admin().pttl(ascii(initialMetaKey))).isEqualTo(-1L); - world.resetReads(); - incarnationSource.restoreRecoveryEvidence(); - assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + if (recoveryDrift) { + // Reads one and two are the initial source read and the new pre-claim revalidation; read + // three runs after EVALSHA, where this case exercises recovery-evidence drift. + world.setAfterRead(3, incarnationSource::changeRecoveryEvidence); + Throwable recoveryDriftFailure = + catchThrowable(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())); + assertThat(recoveryDriftFailure).isInstanceOf(IllegalStateException.class); + assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + Record retainedPreparation = + dsl.fetchOne( + "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", + TRANSITION_ID); + assertThat(retainedPreparation) + .as( + "Timeline preparation must precede recovery drift; original failure: %s", + recoveryDriftFailure.getCause()) + .isNotNull(); + assertThat(retainedPreparation.get("phase", String.class)).isEqualTo("REDIS_INITIALIZED"); + assertThat(redis.admin().hlen(ascii(initialMetaKey))).isEqualTo(5L); + assertThat(redis.admin().pttl(ascii(initialMetaKey))).isEqualTo(-1L); + world.resetReads(); + incarnationSource.restoreRecoveryEvidence(); + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + assertThatThrownBy(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().type(redisKey)).isEqualTo("none"); + assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + assertThat( + dsl.fetchOne( + "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", + TRANSITION_ID)) + .isEqualTo(retainedPreparation); + return; + } + 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); + byte[] leaseTokenAfterLostCompletion = redis.admin().get(redisKey); + long leaseExpiryAfterLostCompletion = redis.admin().pexpiretime(redisKey); + assertThat(leaseTokenAfterLostCompletion).isNotNull(); + assertThat(leaseExpiryAfterLostCompletion).isPositive(); + var retainedFirstOwner = statusRepository.find(qualifiedSource).orElseThrow(); + var retainedPreparation = + statusRepository.findTimelinePreparation(qualifiedSource).orElseThrow(); + assertThat(retainedPreparation.phase()) + .isEqualTo( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .REDIS_INITIALIZED); + UUID initialTimelineOperationId = retainedPreparation.operationId(); + String initialTimelineSourceDigest = retainedPreparation.sourceDigest(); + 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(redis.admin().get(redisKey)).containsExactly(leaseTokenAfterLostCompletion); + assertThat(redis.admin().pexpiretime(redisKey)).isEqualTo(leaseExpiryAfterLostCompletion); + assertThat(statusRepository.find(qualifiedSource).orElseThrow()) + .isEqualTo(retainedFirstOwner); var firstStatus = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(firstStatus.regionEpoch()).isEqualTo(1L); assertThat(firstStatus.lifecycleEpoch()).isEqualTo(7L); @@ -376,53 +424,46 @@ void composesLeaseInstallRevalidationReuseAndFailClosedSourceChanges() throws Ex var reused = firstOwner.installForTransition(firstInstallation, TRANSITION_ID, world.request()); + assertThat(reused.status).isEqualTo(firstStatus); assertThat(reused.grant).isSameAs(firstInstallation.grant); - assertThat(redis.admin().get(redisKey)).containsExactly(initialLeaseValue); - assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); assertThat(fenceSequenceValue(dsl)).isEqualTo(sequenceAfterInstall); incarnationSource.changeStorageGeneration("storage-generation-2"); assertThatThrownBy( () -> firstOwner.installForTransition(reused, TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); - assertThat(redis.admin().get(redisKey)).containsExactly(initialLeaseValue); - assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); - assertThat(fenceSequenceValue(dsl)).isEqualTo(sequenceAfterInstall); incarnationSource.restoreStorageGeneration(); WorldCanonicalInstanceLifecycleEvidence changed = changedEvidence(world.originalEvidence()); - for (int changedRead : new int[] {2, 3}) { - world.resetReads(); - world.replaceOnRead(changedRead, changed); + 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.resetReads(); world.setAfterRead(2, dataSource::failConnections); - Throwable sqlOutageFailure = - catchThrowable( - () -> firstOwner.installForTransition(reused, TRANSITION_ID, world.request())); - dataSource.restoreConnections(); + 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(); - world.resetReads(); - assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); - byte[] retainedMetadata = redis.admin().dump(ascii(initialMetaKey)); - String timelineImageSql = - "SELECT to_jsonb(preparation)::text FROM game_session_region_timeline_preparation" - + " preparation WHERE transition_id = ?"; - String retainedTimeline = - dsl.fetchSingle(timelineImageSql, TRANSITION_ID).get(0, String.class); - assertThat(retainedTimeline).isNotNull(); - var replacementOwner = + var contender = owner( bindingInventory, statusRepository, @@ -430,20 +471,622 @@ void composesLeaseInstallRevalidationReuseAndFailClosedSourceChanges() throws Ex world, "instance-b", incarnationSource); - assertThatThrownBy( - () -> replacementOwner.installForTransition(TRANSITION_ID, world.request())) - .isInstanceOf(IllegalStateException.class) - .hasMessage( - "Canonical Game Session region owner requires current exact assignment and lease evidence"); - assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(reused)) + assertThatThrownBy(() -> contender.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().get(redisKey)).containsExactly(initialLeaseValue); assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); - assertThat(dsl.fetchSingle(timelineImageSql, TRANSITION_ID).get(0, String.class)) - .isEqualTo(retainedTimeline); + + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(reused)) + .isInstanceOf(IllegalStateException.class); + + dsl.execute( + "UPDATE game_session_region_runtime_status" + + " SET last_committed_tick_batch_id = 'batch-8', last_committed_tick_id = 8" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId()); + redis + .admin() + .hset( + ascii(initialMetaKey), + 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())) + .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(retainedMetadata); + assertThat(redis.admin().dump(ascii(initialMetaKey))) + .containsExactly(timelineBeforeReplacement); assertThat(redis.admin().pttl(ascii(initialMetaKey))).isEqualTo(-1L); + } finally { + dropSchema(schema.schema()); + } + } + + @Test + void boundedTimelineCreationRejectsExpiryAndCapsNewLease() throws Exception { + try (RedisFixture redis = RedisFixture.open()) { + byte[] script; + try (InputStream input = + getClass() + .getClassLoader() + .getResourceAsStream("redis/lua/game-session-region-timeline-initialize.lua")) { + assertThat(input).isNotNull(); + script = input.readAllBytes(); + } + byte[] leaseKey = + ascii( + CanonicalGameplayRegionRedisKeys.lease( + ACCOUNT_ID, CHARACTER_ID, CANONICAL_REGION_ID)); + byte[] metaKey = + ascii( + CanonicalGameplayRegionRedisKeys.meta(ACCOUNT_ID, CHARACTER_ID, CANONICAL_REGION_ID)); + byte[][] keys = {leaseKey, metaKey}; + byte[][] arguments = { + ascii("gs_region_timeline_init/v2"), + ascii("INITIALIZE"), + ascii("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + ascii("1"), + ascii("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + ascii("a".repeat(64)), + ascii("30000"), + ascii("1"), + ascii("1") + }; + Long expired = redis.admin().eval(script, ScriptOutputType.INTEGER, keys, arguments); + assertThat(expired).isEqualTo(-3L); + assertThat(redis.admin().type(leaseKey)).isEqualTo("none"); + assertThat(redis.admin().type(metaKey)).isEqualTo("none"); + + arguments[8] = ascii("9007199254740993"); + Long unrepresentable = redis.admin().eval(script, ScriptOutputType.INTEGER, keys, arguments); + assertThat(unrepresentable).isEqualTo(-1L); + assertThat(redis.admin().type(leaseKey)).isEqualTo("none"); + assertThat(redis.admin().type(metaKey)).isEqualTo("none"); + + long submittedDeadline = redisTimeMillis(redis.admin()) + 10_000L; + arguments[8] = ascii(Long.toString(submittedDeadline)); + Long initialized = redis.admin().eval(script, ScriptOutputType.INTEGER, keys, arguments); + assertThat(initialized).isEqualTo(1L); + assertThat(redis.admin().pttl(leaseKey)).isPositive(); + assertThat(redis.admin().pexpiretime(leaseKey)) + .isPositive() + .isLessThanOrEqualTo(submittedDeadline); + assertThat(redis.admin().pttl(metaKey)).isEqualTo(-1L); + + byte[] retainedMeta = redis.admin().dump(metaKey); + assertThat(redis.admin().pexpire(leaseKey, 0)).isTrue(); + arguments[2] = ascii("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + arguments[7] = ascii("0"); + arguments[8] = ascii(Long.toString(redisTimeMillis(redis.admin()) + 10_000L)); + Long retainedWithoutLease = + redis.admin().eval(script, ScriptOutputType.INTEGER, keys, arguments); + assertThat(retainedWithoutLease).isZero(); + assertThat(redis.admin().type(leaseKey)).isEqualTo("none"); + assertThat(redis.admin().dump(metaKey)).containsExactly(retainedMeta); + assertThat(redis.admin().pttl(metaKey)).isEqualTo(-1L); + } + } + + @Test + void installationRefusesCapturedBindingWithoutDurableClaimEvidence() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try (RedisFixture redis = RedisFixture.open()) { + var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var redisOwner = redis.owner(); + WorldFixture world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var evidence = provisionalEvidence(world.request()); + var inventory = + org.mockito.Mockito.spy( + new CanonicalGameplayBindingInventoryRepository(testSchema.dsl())); + // Preflight compares two reads of the same synthetic evidence. Claim requalification + // still locks and reads the real SQL rows. + org.mockito.Mockito.doReturn(evidence) + .when(inventory) + .readProvisionalCasEvidence(TRANSITION_ID); + org.mockito.Mockito.doNothing() + .when(inventory) + .requireSameProvisionalSource( + org.mockito.ArgumentMatchers.same(evidence), + org.mockito.ArgumentMatchers.same(evidence)); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + prepareTimeline(statusRepository, redisOwner, world, evidence, source, incarnation); + var owner = + owner( + inventory, statusRepository, redisOwner, world, "missing-binding", incarnationSource); + + assertThatThrownBy(() -> owner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("Durable binding transition does not exist"); + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void installationDeadlineDuringSourceRecheckLeavesPreparedPermission() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try (RedisFixture redis = RedisFixture.open()) { + var claims = new java.util.concurrent.atomic.AtomicInteger(); + var claimObserver = + new org.jooq.impl.DefaultExecuteListener() { + @Override + public void executeStart(org.jooq.ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.contains("UPDATE game_session_region_timeline_preparation") + && sql.contains("SET phase = 'INITIALIZING'")) claims.incrementAndGet(); + } + }; + var statusRepository = + new CanonicalGameplayRegionRuntimeStatusRepository( + DSL.using( + testSchema + .dsl() + .configuration() + .derive(new org.jooq.impl.DefaultExecuteListenerProvider(claimObserver)))); + var redisOwner = redis.owner(); + WorldFixture world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var evidence = provisionalEvidence(world.request()); + var inventory = mock(CanonicalGameplayBindingInventoryRepository.class); + when(inventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(evidence); + when(inventory.forBudget(org.mockito.ArgumentMatchers.any())).thenReturn(inventory); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + prepareTimeline(statusRepository, redisOwner, world, evidence, source, incarnation); + var now = new AtomicReference<>(Instant.now()); + Clock clock = + new Clock() { + @Override + public java.time.ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(java.time.ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now.get(); + } + }; + world.resetReads(); + // The second source read occurs after Redis preflight, before the irreversible SQL claim. + world.setAfterRead(2, () -> now.updateAndGet(value -> value.plusSeconds(10))); + var owner = + new CanonicalGameplayRegionLeaseOwner( + inventory, + statusRepository, + redisOwner, + incarnationSource, + world.resolver(), + runtimeIdentity("expired-before-claim"), + Duration.ofSeconds(30), + clock, + true); + var evaluations = new java.util.concurrent.atomic.AtomicInteger(); + var redisObserver = + new CommandListener() { + @Override + public void commandStarted(CommandStartedEvent event) { + if (event.getCommand().getType() == CommandType.EVALSHA) + evaluations.incrementAndGet(); + } + }; + redis.ownerClient().addListener(redisObserver); + try { + assertThatThrownBy(() -> owner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(claims).hasValue(0); + assertThat(evaluations).as("PROBE only, no INITIALIZE").hasValue(1); + } finally { + redis.ownerClient().removeListener(redisObserver); + } + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + assertThat(world.observedDeadlines).hasSizeGreaterThanOrEqualTo(4); + assertThat(world.observedDeadlines) + .allSatisfy(deadline -> assertThat(deadline).isSameAs(world.observedDeadlines.get(0))); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void installationHoldsTheClaimAfterAPhysicalRedisDeadlineRefusal() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try (RedisFixture redis = RedisFixture.open()) { + var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var redisOwner = redis.owner(); + WorldFixture world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var evidence = provisionalEvidence(world.request()); + var inventory = mock(CanonicalGameplayBindingInventoryRepository.class); + when(inventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(evidence); + when(inventory.forBudget(org.mockito.ArgumentMatchers.any())).thenReturn(inventory); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + prepareTimeline(statusRepository, redisOwner, world, evidence, source, incarnation); + var deadlineObservation = new PreparedTimelineDeadlineObservation(redis.ownerClient(), true); + world.resetReads(); + // The second source read occurs after Redis preflight, before the irreversible SQL claim. + world.setAfterRead( + 2, () -> awaitRedisTimelineCutoff(redis.admin(), deadlineObservation.probeCutoff())); + var owner = + new CanonicalGameplayRegionLeaseOwner( + inventory, + statusRepository, + redisOwner, + incarnationSource, + world.resolver(), + runtimeIdentity("definitive-expiry-after-claim"), + Duration.ofSeconds(30), + deadlineObservation.clock(Clock.systemUTC()), + true); + // A separate autocommit data source read at actual command dispatch proves the SQL + // claim was visible outside its transaction. The earlier Redis PROBE sees PREPARED. + var initialize = new AtomicReference>(); + var completed = new CompletableFuture(); + var observedOwnerCommand = + new CommandListener() { + @Override + public void commandStarted(CommandStartedEvent event) { + if (event.getCommand().getType() != CommandType.EVALSHA) return; + String phase = + testSchema + .dsl() + .fetchSingle( + "SELECT phase FROM game_session_region_timeline_preparation" + + " WHERE initialization_operation_id = ?", + preparation.operationId()) + .get(0, String.class); + if ("INITIALIZING".equals(phase)) { + assertThat(initialize.compareAndSet(null, event.getCommand())).isTrue(); + } else { + assertThat(phase).isEqualTo("PREPARED"); + } + } + + @Override + public void commandSucceeded(CommandSucceededEvent event) { + if (event.getCommand() != initialize.get()) return; + completed.complete(event.getCommand().getOutput().get()); + } + }; + redis.ownerClient().addListener(observedOwnerCommand); + try (deadlineObservation) { + var failedInstall = + catchThrowable(() -> owner.installForTransition(TRANSITION_ID, world.request())); + assertThat(failedInstall).isInstanceOf(IllegalStateException.class); + assertThat(initialize.get()) + .as("INITIALIZE after the committed SQL claim; install refusal: %s", failedInstall) + .isNotNull(); + assertThat(timelineCommandCutoff(initialize.get())) + .isEqualTo(deadlineObservation.probeCutoff()); + assertThat(completed.get(2, TimeUnit.SECONDS)) + .as("physical Redis deadline refusal after dispatch, not local pre-dispatch expiry") + .isEqualTo(-3L); + } finally { + redis.ownerClient().removeListener(observedOwnerCommand); + } + world.setAfterRead(2, () -> {}); + // A definitive -3 after the single-use claim still leaves the scope held. + assertHeldWithoutRedisWrites(testSchema.dsl(), statusRepository, redis, source, preparation); + assertThatThrownBy(() -> owner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertHeldWithoutRedisWrites(testSchema.dsl(), statusRepository, redis, source, preparation); + } finally { + dropSchema(testSchema.schema()); + } + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.EnumSource( + value = CommandType.class, + names = {"SET", "TIME"}) + void installationHoldsTheClaimAfterAPostClaimPermissionRefusal(CommandType commandPermission) + throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema schema = newTestSchema(); + try (RedisFixture redis = RedisFixture.open(); + var pool = newCompositionPool(schema)) { + var repository = + new CanonicalGameplayRegionRuntimeStatusRepository(DSL.using(pool, SQLDialect.POSTGRES)); + var redisOwner = redis.owner(); + var world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var evidence = provisionalEvidence(world.request()); + var inventory = mock(CanonicalGameplayBindingInventoryRepository.class); + when(inventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(evidence); + when(inventory.forBudget(org.mockito.ArgumentMatchers.any())).thenReturn(inventory); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + prepareTimeline(repository, redisOwner, world, evidence, source, incarnation); + var owner = + new CanonicalGameplayRegionLeaseOwner( + inventory, + repository, + redisOwner, + incarnationSource, + world.resolver(), + runtimeIdentity("acl-change"), + Duration.ofSeconds(30), + Clock.systemUTC(), + true); + var probe = new CompletableFuture(); + var initialize = new CompletableFuture(); + var refusedClaim = new AtomicReference(); + var permissionChange = + new CommandListener() { + @Override + public void commandStarted(CommandStartedEvent event) { + var command = event.getCommand(); + if (command.getType() == CommandType.EVALSHA + && command.getArgs().toCommandString().contains("value") + && refusedClaim.get() == null) { + // A separate autocommit connection can see the claim only after SQL commits. + refusedClaim.set(initializationClaim(schema.dsl(), preparation.operationId())); + redis.setOwnerCommandAllowed(commandPermission, false); + } + } + + @Override + public void commandSucceeded(CommandSucceededEvent event) { + var command = event.getCommand(); + if (command.getType() != CommandType.EVALSHA) return; + String arguments = command.getArgs().toCommandString(); + if (arguments.contains("value")) probe.complete(command.getOutput().get()); + if (arguments.contains("value")) { + initialize.complete(command.getOutput().get()); + } + } + }; + redis.ownerClient().addListener(permissionChange); + try { + assertThatThrownBy(() -> owner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(probe.get(2, TimeUnit.SECONDS)).isEqualTo(1L); + assertThat(refusedClaim.get()).isNotNull(); + assertThat(initialize.get(2, TimeUnit.SECONDS)).isEqualTo(-4L); + // Permissions are checked before either write, and the consumed claim stays held. + assertHeldWithoutRedisWrites(schema.dsl(), repository, redis, source, preparation); + } finally { + redis.ownerClient().removeListener(permissionChange); + redis.setOwnerCommandAllowed(commandPermission, true); + } + + assertThatThrownBy(() -> owner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertHeldWithoutRedisWrites(schema.dsl(), repository, redis, source, preparation); + assertThat(initializationClaim(schema.dsl(), preparation.operationId())) + .isEqualTo(refusedClaim.get()); + } finally { + dropSchema(schema.schema()); + } + } + + private static CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation prepareTimeline( + CanonicalGameplayRegionRuntimeStatusRepository repository, + CanonicalGameplayRegionLeaseRedisOwner redisOwner, + WorldFixture world, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation) { + return repository.prepareInitialTimeline( + evidence, + world.request(), + world.resolver().resolve(world.request()), + source, + incarnation, + redisOwner.requireTimelineAbsent(source, incarnation), + NOW); + } + + private static UUID initializationClaim(DSLContext dsl, UUID operationId) { + return dsl.fetchSingle( + "SELECT initialization_claim_generation FROM game_session_region_timeline_preparation" + + " WHERE initialization_operation_id = ?", + operationId) + .get(0, UUID.class); + } + + private static long timelineCommandCutoff(RedisCommand command) { + String arguments = command.getArgs().toCommandString(); + String lastArgument = arguments.substring(arguments.lastIndexOf(' ') + 1); + assertThat(lastArgument).matches("value<[0-9]+>"); + return Long.parseLong(lastArgument.substring("value<".length(), lastArgument.length() - 1)); + } + + private static final class PreparedTimelineDeadlineObservation + implements CommandListener, AutoCloseable { + private final RedisClient client; + private final boolean shortenRedisBudget; + private final ThreadLocal timeSubmitted = new ThreadLocal<>(); + private final AtomicReference localBudgetStart = new AtomicReference<>(); + private final java.util.concurrent.atomic.AtomicLong probeCutoff = + new java.util.concurrent.atomic.AtomicLong(); + + private PreparedTimelineDeadlineObservation(RedisClient client, boolean shortenRedisBudget) { + this.client = client; + this.shortenRedisBudget = shortenRedisBudget; + client.addListener(this); + } + + @Override + public void commandStarted(CommandStartedEvent event) { + var command = event.getCommand(); + if (shortenRedisBudget && command.getType() == CommandType.TIME && probeCutoff() == 0) { + timeSubmitted.set(true); + } else if (command.getType() == CommandType.EVALSHA + && command.getArgs().toCommandString().contains("value")) { + timeSubmitted.remove(); + probeCutoff.compareAndSet(0, timelineCommandCutoff(command)); + } + } + + long probeCutoff() { + return probeCutoff.get(); + } + + Clock clock(Clock delegate) { + return new Clock() { + @Override + public java.time.ZoneId getZone() { + return delegate.getZone(); + } + + @Override + public Clock withZone(java.time.ZoneId zone) { + return PreparedTimelineDeadlineObservation.this.clock(delegate.withZone(zone)); + } + + @Override + public Instant instant() { + Instant now = delegate.instant(); + localBudgetStart.compareAndSet(null, now); + // During conversion only, model a tighter local wall-clock budget. The unchanged + // monotonic deadline leaves time to claim, wait for Redis, and observe a real -3. + if (Boolean.TRUE.equals(timeSubmitted.get())) { + long elapsed = + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_OPERATION_MILLIS - 1_500L; + Instant later = localBudgetStart.get().plusMillis(elapsed); + if (later.isAfter(now)) return later; + } + return now; + } + }; + } + + @Override + public void close() { + client.removeListener(this); + } + } + + 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(); + return Long.parseLong(new String(time.get(0), StandardCharsets.US_ASCII)) * 1_000L + + Long.parseLong(new String(time.get(1), StandardCharsets.US_ASCII)) / 1_000L; + } + + @Test + void freshDeadlineDoesNotReplaceExpiredOriginalGrantFromRetainedMetadata() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try (RedisFixture redis = RedisFixture.open()) { + var repository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var redisOwner = redis.owner(); + WorldFixture world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + prepareTimeline( + repository, + redisOwner, + world, + provisionalEvidence(world.request()), + source, + incarnation); + assertThat(repository.beginInitialTimeline(preparation, NOW)).isPresent(); + assertThat(repository.beginInitialTimeline(preparation, NOW)).isEmpty(); + + byte[] metaKey = + ascii( + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())); + byte[] leaseKey = + ascii( + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId())); + // Represent a retained epoch-one baseline after its lease is no longer present. + redis.admin().hset(metaKey, ascii("region_epoch"), ascii("1")); + redis.admin().hset(metaKey, ascii("current_tick_id"), ascii("-1")); + redis.admin().hset(metaKey, ascii("current_tick_state"), ascii("APPLIED")); + redis + .admin() + .hset( + metaKey, + ascii("first_timeline_operation_id"), + ascii(preparation.operationId().toString())); + redis + .admin() + .hset(metaKey, ascii("first_timeline_source_digest"), ascii(preparation.sourceDigest())); + assertThat(redis.admin().type(leaseKey)).isEqualTo("none"); + long redisBefore = redisTimeMillis(redis.admin()); + // A fresh, bounded operation still cannot replace an expired original grant. + var initializationNow = Instant.ofEpochMilli(redisBefore).plusSeconds(60); + var initializationClock = Clock.fixed(initializationNow, ZoneOffset.UTC); + var deadline = initializationNow.toEpochMilli() + 10_000L; + byte[] originalMetadata = redis.admin().dump(metaKey); + assertThat(redis.admin().pttl(metaKey)).isEqualTo(-1L); + assertThatThrownBy(() -> + initializeTimelineWithoutCreationPermission( + redisOwner.forHandoffDeadline(initializationClock, deadline), + preparation, + "replacement")) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().type(leaseKey)).isEqualTo("none"); + assertThat(redis.admin().dump(metaKey)).containsExactly(originalMetadata); + assertThat(redis.admin().pttl(metaKey)).isEqualTo(-1L); + assertThat(repository.findTimelinePreparation(source).orElseThrow().phase()) + .isEqualTo( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INITIALIZING); + assertThat(repository.beginInitialTimeline(preparation, NOW)).isEmpty(); + } finally { + dropSchema(testSchema.schema()); } } @@ -453,8 +1096,7 @@ void timelinePreflightFailuresLeavePreparedPermissionAndAllowLaterFirstClaim() t TestSchema testSchema = newTestSchema(); try (RedisFixture redis = RedisFixture.open()) { var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); - var validRedisOwner = - new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var validRedisOwner = redis.owner(); WorldFixture world = WorldFixture.open(); var incarnationSource = new ControlledStableIncarnationSource(); var bindingEvidence = provisionalEvidence(world.request()); @@ -465,23 +1107,83 @@ void timelinePreflightFailuresLeavePreparedPermissionAndAllowLaterFirstClaim() t incarnationSource.readCurrent( CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); var preparation = - statusRepository.prepareInitialTimeline( - bindingEvidence, - world.request(), - world.resolver().resolve(world.request()), - source, - incarnation, - validRedisOwner.requireTimelineAbsent(source, incarnation), - NOW); + prepareTimeline( + statusRepository, validRedisOwner, world, bindingEvidence, source, incarnation); assertPreparedTimelineUnchanged( testSchema.dsl(), statusRepository, redis, source, preparation); + var deadlineBoundRedisOwner = + validRedisOwner.forHandoffDeadline( + Clock.systemUTC(), System.currentTimeMillis() + 10_000L); + redis.setOwnerTimeAllowed(false); + try { + assertThatThrownBy(() -> + deadlineBoundRedisOwner.prepareTimelineInitialization( + preparation, + Duration.ofSeconds(30), + runtimeIdentity("time-denied-during-probe"))) + .isInstanceOf(IllegalStateException.class) + .hasStackTraceContaining("NOPERM") + .hasStackTraceContaining("time"); + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + } finally { + redis.setOwnerTimeAllowed(true); + } + try (CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization session = + deadlineBoundRedisOwner.prepareTimelineInitialization( + preparation, + Duration.ofSeconds(30), + runtimeIdentity("time-granted-after-probe-refusal"))) { + assertThat(session).isNotNull(); + } + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + + for (CommandType write : List.of(CommandType.HSET, CommandType.SET)) { + var probeResult = new CompletableFuture(); + var probeObserver = + new CommandListener() { + @Override + public void commandSucceeded(CommandSucceededEvent event) { + var command = event.getCommand(); + if (command.getType() == CommandType.EVALSHA + && command.getArgs().toCommandString().contains("value")) { + probeResult.complete(command.getOutput().get()); + } + } + }; + var caseOwner = + validRedisOwner.forHandoffDeadline( + Clock.systemUTC(), System.currentTimeMillis() + 10_000L); + redis.setOwnerCommandAllowed(write, false); + redis.ownerClient().addListener(probeObserver); + try { + assertThatThrownBy(() -> + caseOwner.prepareTimelineInitialization( + preparation, + Duration.ofSeconds(30), + runtimeIdentity("write-denied-during-probe"))) + .isInstanceOf(IllegalStateException.class); + assertThat(probeResult.get(2, TimeUnit.SECONDS)) + .as("ACL refusal for %s", write) + .isEqualTo(-4L); + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + } finally { + redis.ownerClient().removeListener(probeObserver); + redis.setOwnerCommandAllowed(write, true); + } + } + var missingDescriptorOwner = owner( bindingInventory, statusRepository, new CanonicalGameplayRegionLeaseRedisOwner( - redis.ownerClient(), RedisScriptCatalog.fromContributions(List.of())), + redis.ownerClient(), + RedisFixture.clientUri(PRINCIPAL, PASSWORD), + RedisScriptCatalog.fromContributions(List.of())), world, "missing-descriptor", incarnationSource); @@ -491,16 +1193,17 @@ void timelinePreflightFailuresLeavePreparedPermissionAndAllowLaterFirstClaim() t assertPreparedTimelineUnchanged( testSchema.dsl(), statusRepository, redis, source, preparation); - RedisClient unavailableClient = - RedisClient.create( - RedisURI.Builder.redis("127.0.0.1", 1).withTimeout(Duration.ofMillis(250)).build()); + var unavailableUri = + RedisURI.Builder.redis("127.0.0.1", 1).withTimeout(Duration.ofMillis(250)).build(); + RedisClient unavailableClient = RedisClient.create(unavailableUri); unavailableClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); try { var connectionFailureOwner = owner( bindingInventory, statusRepository, - new CanonicalGameplayRegionLeaseRedisOwner(unavailableClient, redis.catalog()), + new CanonicalGameplayRegionLeaseRedisOwner( + unavailableClient, unavailableUri, redis.catalog()), world, "connection-refused", incarnationSource); @@ -513,13 +1216,18 @@ void timelinePreflightFailuresLeavePreparedPermissionAndAllowLaterFirstClaim() t assertPreparedTimelineUnchanged( testSchema.dsl(), statusRepository, redis, source, preparation); + String wrongPrincipal = "gamesession_coord_wrong"; + String wrongPassword = UUID.randomUUID().toString(); RedisClient wrongPrincipalClient = - redis.additionalClient("gamesession_coord_wrong", UUID.randomUUID().toString(), true); + redis.additionalClient(wrongPrincipal, wrongPassword, true); var principalFailureOwner = owner( bindingInventory, statusRepository, - new CanonicalGameplayRegionLeaseRedisOwner(wrongPrincipalClient, redis.catalog()), + new CanonicalGameplayRegionLeaseRedisOwner( + wrongPrincipalClient, + RedisFixture.clientUri(wrongPrincipal, wrongPassword), + redis.catalog()), world, "wrong-principal", incarnationSource); @@ -599,8 +1307,7 @@ void initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry TestSchema testSchema = newTestSchema(); try (RedisFixture redis = RedisFixture.open()) { var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); - var redisOwner = - new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var redisOwner = redis.owner(); // World, provisional binding and stable-incarnation authority are controlled inputs; // PostgreSQL preparation, the Redis absence probe and subsequent region owner are actual. WorldFixture world = WorldFixture.open(); @@ -625,14 +1332,8 @@ void initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry qualifiedSource.gameInstanceId(), qualifiedSource.regionId())); var preparation = - statusRepository.prepareInitialTimeline( - bindingEvidence, - world.request(), - world.resolver().resolve(world.request()), - qualifiedSource, - incarnation, - redisOwner.requireTimelineAbsent(qualifiedSource, incarnation), - NOW); + prepareTimeline( + statusRepository, redisOwner, world, bindingEvidence, qualifiedSource, incarnation); assertThat(preparation.phase()) .isEqualTo( CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.PREPARED); @@ -649,7 +1350,7 @@ void initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry + " FROM game_session_region_timeline_preparation WHERE transition_id = ?", TRANSITION_ID) .get(0, UUID.class)) - .isEqualTo(permit.claimGeneration()); + .isEqualTo(permit.generation()); var initializing = statusRepository.findTimelinePreparation(qualifiedSource).orElseThrow(); assertThat(initializing.phase()) .isEqualTo( @@ -687,7 +1388,8 @@ void initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry testSchema .dsl() .fetch( - "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", + "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id" + + " = ?", TRANSITION_ID) .formatJSON()) .isEqualTo(retainedSqlImage); @@ -701,7 +1403,8 @@ void initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry void bridgeSqlPhasesWaitForRuntimeBeforeLockingTransition() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); TestSchema schema = newTestSchema(); - try { + try (var compositionPool = newCompositionPool(schema)) { + var compositionDsl = DSL.using(compositionPool, SQLDialect.POSTGRES); try (RedisFixture redis = RedisFixture.open()) { redis.admin().flushdb(); } @@ -716,7 +1419,7 @@ void bridgeSqlPhasesWaitForRuntimeBeforeLockingTransition() throws Exception { try (var entity = EntityReferenceFixture.open()) { var proof = CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeWithSqlPhaseRunner( - schema.dsl(), + compositionDsl, REDIS.getHost(), REDIS.getMappedPort(REDIS_PORT), world.request(), @@ -805,7 +1508,8 @@ void accountMemberAcknowledgementAfterRegionBridgePreservesOriginalBridgeEvidenc throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); TestSchema testSchema = newTestSchema(); - try { + try (var compositionPool = newCompositionPool(testSchema)) { + var compositionDsl = DSL.using(compositionPool, SQLDialect.POSTGRES); // The shared test Redis container may have state from the sibling owner test. try (RedisFixture redis = RedisFixture.open()) { redis.admin().flushdb(); @@ -821,7 +1525,7 @@ void accountMemberAcknowledgementAfterRegionBridgePreservesOriginalBridgeEvidenc try (var entitySource = EntityReferenceFixture.open()) { CanonicalGameplayRegionOwnerCompositionFixture.MemberRepairProof proof = CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeThenRepairAccountMember( - testSchema.dsl(), + compositionDsl, REDIS.getHost(), REDIS.getMappedPort(REDIS_PORT), world.request(), @@ -853,7 +1557,7 @@ void accountMemberAcknowledgementAfterRegionBridgePreservesOriginalBridgeEvidenc void acknowledgedRegionBridgeSurvivesRefusedExpiredGrantReplacement() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); TestSchema testSchema = newTestSchema(); - try { + try (var compositionPool = newCompositionPool(testSchema)) { try (RedisFixture redis = RedisFixture.open()) { redis.admin().flushdb(); } @@ -867,7 +1571,7 @@ void acknowledgedRegionBridgeSurvivesRefusedExpiredGrantReplacement() throws Exc CanonicalGameplayRegionOwnerCompositionFixture.ExpiredGrantProof proof = CanonicalGameplayRegionOwnerCompositionFixture .installAndBridgeThenExpiredGrantReplacementRefuses( - testSchema.dsl(), + DSL.using(compositionPool, SQLDialect.POSTGRES), REDIS.getHost(), REDIS.getMappedPort(REDIS_PORT), world.request(), @@ -877,9 +1581,6 @@ void acknowledgedRegionBridgeSurvivesRefusedExpiredGrantReplacement() throws Exc assertThat(proof.acknowledgedBridge().exactLostReplyRetry()).isTrue(); assertThat(proof.replacementRefused()).isTrue(); - assertThat(proof.refusalMessage()) - .isEqualTo( - "Canonical Game Session region owner requires current exact assignment and lease evidence"); assertThat(proof.ownerSqlStatePreserved()).isTrue(); assertThat(proof.acknowledgementRowPreserved()).isTrue(); assertThat(proof.inventoryStatePreserved()).isTrue(); @@ -926,7 +1627,8 @@ private static void assertRetainedParentRegionBridgeUpgrade(boolean incompatible schema .dsl() .fetchSingle( - "SELECT * FROM game_session_canonical_binding_region_bridge_obligation WHERE transition_id = ?", + "SELECT * FROM game_session_canonical_binding_region_bridge_obligation WHERE" + + " transition_id = ?", transitionId); assertThat(bridge.get("bridge_operation_id", UUID.class)).isNotNull(); assertThat(bridge.get("status", String.class)).isEqualTo("REQUIRED"); @@ -935,7 +1637,8 @@ private static void assertRetainedParentRegionBridgeUpgrade(boolean incompatible schema .dsl() .fetchSingle( - "SELECT phase FROM game_session_region_timeline_preparation WHERE transition_id = ?", + "SELECT phase FROM game_session_region_timeline_preparation WHERE" + + " transition_id = ?", transitionId) .get(0, String.class)) .isEqualTo("INSTALLED"); @@ -945,7 +1648,8 @@ private static void assertRetainedParentRegionBridgeUpgrade(boolean incompatible schema .dsl() .execute( - "UPDATE game_session_region_timeline_preparation SET assignment_uuid = ? WHERE transition_id = ?", + "UPDATE game_session_region_timeline_preparation SET assignment_uuid = ?" + + " WHERE transition_id = ?", UUID.randomUUID(), transitionId)) .isOne(); @@ -968,18 +1672,20 @@ private static void assertRetainedParentRegionBridgeUpgrade(boolean incompatible schema .dsl() .fetchSingle( - "SELECT count(*) FROM information_schema.columns WHERE table_schema = current_schema()" - + " AND table_name IN ('game_session_region_timeline_preparation'," - + " 'game_session_canonical_binding_region_bridge_obligation')" - + " AND column_name = 'entity_created_origin'") + "SELECT count(*) FROM information_schema.columns WHERE table_schema =" + + " current_schema() AND table_name IN" + + " ('game_session_region_timeline_preparation'," + + " 'game_session_canonical_binding_region_bridge_obligation') AND" + + " column_name = 'entity_created_origin'") .get(0, Integer.class)) .isZero(); assertThat( schema .dsl() .fetchSingle( - "SELECT count(*) FROM pg_proc WHERE pronamespace = current_schema()::regnamespace" - + " AND proname = 'gs_region_bridge_original_preparation_matches'") + "SELECT count(*) FROM pg_proc WHERE pronamespace =" + + " current_schema()::regnamespace AND proname =" + + " 'gs_region_bridge_original_preparation_matches'") .get(0, Integer.class)) .isZero(); } else { @@ -1086,7 +1792,8 @@ void createdOriginNativeBridgeRetainsOriginalPurposeAndRejectsSourceSubstitution throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); TestSchema testSchema = newTestSchema(); - try { + try (var compositionPool = newCompositionPool(testSchema)) { + var compositionDsl = DSL.using(compositionPool, SQLDialect.POSTGRES); try (RedisFixture redis = RedisFixture.open()) { redis.admin().flushdb(); } @@ -1124,7 +1831,7 @@ void createdOriginNativeBridgeRetainsOriginalPurposeAndRejectsSourceSubstitution var created = CreatedEntityReferenceFixture.open(request)) { var proof = CanonicalGameplayRegionOwnerCompositionFixture.installCreatedAndBridgeThenCheckSources( - testSchema.dsl(), + compositionDsl, REDIS.getHost(), REDIS.getMappedPort(REDIS_PORT), request, @@ -1137,14 +1844,16 @@ void createdOriginNativeBridgeRetainsOriginalPurposeAndRejectsSourceSubstitution testSchema .dsl() .fetchSingle( - "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", + "SELECT * FROM game_session_region_timeline_preparation WHERE" + + " transition_id = ?", binding.acknowledgement().obligation().transitionId()); var obligation = testSchema .dsl() .fetchSingle( - "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" - + " WHERE transition_id = ?", + "SELECT * FROM" + + " game_session_canonical_binding_region_bridge_obligation WHERE" + + " transition_id = ?", binding.acknowledgement().obligation().transitionId()); for (Record row : List.of(preparation, obligation)) { assertThat(row.get("assignment_uuid")).isNull(); @@ -1236,11 +1945,14 @@ void createdOriginNativeBridgeRetainsOriginalPurposeAndRejectsSourceSubstitution } } - @Test - void laterPlacementReusesCurrentGrantAndPreservesInitialTimelineProvenance() throws Exception { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void laterPlacementReusesCurrentGrantAndPreservesInitialTimelineProvenance( + boolean expireBeforeBridge) throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); TestSchema schema = newTestSchema(); - try { + try (var compositionPool = newCompositionPool(schema)) { + var compositionDsl = DSL.using(compositionPool, SQLDialect.POSTGRES); try (RedisFixture redis = RedisFixture.open()) { redis.admin().flushdb(); } @@ -1292,7 +2004,7 @@ void laterPlacementReusesCurrentGrantAndPreservesInitialTimelineProvenance() thr try (var entity = EntityReferenceFixture.open(secondRequest.getCharacterUuid())) { var result = CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeTwoCandidates( - schema.dsl(), + compositionDsl, REDIS.getHost(), REDIS.getMappedPort(REDIS_PORT), first.request(), @@ -1300,7 +2012,16 @@ void laterPlacementReusesCurrentGrantAndPreservesInitialTimelineProvenance() thr first.resolver(), entity.client(), new CanonicalGameplayRegionOwnerCompositionFixture.SecondBinding( - secondRequest, target.playableTarget(), entity.client())); + secondRequest, + target.playableTarget(), + first.resolver(), + entity.client(), + expireBeforeBridge)); + if (expireBeforeBridge) { + assertThat(result.expiredGrantRejectedWithoutStateChange()).isTrue(); + assertThat(result.second()).isNull(); + return; + } assertThat(result.firstTimelineProvenancePreserved()).isTrue(); assertThat(result.initialMetaUnchanged()).isTrue(); assertThat(result.first().exactLostReplyRetry()).isTrue(); @@ -1373,15 +2094,6 @@ private static ReadPreseededActorRuntimeReferenceResponse entityResponse( .build(); } - private static ControlledConnectionFailureDataSource dataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(POSTGRES.getDriverClassName()); - dataSource.setUrl(POSTGRES.getJdbcUrl()); - dataSource.setUsername(POSTGRES.getUsername()); - dataSource.setPassword(POSTGRES.getPassword()); - return new ControlledConnectionFailureDataSource(dataSource); - } - private static final class ControlledConnectionFailureDataSource extends DelegatingDataSource { private volatile boolean connectionsUnavailable; @@ -1414,6 +2126,14 @@ public Connection getConnection(String username, String password) throws SQLExce } } + private static HikariDataSource newCompositionPool(TestSchema schema) { + var pool = new HikariDataSource(); + pool.setDataSource(schema.dataSource()); + pool.setMaximumPoolSize(4); + pool.setMinimumIdle(0); + return pool; + } + private static TestSchema newTestSchema() { return newTestSchema(null); } @@ -1530,6 +2250,17 @@ synchronized void restoreRecoveryEvidence() { } } + private static RuntimeIdentity runtimeIdentity(String instanceId) { + return new RuntimeIdentity( + "game-session-service", + instanceId, + "localhost", + NOW, + "controlled-test", + "controlled-sha", + "controlled-image"); + } + private static CanonicalGameplayRegionLeaseOwner owner( CanonicalGameplayBindingInventoryRepository bindingInventory, CanonicalGameplayRegionRuntimeStatusRepository statusRepository, @@ -1543,14 +2274,7 @@ private static CanonicalGameplayRegionLeaseOwner owner( redisOwner, incarnationSource, world.resolver(), - new RuntimeIdentity( - "game-session-service", - instanceId, - "localhost", - NOW, - "controlled-test", - "controlled-sha", - "controlled-image"), + runtimeIdentity(instanceId), Duration.ofSeconds(30), Clock.fixed(NOW, ZoneOffset.UTC)); } @@ -1561,16 +2285,7 @@ private static void initializeTimelineWithoutCreationPermission( String instanceId) { try (CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization session = redisOwner.prepareTimelineInitialization( - preparation, - Duration.ofSeconds(30), - new RuntimeIdentity( - "game-session-service", - instanceId, - "localhost", - NOW, - "controlled-test", - "controlled-sha", - "controlled-image"))) { + preparation, Duration.ofSeconds(30), runtimeIdentity(instanceId))) { session.initialize(null); } } @@ -1788,6 +2503,31 @@ private static byte[] ascii(String value) { return value.getBytes(StandardCharsets.US_ASCII); } + private static void assertHeldWithoutRedisWrites( + DSLContext dsl, + CanonicalGameplayRegionRuntimeStatusRepository statusRepository, + RedisFixture redis, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation) { + assertThat(statusRepository.find(source)).isEmpty(); + var row = + dsl.fetchSingle( + "SELECT phase, initialization_claim_generation" + + " FROM game_session_region_timeline_preparation" + + " WHERE initialization_operation_id = ?", + preparation.operationId()); + assertThat(row.get("phase", String.class)).isEqualTo("INITIALIZING"); + assertThat(row.get("initialization_claim_generation", UUID.class)).isNotNull(); + for (String key : + List.of( + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId()), + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId()))) { + assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); + } + } + private static void assertPreparedTimelineUnchanged( DSLContext dsl, CanonicalGameplayRegionRuntimeStatusRepository statusRepository, @@ -1800,13 +2540,14 @@ private static void assertPreparedTimelineUnchanged( assertThat(observed.phase()) .isEqualTo( CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.PREPARED); - assertThat( - dsl.fetchSingle( - "SELECT phase FROM game_session_region_timeline_preparation" - + " WHERE initialization_operation_id = ?", - preparation.operationId()) - .get("phase", String.class)) - .isEqualTo("PREPARED"); + var row = + dsl.fetchSingle( + "SELECT phase, initialization_claim_generation" + + " FROM game_session_region_timeline_preparation" + + " WHERE initialization_operation_id = ?", + preparation.operationId()); + assertThat(row.get("phase", String.class)).isEqualTo("PREPARED"); + assertThat(row.get("initialization_claim_generation", UUID.class)).isNull(); assertThat( redis .admin() @@ -1836,6 +2577,7 @@ private static final class WorldFixture { private volatile WorldCanonicalInstanceLifecycleEvidence replacement; private volatile int callbackOnRead = -1; private volatile Runnable afterRead = () -> {}; + private final java.util.List observedDeadlines = new java.util.ArrayList<>(); private final CanonicalInitialPlayerLocationRegionResolver resolver; private WorldFixture(WorldCanonicalInstanceLifecycleEvidence original) { @@ -1859,7 +2601,23 @@ private WorldFixture( if (read == callbackOnRead) afterRead.run(); return response; }); + when(initialClient.readInitialPlayerLocationRegion( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) + .thenAnswer(invocation -> { + io.grpc.Deadline deadline = invocation.getArgument(1); + assertThat(deadline).isNotNull(); + observedDeadlines.add(deadline); + return initialClient.readInitialPlayerLocationRegion(invocation.getArgument(0)); + }); when(lifecycleClient.read(original.request())).thenAnswer(invocation -> current.get()); + when(lifecycleClient.read( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) + .thenAnswer(invocation -> { + io.grpc.Deadline deadline = invocation.getArgument(1); + assertThat(deadline).isNotNull(); + observedDeadlines.add(deadline); + return lifecycleClient.read(invocation.getArgument(0)); + }); this.resolver = new CanonicalInitialPlayerLocationRegionResolver( initialClient, new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); @@ -2116,13 +2874,22 @@ static RedisFixture open() { } private static RedisClient createClient(String username, String password) { + RedisClient client = RedisClient.create(clientUri(username, password)); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private static RedisURI clientUri(String username, String password) { RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(REDIS_PORT)) .withTimeout(Duration.ofSeconds(3)); if (username != null) builder.withAuthentication(username, password); - RedisClient client = RedisClient.create(builder.build()); - client.setOptions(ClientOptions.builder().autoReconnect(false).build()); - return client; + return builder.build(); + } + + CanonicalGameplayRegionLeaseRedisOwner owner() { + return new CanonicalGameplayRegionLeaseRedisOwner( + ownerClient, clientUri(PRINCIPAL, PASSWORD), catalog); } RedisClient ownerClient() { @@ -2148,29 +2915,23 @@ void setOwnerScriptLoadAllowed(boolean allowed) { admin.aclSetuser(PRINCIPAL, ownerArguments(PASSWORD, allowed)); } + void setOwnerTimeAllowed(boolean allowed) { + admin.aclSetuser( + PRINCIPAL, + CanonicalGameplayRegionOwnerCompositionFixture.regionOwnerPermissions( + PASSWORD, true, allowed)); + } + + void setOwnerCommandAllowed(CommandType command, boolean allowed) { + var args = new AclSetuserArgs(); + if (allowed) args.addCommand(command); + else args.removeCommand(command); + admin.aclSetuser(PRINCIPAL, args); + } + private static AclSetuserArgs ownerArguments(String password, boolean allowScriptLoad) { - AclSetuserArgs args = - new AclSetuserArgs() - .reset() - .on() - .addPassword(password) - .keyPattern("tick-executor-lease:*") - .keyPattern("tick:*") - .addCommand(CommandType.HELLO) - .addCommand(CommandType.PING) - .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) - .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) - .addCommand(CommandType.EVALSHA) - .addCommand(CommandType.TYPE) - .addCommand(CommandType.HGET) - .addCommand(CommandType.HSET) - .addCommand(CommandType.HLEN) - .addCommand(CommandType.PTTL) - .addCommand(CommandType.GET) - .addCommand(CommandType.SET) - .addCommand(CommandType.PEXPIRE); - if (allowScriptLoad) args.addCommand(CommandType.SCRIPT, CommandKeyword.LOAD); - return args; + return CanonicalGameplayRegionOwnerCompositionFixture.regionOwnerPermissions( + password, allowScriptLoad, true); } @Override diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java index 8a07423ff3..02e193a7d6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java @@ -12,16 +12,24 @@ import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.CommandType; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; import java.nio.charset.StandardCharsets; +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; 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.CanonicalGameplayRegionLeaseRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.testcontainers.containers.GenericContainer; import org.testcontainers.junit.jupiter.Container; @@ -38,10 +46,129 @@ class CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest { private static final GenericContainer REDIS = new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(PORT); + @Test + void expiredTimelineProbeAndInitializeRefuseBeforeAnyWrite() throws Exception { + try (RedisFixture redis = RedisFixture.open(); + var connection = redis.ownerClient().connect(ByteArrayCodec.INSTANCE); + var input = + getClass() + .getClassLoader() + .getResourceAsStream("redis/lua/game-session-region-timeline-initialize.lua")) { + var commands = connection.sync(); + String sha = commands.scriptLoad(input.readAllBytes()); + assertThat(commands.aclWhoami()).isEqualTo(PRINCIPAL); + String token = UUID.randomUUID().toString(); + String operationId = UUID.randomUUID().toString(); + String sourceDigest = "a".repeat(64); + for (boolean live : java.util.List.of(false, true)) { + String region = (live ? "d" : "c").repeat(32); + String tag = "r1-" + "a".repeat(32) + "-" + "b".repeat(32) + "-" + region; + byte[][] keys = { + ascii("tick-executor-lease:{" + tag + "}"), ascii("tick:{" + tag + "}:meta") + }; + assertThat(redis.admin().type(keys[0])).isEqualTo("none"); + assertThat(redis.admin().type(keys[1])).isEqualTo("none"); + var redisTime = commands.time(); + long nowMillis = + Long.parseLong(new String(redisTime.get(0), StandardCharsets.US_ASCII)) * 1_000L + + Long.parseLong(new String(redisTime.get(1), StandardCharsets.US_ASCII)) / 1_000L; + String deadline = live ? Long.toString(nowMillis + 30_000L) : "1"; + for (String action : java.util.List.of("PROBE", "INITIALIZE")) { + byte[][] args = { + ascii("gs_region_timeline_init/v2"), + ascii(action), + ascii(token), + ascii("1"), + ascii(operationId), + ascii(sourceDigest), + // Request a TTL longer than the remaining deadline so the cap is observable. + ascii("120000"), + ascii("1"), + ascii(deadline) + }; + Long outcome = + commands.evalsha(sha, io.lettuce.core.ScriptOutputType.INTEGER, keys, args); + assertThat(outcome).isEqualTo(live ? 1L : -3L); + if (live && "INITIALIZE".equals(action)) { + assertThat(redis.admin().get(keys[0])).containsExactly(ascii(token)); + assertThat(redis.admin().pttl(keys[0])).isPositive(); + assertThat(redis.admin().pexpiretime(keys[0])) + .isLessThanOrEqualTo(Long.parseLong(deadline)); + assertThat(redis.admin().hget(keys[1], ascii("first_timeline_operation_id"))) + .containsExactly(ascii(operationId)); + assertThat(redis.admin().hget(keys[1], ascii("first_timeline_source_digest"))) + .containsExactly(ascii(sourceDigest)); + assertThat(redis.admin().pttl(keys[1])).isEqualTo(-1L); + } else { + assertThat(redis.admin().type(keys[0])).isEqualTo("none"); + assertThat(redis.admin().type(keys[1])).isEqualTo("none"); + } + } + } + } + } + + @Test + void handoffBudgetClosesAConnectionWhoseRedisHandshakeNeverReplies() throws Exception { + try (var listener = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + listener.setSoTimeout(2_000); + var disconnected = new CompletableFuture(); + Thread.ofVirtual() + .start(() -> { + try (var socket = listener.accept()) { + socket.setSoTimeout(2_000); + var input = socket.getInputStream(); + boolean handshakeReceived = input.read() != -1; + while (input.read() != -1) { + // Read the handshake without answering it. + } + disconnected.complete(handshakeReceived); + } catch (IOException failure) { + disconnected.completeExceptionally(failure); + } + }); + var uri = + RedisURI.Builder.redis("127.0.0.1", listener.getLocalPort()) + .withTimeout(Duration.ofSeconds(10)) + .build(); + try (var client = RedisClient.create(uri)) { + var catalog = + RedisScriptCatalog.fromContributions( + java.util.List.of(new CanonicalGameplayRegionLeaseRedisScriptContribution())); + Clock clock = Clock.systemUTC(); + var acquisitionStarted = new CompletableFuture(); + var elapsedNanos = new java.util.concurrent.atomic.AtomicLong(); + var refusal = + CompletableFuture.runAsync(() -> { + var owner = + new CanonicalGameplayRegionLeaseRedisOwner(client, uri, catalog) + .forHandoffDeadline(clock, clock.millis() + 1_000L); + acquisitionStarted.complete(null); + long started = System.nanoTime(); + assertThatThrownBy(() -> + owner.acquire( + source(GAME_INSTANCE_ID_A), + 7L, + Duration.ofSeconds(30), + identity("stalled"))) + .isInstanceOf(IllegalStateException.class); + elapsedNanos.set(System.nanoTime() - started); + }); + acquisitionStarted.get(2, TimeUnit.SECONDS); + // The future timeout is only a watchdog; the bound is measured around acquire itself. + refusal.get(5, TimeUnit.SECONDS); + assertThat(elapsedNanos.get()).isLessThan(TimeUnit.MILLISECONDS.toNanos(1_500)); + assertThat(disconnected.get(2, TimeUnit.SECONDS)).isTrue(); + } + } + } + @Test void exactOpaqueLeaseGrantIsScopedRenewableAndFailsClosedAfterExpiry() { try (RedisFixture redis = RedisFixture.open()) { - var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var owner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.redisUri(PRINCIPAL, PASSWORD), redis.catalog()); RuntimeIdentity firstIdentity = identity("instance-a"); var firstSource = source(GAME_INSTANCE_ID_A); try { @@ -95,10 +222,86 @@ void exactOpaqueLeaseGrantIsScopedRenewableAndFailsClosedAfterExpiry() { } } + @ParameterizedTest + @ValueSource(ints = {-30, 30}) + void boundedAcquireAndRepeatedRenewalUseRedisTime(int applicationOffsetSeconds) { + try (RedisFixture redis = RedisFixture.open()) { + var owner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.redisUri(PRINCIPAL, PASSWORD), redis.catalog()); + var source = source(GAME_INSTANCE_ID_A); + seedMeta(redis.admin(), source); + byte[] leaseKey = + ascii( + CanonicalGameplayRegionRedisKeys.lease( + TENANT_ID, GAME_INSTANCE_ID_A, OPERATIONAL_REGION_ID)); + Clock applicationClock = + Clock.offset(Clock.systemUTC(), Duration.ofSeconds(applicationOffsetSeconds)); + long handoffMillis = 4_000; + var boundedOwner = + owner.forHandoffDeadline(applicationClock, applicationClock.millis() + handoffMillis); + + var grant = boundedOwner.acquire(source, 7L, Duration.ofSeconds(30), identity("bounded")); + long remainingLeaseMillis = redis.admin().pttl(leaseKey); + assertThat(remainingLeaseMillis).isPositive().isLessThanOrEqualTo(handoffMillis); + byte[] token = redis.admin().get(leaseKey); + assertThat(token).isNotNull(); + + boundedOwner.requireCurrent(grant); + boundedOwner.renew(grant, Duration.ofSeconds(30)); + assertThat(redis.admin().pttl(leaseKey)).isGreaterThan(handoffMillis); + boundedOwner.renew(grant, Duration.ofSeconds(60)); + assertThat(redis.admin().pttl(leaseKey)).isGreaterThan(30_000); + assertThat(redis.admin().get(leaseKey)).containsExactly(token); + } + } + + @Test + void redisRefusesLateRenewalWithoutChangingTheLiveLease() throws IOException { + try (RedisFixture redis = RedisFixture.open(); + var connection = redis.ownerClient().connect(ByteArrayCodec.INSTANCE); + var input = + getClass() + .getClassLoader() + .getResourceAsStream( + CanonicalGameplayRegionLeaseRedisScriptContribution.RENEW_PATH)) { + var source = source(GAME_INSTANCE_ID_A); + seedMeta(redis.admin(), source); + var owner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.redisUri(PRINCIPAL, PASSWORD), redis.catalog()); + var grant = owner.acquire(source, 7L, Duration.ofSeconds(30), identity("late-renewal")); + byte[] leaseKey = ascii(grant.key()); + byte[] token = redis.admin().get(leaseKey); + long expiry = redis.admin().pexpiretime(leaseKey); + assertThat(token).isNotNull(); + assertThat(redis.admin().pttl(leaseKey)).isPositive(); + + var commands = connection.sync(); + String sha = commands.scriptLoad(input.readAllBytes()); + byte[][] keys = { + leaseKey, + ascii( + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())) + }; + // A deadline at the start of the Unix epoch is already elapsed in Redis time. + byte[][] args = {ascii("gs_region_lease/v2"), token, ascii("7"), ascii("60000"), ascii("1")}; + Long result = commands.evalsha(sha, io.lettuce.core.ScriptOutputType.INTEGER, keys, args); + + assertThat(result).isZero(); + assertThat(redis.admin().get(leaseKey)).containsExactly(token); + assertThat(redis.admin().pexpiretime(leaseKey)).isEqualTo(expiry); + assertThat(redis.admin().pttl(leaseKey)).isPositive(); + } + } + @Test void acceptsTickZeroAndRejectsExpiringTimelineMetadata() { try (RedisFixture redis = RedisFixture.open()) { - var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var owner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.redisUri(PRINCIPAL, PASSWORD), redis.catalog()); var source = source(GAME_INSTANCE_ID_A); String metaKey = CanonicalGameplayRegionRedisKeys.meta( @@ -130,7 +333,9 @@ void acceptsTickZeroAndRejectsExpiringTimelineMetadata() { @Test void missingCurrentTickIdMakesLeaseAcquireReadAndRenewStaleWithoutChangingLeaseOrMeta() { try (RedisFixture redis = RedisFixture.open()) { - var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var owner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisFixture.redisUri(PRINCIPAL, PASSWORD), redis.catalog()); var source = source(GAME_INSTANCE_ID_A); seedMeta(redis.admin(), source); var grant = owner.acquire(source, 7L, Duration.ofSeconds(30), identity("missing-tick-id")); @@ -278,9 +483,11 @@ static RedisFixture open() { .addCommand(CommandType.EVALSHA) .addCommand(CommandType.TYPE) .addCommand(CommandType.HGET) + .addCommand(CommandType.HSET) .addCommand(CommandType.PTTL) .addCommand(CommandType.GET) .addCommand(CommandType.SET) + .addCommand(CommandType.TIME) .addCommand(CommandType.PEXPIRE)); RedisClient ownerClient = createClient(PRINCIPAL, PASSWORD); RedisScriptCatalog catalog = @@ -290,13 +497,17 @@ static RedisFixture open() { } private static RedisClient createClient(String username, String password) { + RedisClient client = RedisClient.create(redisUri(username, password)); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private static RedisURI redisUri(String username, String password) { RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(PORT)) .withTimeout(Duration.ofSeconds(3)); if (username != null) builder.withAuthentication(username, password); - RedisClient client = RedisClient.create(builder.build()); - client.setOptions(ClientOptions.builder().autoReconnect(false).build()); - return client; + return builder.build(); } private RedisClient ownerClient() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionContractTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionContractTest.java new file mode 100644 index 0000000000..c8da1b7ae4 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionContractTest.java @@ -0,0 +1,24 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayRegionOwnerCompositionContractTest { + @Test + void distinctResolversAreRejectedBeforeAnySourceOrStorageEffect() { + var first = mock(CanonicalInitialPlayerLocationRegionResolver.class); + var second = mock(CanonicalInitialPlayerLocationRegionResolver.class); + var secondBinding = + new CanonicalGameplayRegionOwnerCompositionFixture.SecondBinding(null, null, second, null); + assertThatThrownBy(() -> + CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeTwoCandidates( + null, null, 0, null, null, first, null, secondBinding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Both bindings require the same resolver routing their exact World requests"); + verifyNoInteractions(first, second); + } +} 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 abc3100350..3acf731ece 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 @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulRedisConnection; @@ -80,6 +81,7 @@ private CanonicalGameplayRegionOwnerCompositionFixture() {} static ExistingBinding installExistingOriginalCandidate( DSLContext dsl, RedisClient coordinationRedis, + RedisURI coordinationUri, UUID transitionId, CanonicalInitialPlayerLocationRequest worldRequest, CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, @@ -97,6 +99,7 @@ static ExistingBinding installExistingOriginalCandidate( CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( dsl, coordinationRedis, + coordinationUri, RedisScriptCatalog.fromContributions( List.of( new CanonicalGameplayRegionLeaseRedisScriptContribution(), @@ -205,16 +208,7 @@ static UUID installHistoricalMaterializedRequiredBridge( new CanonicalGameplayAdmissionDecision( transitionId, lease, identity, prepared.bindingGeneration(), null, currentTarget)); var evidence = inventory.readProvisionalCasEvidence(transitionId); - var reference = - entityReferenceClient.read( - ReadPreseededActorRuntimeReferenceRequest.newBuilder() - .setSchemaVersion(1) - .setAssignmentUuid(worldRequest.getAssignmentUuid()) - .setCanonicalAccountUuid(worldRequest.getCanonicalAccountUuid()) - .setExpectedTarget(worldRequest.getExpectedTarget()) - .setCharacterUuid(worldRequest.getCharacterUuid()) - .setIntentDigest(worldRequest.getAssignmentIntentDigest()) - .build()); + var reference = entityReferenceClient.read(preseededEntityRequest(worldRequest)); String parentEntityReferenceDigest = historicalParentEntityReferenceDigest(reference); // Compare current compatibility separately; historical storage always uses the frozen value. if (!parentEntityReferenceDigest.equals( @@ -898,9 +892,9 @@ && new BigInteger( } /** - * Runs the real first owner chain, then exercises a second candidate under its private grant. - * Same-grant reuse is limited to the initial timeline: the region has committed no tick, and a - * progressed region (tick past -1) is refused by design. + * Runs both candidates through one owner and its retained private grant. Both bindings must use + * the same resolver instance, configured to route each exact request (including deadline-aware + * reads). A separate preliminary resolution is not proof that the retained owner can resolve it. */ public static TwoBindingProof installAndBridgeTwoCandidates( DSLContext dsl, @@ -912,6 +906,12 @@ public static TwoBindingProof installAndBridgeTwoCandidates( CanonicalPreseededActorRuntimeReferenceClient firstEntityReferenceClient, SecondBinding secondBinding) throws Exception { + java.util.Objects.requireNonNull(firstWorldRegionResolver, "firstWorldRegionResolver"); + java.util.Objects.requireNonNull(secondBinding, "secondBinding"); + if (firstWorldRegionResolver != secondBinding.worldRegionResolver()) { + throw new IllegalArgumentException( + "Both bindings require the same resolver routing their exact World requests"); + } return installAndBridgeInternal( dsl, redisHost, @@ -1058,6 +1058,7 @@ private static TwoBindingProof installAndBridgeInternal( CanonicalGameplayRegionLeaseOwnerFactory.compose( dsl, redis.ownerClient(), + redis.ownerUri, scriptCatalog, stableSource, worldRegionResolver, @@ -1216,6 +1217,69 @@ private static TwoBindingProof installAndBridgeInternal( var secondInstallation = bridgeOwner.installForTransition( installation, secondTransitionId, secondBinding.worldRequest()); + if (secondBinding.expireBeforeBridge()) { + var reference = + secondBinding + .entityReferenceClient() + .read(preseededEntityRequest(secondBinding.worldRequest())); + var secondBindingKey = + ascii( + CanonicalGameplayRegionRedisKeys.sessionBinding( + secondIdentity.tenantId(), + secondIdentity.gameInstanceId(), + secondIdentity.regionId(), + reference.runtimeEntityId().value())); + if (!redis.admin().pexpire(redisKey, 0L)) { + throw new IllegalStateException("Fixture requires a live reused region grant to expire"); + } + Supplier>> readSql = + () -> + snapshotBridgeSqlState( + dsl, + identity.tenantId(), + identity.gameInstanceId(), + identity.regionId(), + secondTransitionId); + Supplier readTimeline = + () -> snapshotRegionRedisState(redis, redisKey, initialMetaKey); + var sqlBefore = readSql.get(); + var timelineBefore = readTimeline.get(); + byte[] firstBindingKey = + ascii( + CanonicalGameplayRegionRedisKeys.sessionBinding( + identity.tenantId(), + identity.gameInstanceId(), + identity.regionId(), + firstProof.runtimeEntityId())); + byte[] firstBindingBefore = redis.admin().dump(firstBindingKey); + long firstBindingExpiryBefore = redis.admin().pexpiretime(firstBindingKey); + if (timelineBefore.metadataTtlMillis() != -1L + || firstBindingBefore == null + || redis.admin().dump(secondBindingKey) != null) { + throw new IllegalStateException( + "Fixture requires persistent timeline metadata, the first actor's binding and an" + + " unbridged second binding"); + } + Runnable requireUnchangedState = + () -> { + if (!sqlBefore.equals(readSql.get()) + || !timelineBefore.equals(readTimeline.get()) + || !Arrays.equals(firstBindingBefore, redis.admin().dump(firstBindingKey)) + || firstBindingExpiryBefore != redis.admin().pexpiretime(firstBindingKey) + || redis.admin().dump(secondBindingKey) != null) { + throw new IllegalStateException("Expired grant refusal changed SQL or Redis"); + } + }; + requireExpiredGrantRefusal(() -> bridgeOwner.bridge(secondInstallation), "renew"); + requireUnchangedState.run(); + requireExpiredGrantRefusal( + () -> + bridgeOwner.installForTransition( + installation, secondTransitionId, secondBinding.worldRequest()), + "requireCurrent"); + requireUnchangedState.run(); + return new TwoBindingProof(firstProof, null, firstAbort, false, false, false, false, true); + } var secondAcknowledgement = bridgeOwner.bridge(secondInstallation).obligation(); var secondLostReplyRetry = bridgeOwner.bridge(secondInstallation).obligation(); requireMaterializedBridgeCaptured(dsl, secondTransitionId); @@ -1259,14 +1323,10 @@ private static TwoBindingProof installAndBridgeInternal( byte[] secondMetaTickState = redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_state")); Objects.requireNonNull(firstTimelineAfter, "retained timeline source row"); - // Reinstallation refreshes only the current grant and update timestamp. Compare every - // other column, including the first actor/origin, source, phase and initial Redis digest. - Set refreshedPreparationColumns = - Set.of("executor_fence", "lease_token_correlation", "updated_at"); - List changedImmutableColumns = + // Same-grant reuse must preserve the complete row, including its update timestamp. + List changedPreparationColumns = Arrays.stream(firstTimelineBefore.fields()) .map(field -> field.getName()) - .filter(column -> !refreshedPreparationColumns.contains(column)) .filter(column -> !Objects.deepEquals( firstTimelineBefore.get(column), firstTimelineAfter.get(column))) @@ -1279,7 +1339,7 @@ private static TwoBindingProof installAndBridgeInternal( firstTimelineAfter.get("lease_token_correlation", String.class), secondStatus.leaseTokenCorrelation()); boolean unchangedTimeline = - changedImmutableColumns.isEmpty() + changedPreparationColumns.isEmpty() && firstTimelineOperationId.equals( Objects.requireNonNull( firstTimelineAfter.get("initialization_operation_id", UUID.class), @@ -1308,8 +1368,8 @@ private static TwoBindingProof installAndBridgeInternal( || redis.admin().pttl(ascii(initialMetaKey)) != -1L) { throw new IllegalStateException( "Second binding changed first timeline provenance or lost the live region grant; " - + "changed immutable preparation columns=" - + changedImmutableColumns + + "changed preparation columns=" + + changedPreparationColumns + ", preparation grant matches current=" + preparationGrantMatchesCurrent); } @@ -1323,6 +1383,7 @@ private static TwoBindingProof installAndBridgeInternal( CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( dsl, redis.ownerClient(), + redis.ownerUri, scriptCatalog, stableSource, worldRegionResolver, @@ -1465,6 +1526,7 @@ private static ExpiredGrantProof refuseReplacementAfterAcknowledgement( CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( dsl, redis.ownerClient(), + redis.ownerUri, scriptCatalog, stableSource, worldRegionResolver, @@ -2012,6 +2074,22 @@ private static List> snapshotRegionOwnerSqlState( gameInstanceId, regionId) .getValues("image", String.class), + dsl.fetch( + "SELECT (to_jsonb(inventory) || jsonb_build_object('xmin', inventory.xmin::text))::text" + + " AS image" + + " FROM game_session_canonical_gameplay_binding_inventory inventory" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " ORDER BY binding_ref", + tenantId, + gameInstanceId, + regionId) + .getValues("image", String.class), + dsl.fetch( + "SELECT (to_jsonb(clock) || jsonb_build_object('xmin', clock.xmin::text))::text" + + " AS image" + + " FROM game_session_canonical_binding_inventory_clock clock" + + " ORDER BY singleton_id") + .getValues("image", String.class), // nextval is not rolled back, so a refused replacement must not consume a fence either. dsl.fetch( "SELECT last_value::text || ':' || is_called AS image" @@ -2019,6 +2097,39 @@ private static List> snapshotRegionOwnerSqlState( .getValues("image", String.class)); } + private static List> snapshotBridgeSqlState( + DSLContext dsl, UUID tenantId, UUID gameInstanceId, UUID regionId, UUID transitionId) { + List> rows = + new ArrayList<>(snapshotRegionOwnerSqlState(dsl, tenantId, gameInstanceId, regionId)); + for (String table : + List.of( + "game_session_canonical_binding_transition", + "game_session_canonical_issuer_partition_reservation", + "game_session_canonical_binding_account_index_obligation", + "game_session_canonical_binding_issuer_index_obligation")) { + rows.add( + dsl.fetch( + "SELECT (to_jsonb(target) || jsonb_build_object('xmin', target.xmin::text))::text" + + " AS image" + + " FROM {0} AS target WHERE transition_id = {1} ORDER BY image", + DSL.name(table), DSL.val(transitionId)) + .getValues("image", String.class)); + } + return rows; + } + + private static void requireExpiredGrantRefusal(Runnable operation, String expectedOwnerMethod) { + try { + operation.run(); + } catch (IllegalStateException failure) { + if (failedRedisGrantCheck(failure, expectedOwnerMethod)) { + return; + } + throw failure; + } + throw new IllegalStateException("Expired grant passed " + expectedOwnerMethod); + } + private static Map metadataImage(RegionRedis redis, String metaKey) { Map metadata = new java.util.TreeMap<>(); redis @@ -2038,8 +2149,32 @@ private static RegionRedisState snapshotRegionRedisState( return new RegionRedisState( redis.admin().type(leaseKey), asciiString(redis.admin().get(leaseKey)), - redis.admin().pexpiretime(leaseKey), - Map.copyOf(metadata)); + Map.copyOf(metadata), + redis.admin().pttl(ascii(metaKey))); + } + + private static ReadPreseededActorRuntimeReferenceRequest preseededEntityRequest( + CanonicalInitialPlayerLocationRequest request) { + return ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(request.getAssignmentUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setExpectedTarget(request.getExpectedTarget()) + .setCharacterUuid(request.getCharacterUuid()) + .setIntentDigest(request.getAssignmentIntentDigest()) + .build(); + } + + private static boolean failedRedisGrantCheck(IllegalStateException failure, String method) { + StackTraceElement[] frames = failure.getStackTrace(); + String owner = CanonicalGameplayRegionLeaseRedisOwner.class.getName(); + return failure.getCause() == null + && "Canonical Game Session region lease is unavailable".equals(failure.getMessage()) + && frames.length >= 2 + && owner.equals(frames[0].getClassName()) + && "unavailable".equals(frames[0].getMethodName()) + && owner.equals(frames[1].getClassName()) + && method.equals(frames[1].getMethodName()); } private static RegionBridgeRedisState snapshotRegionBridgeRedisState( @@ -2125,7 +2260,17 @@ public record Proof( public record SecondBinding( CanonicalInitialPlayerLocationRequest worldRequest, CanonicalPlayableTarget currentTarget, - CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) {} + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + boolean expireBeforeBridge) { + public SecondBinding( + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) { + this(worldRequest, currentTarget, worldRegionResolver, entityReferenceClient, false); + } + } public record TwoBindingProof( Proof first, @@ -2139,7 +2284,7 @@ public record TwoBindingProof( // Absolute lease expiry detects a renewal without failing on elapsed time. private record RegionRedisState( - String leaseType, String leaseValue, long leaseExpiresAt, Map metadata) {} + String leaseType, String leaseValue, Map metadata, long metadataTtlMillis) {} private record RegionBridgeRedisState( String leaseValue, @@ -2186,19 +2331,49 @@ public StableEvidence readCurrent(RegionScope scope) { } } + static AclSetuserArgs regionOwnerPermissions( + String password, boolean allowScriptLoad, boolean allowTime) { + AclSetuserArgs args = + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("tick-executor-lease:*") + .keyPattern("tick:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HSET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRE); + if (allowTime) args.addCommand(CommandType.TIME); + if (allowScriptLoad) args.addCommand(CommandType.SCRIPT, CommandKeyword.LOAD); + return args; + } + private static final class RegionRedis implements AutoCloseable { private final RedisClient administrator; private final RedisClient ownerClient; + private final RedisURI ownerUri; private final StatefulRedisConnection adminConnection; private final RedisCommands admin; private RegionRedis( RedisClient administrator, RedisClient ownerClient, + RedisURI ownerUri, StatefulRedisConnection adminConnection, RedisCommands admin) { this.administrator = administrator; this.ownerClient = ownerClient; + this.ownerUri = ownerUri; this.adminConnection = adminConnection; this.admin = admin; } @@ -2217,27 +2392,7 @@ private static RegionRedis open(String host, int port, boolean allowAccountMembe StatefulRedisConnection adminConnection = administrator.connect(ByteArrayCodec.INSTANCE); RedisCommands admin = adminConnection.sync(); - AclSetuserArgs permissions = - new AclSetuserArgs() - .reset() - .on() - .addPassword(REDIS_PASSWORD) - .keyPattern("tick-executor-lease:*") - .keyPattern("tick:*") - .addCommand(CommandType.HELLO) - .addCommand(CommandType.PING) - .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) - .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) - .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) - .addCommand(CommandType.EVALSHA) - .addCommand(CommandType.TYPE) - .addCommand(CommandType.HGET) - .addCommand(CommandType.HSET) - .addCommand(CommandType.HLEN) - .addCommand(CommandType.PTTL) - .addCommand(CommandType.GET) - .addCommand(CommandType.SET) - .addCommand(CommandType.PEXPIRE); + var permissions = regionOwnerPermissions(REDIS_PASSWORD, true, true); if (allowAccountMemberRepair) { permissions .keyPattern("session:game:index:account:*") @@ -2250,7 +2405,9 @@ private static RegionRedis open(String host, int port, boolean allowAccountMembe .withTimeout(Duration.ofSeconds(5)) .withAuthentication(REDIS_PRINCIPAL, REDIS_PASSWORD) .build(); - return new RegionRedis(administrator, RedisClient.create(ownerUri), adminConnection, admin); + RedisClient owner = RedisClient.create(ownerUri); + owner.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return new RegionRedis(administrator, owner, ownerUri, adminConnection, admin); } RedisClient ownerClient() { 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 a365776e03..1cd336d863 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 @@ -400,6 +400,7 @@ final class TransferSqlProof implements AutoCloseable { CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( sql, redis, + coordinationUri, fixture.transitionId(), upstream.request, upstream.resolver, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index 02d85d4726..27d343d61a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -362,11 +362,16 @@ void createPendingIsCreateOnlyAndUsesPhysicalAcknowledgementAndIndependentReadba var original = coordinates(); own(original); var provider = new TracedProvider(writer); - var client = client(provider, new ControlledAuthority(), 1); + var client = + client( + provider, + new ControlledAuthority(), + new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 3_000)); var expected = InitialGameplayLoginContextState.pending(original); - assertThat(client.createPending(original).orElseThrow().encode()) - .containsExactly(expected.encode()); + var createdPending = client.createPending(original); + assertThat(createdPending).as("physical create observations: %s", provider.traces).isPresent(); + assertThat(createdPending.orElseThrow().encode()).containsExactly(expected.encode()); byte[] created = admin.get(key(original)); assertThat(created).containsExactly(expected.encode()); assertThat(admin.pexpiretime(key(original))).isEqualTo(-1L); @@ -651,7 +656,10 @@ void ownerComposesDurableOriginalWithPhysicalPendingAndExactNonAdmittingInstall( throws Exception { var authority = new ControlledAuthority(); var provider = new TracedProvider(writer); - var contexts = client(provider, authority, 1); + // Positive composition requires replica fsync under shared-runner load. + // Keep insufficient-acknowledgement tests on their separate short failure deadline. + var contexts = + client(provider, authority, new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 3_000)); var account = mock(CanonicalGameplayLoginAccountClient.class); var cleanup = cleanup(contexts, account); var owner = new InitialGameplayLoginOwner(contexts, cleanup, account); @@ -706,6 +714,7 @@ void ownerComposesDurableOriginalWithPhysicalPendingAndExactNonAdmittingInstall( ownedKeys.add(InitialGameplayLoginContextRedisKeys.contextKey(original.callerContextId())); assertThat(outcome.status()) + .as("physical original composition observations: %s", provider.traces) .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); assertThat(original.expectedAttemptFence()).isEqualTo(1L); assertThat(original.requestId().version()).isEqualTo(4); @@ -747,7 +756,8 @@ void ownerClosesExactOriginalAndWipesResultWhenCredentialCustodyEndsAfterAccount throws Exception { var authority = new ControlledAuthority(); var provider = new TracedProvider(writer); - var contexts = client(provider, authority, 1); + var contexts = + client(provider, authority, new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 3_000)); var account = mock(CanonicalGameplayLoginAccountClient.class); var cleanup = cleanup(contexts, account); var owner = new InitialGameplayLoginOwner(contexts, cleanup, account); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java index 2914429478..17c823badf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java @@ -28,6 +28,8 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -203,6 +205,81 @@ void rejectsRegionResultWithChangedPlacementTargetOrLifecycleFence() throws Exce .hasMessageContaining("incomplete or stale"); } + @Test + void defaultRegionReadUsesTwentySecondOptionsOnTheActualCall() throws Exception { + var request = request(); + var region = regionResponse(request); + var channel = mock(ManagedChannel.class); + @SuppressWarnings("unchecked") + ClientCall + call = mock(ClientCall.class); + var ssl = mock(javax.net.ssl.SSLSession.class); + var certificate = mock(X509Certificate.class); + when(ssl.getPeerCertificates()).thenReturn(new java.security.cert.Certificate[] {certificate}); + when(certificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, EXPECTED_WORLD_PEER))); + when(call.getAttributes()) + .thenReturn( + Attributes.newBuilder().set(io.grpc.Grpc.TRANSPORT_ATTR_SSL_SESSION, ssl).build()); + doAnswer( + invocation -> { + ClientCall.Listener listener = + invocation.getArgument(0); + listener.onMessage(region); + listener.onClose(Status.OK, new Metadata()); + return null; + }) + .when(call) + .start(any(), any()); + var method = + CanonicalInitialPlayerLocationServiceGrpc.getReadInitialPlayerLocationRegionMethod(); + when(channel.newCall(org.mockito.ArgumentMatchers.eq(method), any())).thenReturn(call); + when(channels.buildChannel(anyString(), anyInt(), any(), anyBoolean())).thenReturn(channel); + var client = newClient(); + client.init(); + + Deadline earliest = Deadline.after(20L, TimeUnit.SECONDS); + assertThat(client.readInitialPlayerLocationRegion(request)).isEqualTo(region); + Deadline latest = Deadline.after(20L, TimeUnit.SECONDS); + + var optionsCaptor = org.mockito.ArgumentCaptor.forClass(CallOptions.class); + verify(channel).newCall(org.mockito.ArgumentMatchers.eq(method), optionsCaptor.capture()); + var actual = optionsCaptor.getValue().getDeadline(); + assertThat(actual).isNotNull(); + assertThat(actual.compareTo(earliest)).isGreaterThanOrEqualTo(0); + assertThat(actual.compareTo(latest)).isLessThanOrEqualTo(0); + } + + @Test + void deadlineBoundRegionReadDoesNotWaitForStalledTlsReload() throws Exception { + var request = request(); + var stub = mockStub(); + var region = regionResponse(request); + var deadlineApplied = new CountDownLatch(1); + var deadlineStub = mockStub(); + when(stub.withDeadline(any(Deadline.class))) + .thenAnswer(invocation -> { + deadlineApplied.countDown(); + return deadlineStub; + }); + when(deadlineStub.readInitialPlayerLocationRegion(request)).thenReturn(region); + var client = clientWithStub(stub); + Deadline callerDeadline = Deadline.after(100L, TimeUnit.MILLISECONDS); + + try (var executor = Executors.newSingleThreadExecutor()) { + // TLS reload owns this monitor while it builds and publishes a replacement channel. + synchronized (client) { + var result = + executor.submit(() -> client.readInitialPlayerLocationRegion(request, callerDeadline)); + + assertThat(deadlineApplied.await(1L, TimeUnit.SECONDS)).isTrue(); + assertThat(result.get(1L, TimeUnit.SECONDS)).isEqualTo(region); + } + } + verify(stub).withDeadline(callerDeadline); + verify(deadlineStub).readInitialPlayerLocationRegion(request); + } + @Test void rejectsRegionResultAttributedToAnotherWorkloadNamespace() throws Exception { var request = request(); @@ -609,6 +686,7 @@ private CanonicalInitialPlayerLocationClient newClient() { CanonicalInitialPlayerLocationServiceGrpc .CanonicalInitialPlayerLocationServiceBlockingStub.class); when(stub.withDeadlineAfter(20L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withDeadline(any(Deadline.class))).thenReturn(stub); when(stub.withMaxInboundMessageSize(8 * 1024)).thenReturn(stub); when(stub.withMaxOutboundMessageSize(16 * 1024)).thenReturn(stub); return stub; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java index eb7b546ff3..6ccdba7653 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java @@ -29,6 +29,8 @@ import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.AccountPublicJwksCache; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; @@ -86,8 +88,25 @@ static void generateControlledAccountSigningKey() throws Exception { void buildsNonPersistableTemplateAndAcceptsExactFinalCasReadback() throws Exception { try (Fixture fixture = fixture(claims -> {}); var template = template(fixture)) { + var entitlement = fixture.capacityRequest.evidence().fields(); + assertThat(entitlement) + .containsEntry("membershipExists", true) + .containsEntry("membershipLifecycleState", "ACTIVE") + .containsEntry("gameplayAdmissionAllowed", true); + assertThat((List) entitlement.get("authoritySourceEvidence")) + .anySatisfy(source -> { + assertThat(source).isInstanceOf(Map.class); + String eventJson = (String) ((Map) source).get("canonicalEventJson"); + assertThat(eventJson) + .contains("\"eventType\":\"MEMBERSHIP_CHANGED\"") + .contains("\"membershipLifecycleState\":\"ACTIVE\"") + .contains("\"gameplayAdmissionAllowed\":true"); + }); byte[] templateBytes = template.finalCasTemplateBytes(); String templateJson = new String(templateBytes, StandardCharsets.UTF_8); + String executionDigest = execution(fixture).digest(); + assertThat(JSON.readTree(templateBytes).path("capacityExecutionDigest").asText()) + .isEqualTo(executionDigest); assertThat(templateJson) .contains("__ORIGINAL_NEW_ADMISSION_AT_MS__") .contains("__ORIGINAL_NEW_CONTINUITY_EXPIRES_AT_MS__") @@ -99,43 +118,49 @@ void buildsNonPersistableTemplateAndAcceptsExactFinalCasReadback() throws Except .isInstanceOf(IllegalArgumentException.class) .hasMessage("Canonical ORIGINAL_NEW authenticated session is invalid"); - var execution = capacityExecution(fixture.candidate); - try (var bound = template.bindCapacityExecution(execution)) { - long admissionAt = CLOCK.millis() + 100L; - byte[] boundBytes = bound.finalCasTemplateBytes(); - byte[] finalBytes = finalizeTemplate(boundBytes, admissionAt, SESSION_DURATION_MILLIS); - try (var finalized = bound.requireFinalizedReadback(finalBytes)) { - assertThat(finalized.originalCandidate().bindingDecisionId()) - .isEqualTo(BINDING_DECISION_ID); - assertThat(finalized.admissionAtMillis()).isEqualTo(admissionAt); - assertThat(finalized.continuityBindingExpiresAtMillis()) - .isEqualTo(admissionAt + SESSION_DURATION_MILLIS); - assertThat(finalized.authTokenHash()).isEqualTo(hash(fixture.compactJwt)); - assertThat(finalized.authTokenIssuedAt()).isEqualTo(NOW_SECONDS); - assertThat(finalized.authTokenExpiresAt()).isEqualTo(NOW_SECONDS + 240L); - assertThat(finalized.capacityExecutionDigest()).isEqualTo(execution.digest()); - assertThat(finalized.tokenGeneration()).isEqualTo("1"); - assertThat(finalized.issuanceFence()).isEqualTo(TOKEN_FENCE); - assertThat(finalized.canonicalSessionDurationMillis()).isEqualTo(SESSION_DURATION_MILLIS); - byte[] returnedHandle = finalized.opaqueRebindHandle(); - try { - assertThat(returnedHandle).containsExactly(HANDLE); - } finally { - Arrays.fill(returnedHandle, (byte) 0); - } - byte[] exactBytes = finalized.canonicalBytes(); - try { - assertThat(exactBytes).containsExactly(finalBytes); - } finally { - Arrays.fill(exactBytes, (byte) 0); - } - assertThat(finalized.toString()).doesNotContain(HANDLE_HEX, fixture.compactJwt); + long admissionAt = CLOCK.millis() + 100L; + byte[] finalBytes = finalizeTemplate(templateBytes, admissionAt, SESSION_DURATION_MILLIS); + String wrongDigest = + "sha256:" + (executionDigest.charAt(7) == '0' ? "1" : "0") + executionDigest.substring(8); + byte[] differentExecution = + new String(finalBytes, StandardCharsets.UTF_8) + .replace(executionDigest, wrongDigest) + .getBytes(StandardCharsets.UTF_8); + try { + assertThatThrownBy(() -> template.requireFinalizedReadback(differentExecution)) + .isInstanceOf(IllegalArgumentException.class); + } finally { + Arrays.fill(differentExecution, (byte) 0); + } + try (var finalized = template.requireFinalizedReadback(finalBytes)) { + assertThat(finalized.originalCandidate().bindingDecisionId()) + .isEqualTo(BINDING_DECISION_ID); + assertThat(finalized.admissionAtMillis()).isEqualTo(admissionAt); + assertThat(finalized.continuityBindingExpiresAtMillis()) + .isEqualTo(admissionAt + SESSION_DURATION_MILLIS); + assertThat(finalized.authTokenHash()).isEqualTo(hash(fixture.compactJwt)); + assertThat(finalized.authTokenIssuedAt()).isEqualTo(NOW_SECONDS); + assertThat(finalized.authTokenExpiresAt()).isEqualTo(NOW_SECONDS + 240L); + assertThat(finalized.capacityExecutionDigest()).isEqualTo(executionDigest); + assertThat(finalized.tokenGeneration()).isEqualTo("1"); + assertThat(finalized.issuanceFence()).isEqualTo(TOKEN_FENCE); + assertThat(finalized.canonicalSessionDurationMillis()).isEqualTo(SESSION_DURATION_MILLIS); + byte[] returnedHandle = finalized.opaqueRebindHandle(); + try { + assertThat(returnedHandle).containsExactly(HANDLE); } finally { - Arrays.fill(boundBytes, (byte) 0); - Arrays.fill(finalBytes, (byte) 0); + Arrays.fill(returnedHandle, (byte) 0); } + byte[] exactBytes = finalized.canonicalBytes(); + try { + assertThat(exactBytes).containsExactly(finalBytes); + } finally { + Arrays.fill(exactBytes, (byte) 0); + } + assertThat(finalized.toString()).doesNotContain(HANDLE_HEX, fixture.compactJwt); } finally { Arrays.fill(templateBytes, (byte) 0); + Arrays.fill(finalBytes, (byte) 0); } } } @@ -244,8 +269,7 @@ void accountSignatureAndBoundClaimsMustMatchTheOriginalLeaseAndCredential() thro @Test void strictFinalReaderRejectsUnknownDuplicateTrailingMalformedAndOversizeJson() throws Exception { try (Fixture fixture = fixture(claims -> {}); - var unbound = template(fixture); - var template = unbound.bindCapacityExecution(capacityExecution(fixture.candidate))) { + var template = template(fixture)) { byte[] candidate = template.finalCasTemplateBytes(); byte[] complete = finalizeTemplate(candidate, CLOCK.millis() + 100L, SESSION_DURATION_MILLIS); try { @@ -273,8 +297,7 @@ void strictFinalReaderRejectsUnknownDuplicateTrailingMalformedAndOversizeJson() @Test void strictFinalReaderRejectsMissingNullPlaceholderAndChangedAnchors() throws Exception { try (Fixture fixture = fixture(claims -> {}); - var unbound = template(fixture); - var template = unbound.bindCapacityExecution(capacityExecution(fixture.candidate))) { + var template = template(fixture)) { byte[] templateBytes = template.finalCasTemplateBytes(); byte[] complete = finalizeTemplate(templateBytes, CLOCK.millis() + 100L, SESSION_DURATION_MILLIS); @@ -331,8 +354,7 @@ void strictFinalReaderRejectsMissingNullPlaceholderAndChangedAnchors() throws Ex @Test void finalCasReadbackAllowsOnlyAdmissionAndContinuityTimeSlotsToChange() throws Exception { try (Fixture fixture = fixture(claims -> {}); - var unbound = template(fixture); - var template = unbound.bindCapacityExecution(capacityExecution(fixture.candidate))) { + var template = template(fixture)) { byte[] templateBytes = template.finalCasTemplateBytes(); byte[] complete = finalizeTemplate(templateBytes, CLOCK.millis() + 100L, SESSION_DURATION_MILLIS); @@ -363,10 +385,37 @@ private static void assertVerifierDenies(Fixture fixture) { .hasMessage("Original NEW bound credential is invalid"); } + private static OriginalNewCapacityExecution execution(Fixture fixture) { + var request = fixture.capacityRequest; + var reservation = + new TenantCapacityAdmission.Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + 1, + request.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + return new OriginalNewCapacityExecution( + request, + reservation, + fixture.candidate.bindingDecisionId(), + "sha256:" + OriginalNewCapacityExecution.sha256(fixture.candidate.canonicalBytes()), + "controlled-owner", + 1); + } + private static CanonicalGameplayOriginalNewAuthenticatedSession.Template template( Fixture fixture) { - return CanonicalGameplayOriginalNewAuthenticatedSession.template( - fixture.candidate, fixture.credential, fixture.verifier, SESSION_DURATION_MILLIS); + var execution = execution(fixture); + try (var raw = + CanonicalGameplayOriginalNewAuthenticatedSession.template( + fixture.candidate, fixture.credential, fixture.verifier, SESSION_DURATION_MILLIS)) { + return raw.bindCapacityExecution(execution); + } } /** Proves the unmutated bound base is valid, so each rejection isolates its own mutation. */ @@ -388,65 +437,6 @@ private static void assertDenied(byte[] bytes) { } } - private static OriginalNewCapacityExecution capacityExecution( - CanonicalGameplayOriginalNewCandidate candidate) throws Exception { - var target = candidate.targetEvidence(); - var at = CLOCK.instant(); - var request = - CapacityAdmissionTestFixture.playerRequestFor( - new TenantCapacityAdmission.PlayerContext( - ACCOUNT_ID, - TENANT_ID, - PLAYABLE_NAMESPACE_ID, - GAME_INSTANCE_ID, - CHARACTER_ID, - SESSION_ID, - REALM_ID, - REQUEST_ID, - "SHARED"), - BINDING_DECISION_ID, - CapacityAdmissionTestFixture.ATTEMPT, - NAMESPACE, - Map.ofEntries( - Map.entry("targetClass", "PUBLIC_PRODUCTION"), - Map.entry("characterCreationPolicy", "PRESEEDED_ONLY"), - Map.entry("targetNamespace", NAMESPACE), - Map.entry("tenantId", TENANT_ID.toString()), - Map.entry("tenantSlug", target.tenantSlug()), - Map.entry("worldSlug", target.worldSlug()), - Map.entry("realmId", REALM_ID.toString()), - Map.entry("realmSlug", target.realmSlug()), - Map.entry("playableStateNamespaceId", PLAYABLE_NAMESPACE_ID.toString()), - Map.entry("playableStateScope", "SHARED"), - Map.entry("gameInstanceId", GAME_INSTANCE_ID.toString()), - Map.entry("canonicalVersionId", VERSION_ID.toString()), - Map.entry("catalogRevision", Long.toString(target.catalogRevision())), - Map.entry("pointerVersion", Long.toString(target.pointerVersion())), - Map.entry("activeWorldEpoch", Long.toString(target.activeWorldEpoch())), - Map.entry("evaluatedAt", at.minusSeconds(1).toString()), - Map.entry("connectScopeExpiresAt", at.plusSeconds(120).toString())), - at); - var reservation = - new TenantCapacityAdmission.Result( - request.identity(), - request.admissionAttemptId(), - request.capacityRearmFence(), - request.mutationDigest(), - RESERVATION_ID, - 1, - request.evidence().expiresAt(), - TenantCapacityAdmission.State.RESERVED, - request.evidence().snapshotIdentity(), - request.evidence().evaluationIdentity()); - return new OriginalNewCapacityExecution( - request, - reservation, - BINDING_DECISION_ID, - "sha256:" + hash(candidate.canonicalBytes()), - "controlled-owner", - 1); - } - private static byte[] finalizeTemplate(byte[] template, long admissionAt, long duration) throws Exception { ObjectNode root = (ObjectNode) JSON.readTree(template); @@ -474,8 +464,10 @@ private static Fixture fixture(java.util.function.Consumer> private static Fixture fixture( java.util.function.Consumer> mutateClaims, KeyPair signingKey) throws Exception { - AccountGameplayAdmissionLeaseEvidence lease = lease(); - CanonicalGameplayOriginalNewCandidate candidate = candidate(lease); + var target = playableTarget(); + var capacityRequest = capacityRequest(target); + AccountGameplayAdmissionLeaseEvidence lease = lease(capacityRequest); + CanonicalGameplayOriginalNewCandidate candidate = candidate(lease, target); Map claims = boundClaims(lease); mutateClaims.accept(claims); String compactJwt = sign(claims, signingKey); @@ -493,11 +485,11 @@ private static Fixture fixture( 1L, "42", checkpointsSha256); - return new Fixture(candidate, credential, compactJwt, verifier()); + return new Fixture(candidate, capacityRequest, credential, compactJwt, verifier()); } private static CanonicalGameplayOriginalNewCandidate candidate( - AccountGameplayAdmissionLeaseEvidence lease) { + AccountGameplayAdmissionLeaseEvidence lease, CanonicalPlayableTarget target) { CanonicalGameplayBindingIdentity binding = new CanonicalGameplayBindingIdentity( ACCOUNT_ID, @@ -515,40 +507,6 @@ private static CanonicalGameplayOriginalNewCandidate candidate( BigInteger.ONE, BigInteger.ONE, BigInteger.ONE); - CanonicalPlayableTarget target = - new CanonicalPlayableTarget( - NAMESPACE, - "tenant", - TENANT_ID, - "world", - "World", - REALM_ID, - "realm", - "Realm", - 42L, - 77L, - PLAYABLE_NAMESPACE_ID, - "SHARED", - GAME_INSTANCE_ID, - VERSION_ID, - 3L, - 5L, - 6L, - "a".repeat(64), - 1L, - REQUEST_ID.toString(), - "b".repeat(64), - OriginKind.NO_PRIOR_POINTER, - null, - OTHER_ID, - RESERVATION_FENCE, - "sha256:" + "c".repeat(64), - 100L, - "sha256:" + "d".repeat(64), - Outcome.COMMITTED, - false, - Instant.parse("2026-10-26T00:00:00Z"), - "PRESEEDED_ONLY"); var bindingRef = binding.bindingRef(); var transition = new CanonicalGameplayOriginalNewCandidate.TransitionSource( @@ -574,7 +532,79 @@ private static CanonicalGameplayOriginalNewCandidate candidate( BINDING_DECISION_ID, lease, binding, target, transition, reservation); } - private static AccountGameplayAdmissionLeaseEvidence lease() { + private static CanonicalPlayableTarget playableTarget() { + return new CanonicalPlayableTarget( + NAMESPACE, + "tenant", + TENANT_ID, + "world", + "World", + REALM_ID, + "realm", + "Realm", + 42L, + 77L, + PLAYABLE_NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + VERSION_ID, + 3L, + 5L, + 6L, + "a".repeat(64), + 1L, + REQUEST_ID.toString(), + "b".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + OTHER_ID, + RESERVATION_FENCE, + "sha256:" + "c".repeat(64), + 100L, + "sha256:" + "d".repeat(64), + Outcome.COMMITTED, + false, + Instant.parse("2026-10-26T00:00:00Z"), + "PRESEEDED_ONLY"); + } + + private static Request capacityRequest(CanonicalPlayableTarget target) { + var player = + new PlayerContext( + ACCOUNT_ID, + TENANT_ID, + PLAYABLE_NAMESPACE_ID, + GAME_INSTANCE_ID, + CHARACTER_ID, + SESSION_ID, + REALM_ID, + REQUEST_ID, + target.playableStateScope()); + var now = CLOCK.instant(); + var accountTarget = + Map.ofEntries( + Map.entry("targetClass", "PUBLIC_PRODUCTION"), + Map.entry("characterCreationPolicy", target.characterCreationPolicy()), + Map.entry("targetNamespace", target.targetNamespace()), + Map.entry("tenantId", target.canonicalTenantId().toString()), + Map.entry("tenantSlug", target.tenantSlug()), + Map.entry("worldSlug", target.worldSlug()), + Map.entry("realmId", target.realmId().toString()), + Map.entry("realmSlug", target.realmSlug()), + Map.entry("playableStateNamespaceId", target.playableStateNamespaceId().toString()), + Map.entry("playableStateScope", target.playableStateScope()), + Map.entry("gameInstanceId", target.canonicalGameInstanceId().toString()), + Map.entry("canonicalVersionId", target.canonicalVersionId().toString()), + Map.entry("catalogRevision", Long.toString(target.catalogRevision())), + Map.entry("pointerVersion", Long.toString(target.pointerVersion())), + Map.entry("activeWorldEpoch", Long.toString(target.activeWorldEpoch())), + Map.entry("evaluatedAt", now.minusSeconds(1).toString()), + Map.entry("connectScopeExpiresAt", now.plusSeconds(120).toString())); + return CapacityAdmissionTestFixture.playerRequestFor( + player, BINDING_DECISION_ID, LEASE_ID, target.targetNamespace(), accountTarget, now); + } + + private static AccountGameplayAdmissionLeaseEvidence lease(Request capacityRequest) { Map value = new LinkedHashMap<>(); value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); value.put("schemaVersion", "1"); @@ -602,14 +632,7 @@ private static AccountGameplayAdmissionLeaseEvidence lease() { scope.put("regionId", REGION_ID.toString()); scope.put("regionEpoch", ONE); value.put("bindingScope", scope); - value.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", ONE, - "accountAuthorityGeneration", ONE, - "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), "2"), - "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), "3"), - "privateRealmGrantVersions", List.of())); + value.put("authorityTuple", capacityRequest.evidence().fields().get("authorityTuple")); value.put("issuanceFence", TOKEN_FENCE); value.put( "membershipBaseline", @@ -617,9 +640,9 @@ private static AccountGameplayAdmissionLeaseEvidence lease() { "membershipLifecycleState", "ACTIVE", "membershipVersion", - Map.of(TENANT_ID.toString(), "9"), + capacityRequest.evidence().fields().get("membershipVersion"), "membershipAuthorityGeneration", - "3")); + capacityRequest.evidence().fields().get("membershipAuthorityGeneration"))); value.put("outboxCheckpoints", checkpoints()); value.put( "tokenIdentityEvidence", @@ -654,7 +677,7 @@ private static List> checkpoints() { "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", - suffix.startsWith("membership/") || suffix.startsWith("tenant/") ? "9" : "0")); + suffix.startsWith("membership/") || suffix.startsWith("tenant/") ? "1" : "0")); } return List.copyOf(result); } @@ -777,16 +800,19 @@ private static UUID uuid(String value) { private static final class Fixture implements AutoCloseable { private final CanonicalGameplayOriginalNewCandidate candidate; + private final Request capacityRequest; private final AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential credential; private final String compactJwt; private final CanonicalGameplayOriginalNewBoundCredentialVerifier verifier; private Fixture( CanonicalGameplayOriginalNewCandidate candidate, + Request capacityRequest, AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential credential, String compactJwt, CanonicalGameplayOriginalNewBoundCredentialVerifier verifier) { this.candidate = candidate; + this.capacityRequest = capacityRequest; this.credential = credential; this.compactJwt = compactJwt; this.verifier = verifier; 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 a1b646d20c..39e628dfd6 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 @@ -6,6 +6,7 @@ import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; @@ -21,18 +22,26 @@ import io.grpc.Context; import io.grpc.Deadline; import io.lettuce.core.ClientOptions; +import io.lettuce.core.ConnectionFuture; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisFuture; +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.async.RedisAsyncCommands; import io.lettuce.core.codec.ByteArrayCodec; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.net.InetSocketAddress; +import java.security.MessageDigest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; +import java.util.HexFormat; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -48,7 +57,9 @@ import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; 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.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; import org.awaitility.Awaitility; import org.jooq.ConnectionProvider; import org.jooq.DSLContext; @@ -66,6 +77,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 { @@ -271,6 +283,608 @@ void backgroundPhysicalCompletionIncludesDelayedProviderReturn() throws Exceptio } } + @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(); + byte[] expectedLeaseKey = + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII); + verify(commands, org.mockito.Mockito.times(3)) + .get(org.mockito.AdditionalMatchers.aryEq(expectedLeaseKey)); + verify(commands, org.mockito.Mockito.times(3)) + .pttl(org.mockito.AdditionalMatchers.aryEq(expectedLeaseKey)); + org.mockito.Mockito.verifyNoMoreInteractions(commands); + } + + @Test + void manualFactoryEnablesPerInstallationDeadline() { + RedisClient client = mock(); + when(client.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + var owner = composeManualLeaseOwner(client, Duration.ofSeconds(30)); + assertThat(ReflectionTestUtils.getField(owner, "deadlineBoundInstallation")).isEqualTo(true); + } + + @Test + void manualFactoryRejectsReconnectEnabledCoordinationClient() { + RedisClient client = mock(); + when(client.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(true).build()); + assertThatThrownBy(() -> composeManualLeaseOwner(client, Duration.ofSeconds(30))) + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("coordinationRedis requires autoReconnect=false"); + } + + @Test + void manualFactoryRequiresLeaseToCoverTheInstallationWindow() { + RedisClient client = mock(); + when(client.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + var installationWindow = + Duration.ofMillis(CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_OPERATION_MILLIS); + assertThatThrownBy(() -> composeManualLeaseOwner(client, installationWindow)) + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("leaseTtl must exceed the bounded installation window"); + } + + @Test + void manualFactoryRefusesSqlConnectionsThatCannotBeRetired() { + RedisClient client = mock(); + when(client.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + var unsupported = + DSL.using( + new org.springframework.jdbc.datasource.DriverManagerDataSource(), SQLDialect.POSTGRES); + assertThatThrownBy(() -> composeManualLeaseOwner(client, Duration.ofSeconds(30), unsupported)) + .isExactlyInstanceOf(IllegalArgumentException.class) + .hasMessage("region lease SQL requires a retireable Hikari data source"); + } + + private static CanonicalGameplayRegionLeaseOwner composeManualLeaseOwner( + RedisClient client, Duration leaseTtl) { + return composeManualLeaseOwner( + client, + leaseTtl, + DSL.using(mock(com.zaxxer.hikari.HikariDataSource.class), SQLDialect.POSTGRES)); + } + + private static CanonicalGameplayRegionLeaseOwner composeManualLeaseOwner( + RedisClient client, Duration leaseTtl, DSLContext dsl) { + return CanonicalGameplayRegionLeaseOwnerFactory.compose( + dsl, + client, + RedisURI.create("redis://localhost:6379"), + mock(RedisScriptCatalog.class), + mock(CanonicalGameplayRegionIncarnationSource.class), + mock( + net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver + .class), + mock(RuntimeIdentity.class), + leaseTtl, + CLOCK); + } + + @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(() -> assertThat(owner.forInstallation(frozenClock)).isNotNull()) + .isInstanceOf(IllegalStateException.class)); + } + verifyNoInteractions(client); + } + + @Test + void timedOutHandoffRedisConnectRetainsAdmissionThroughLateClose() throws Exception { + RedisClient redis = mock(); + RedisURI uri = RedisURI.create("redis://localhost:6379"); + var owner = + new CanonicalGameplayRegionLeaseRedisOwner( + redis, uri, RedisScriptCatalog.fromContributions(List.of())); + CompletableFuture> handshake = + new CompletableFuture<>(); + StatefulRedisConnection connection = mock(); + CompletableFuture close = new CompletableFuture<>(); + CountDownLatch connected = new CountDownLatch(1); + when(redis.connectAsync(eq(ByteArrayCodec.INSTANCE), any(RedisURI.class))) + .thenAnswer(invocation -> { + connected.countDown(); + return ConnectionFuture.from(new InetSocketAddress("localhost", 6379), handshake); + }); + when(connection.closeAsync()).thenReturn(close); + Semaphore permits = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, + "BACKGROUND_OPERATIONS")); + int maximum = CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_BACKGROUND_OPERATIONS; + + var earliestDeadlineReturn = new AtomicLong(); + var callerReturned = new AtomicLong(); + try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { + // Leave the resource worker ample time to reach the blocked connect before the deadline. + var caller = + executor.submit(() -> { + earliestDeadlineReturn.set(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1_900)); + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + CLOCK, + CLOCK.millis() + 2_000, + budget -> + ReflectionTestUtils.invokeMethod(owner, "openConnection", budget))) + .isInstanceOf(IllegalStateException.class); + callerReturned.set(System.nanoTime()); + }); + try { + assertThat(connected.await(4, TimeUnit.SECONDS)).isTrue(); + caller.get(4, TimeUnit.SECONDS); + assertThat(callerReturned.get()).isGreaterThanOrEqualTo(earliestDeadlineReturn.get()); + assertThat(handshake.isDone()).isFalse(); + assertPermitRemainsHeld(permits, maximum); + + handshake.complete(connection); + verify(connection, timeout(1000)).closeAsync(); + assertPermitRemainsHeld(permits, maximum); + verify(connection, never()).async(); + } finally { + handshake.completeExceptionally(new IllegalStateException("test cleanup")); + close.complete(null); + } + assertThat(permits.tryAcquire(maximum, 2, TimeUnit.SECONDS)).isTrue(); + permits.release(maximum); + } + } + + @Test + void timelinePreparationRefusesReconnectBeforeQualifyingOrSubmittingRedisCommands() { + RedisClient redis = mock(); + RedisURI uri = RedisURI.create("redis://localhost:6379"); + var catalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayRegionLeaseRedisScriptContribution())); + var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis, uri, catalog); + StatefulRedisConnection connection = mock(); + var source = mock(CanonicalGameplayRegionRuntimeStatusRepository.Source.class); + var preparation = + mock(CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation.class); + when(source.tenantId()).thenReturn(UUID.randomUUID()); + when(source.gameInstanceId()).thenReturn(UUID.randomUUID()); + when(source.regionId()).thenReturn(UUID.randomUUID()); + when(preparation.source()).thenReturn(source); + when(preparation.operationId()).thenReturn(UUID.randomUUID()); + when(preparation.sourceDigest()).thenReturn("a".repeat(64)); + when(preparation.regionEpoch()).thenReturn(1L); + when(redis.connectAsync(eq(ByteArrayCodec.INSTANCE), any(RedisURI.class))) + .thenReturn( + ConnectionFuture.from( + new InetSocketAddress("localhost", 6379), + CompletableFuture.completedFuture(connection))); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(true).build()); + when(connection.closeAsync()).thenReturn(CompletableFuture.completedFuture(null)); + RuntimeIdentity identity = + new RuntimeIdentity( + "game-session-service", + "controlled-instance", + "localhost", + CLOCK.instant(), + "controlled-test", + "controlled-sha", + "controlled-image"); + + assertThatThrownBy(() -> + owner + .forHandoffDeadline(CLOCK, CLOCK.millis() + 4_000L) + .prepareTimelineInitialization(preparation, Duration.ofSeconds(30), identity)) + .isInstanceOf(IllegalStateException.class); + verify(connection, atLeastOnce()).getOptions(); + verify(connection, never()).async(); + verify(connection).closeAsync(); + } + + @Test + void preparedTimelineRetainsAdmissionThroughRejectedCallersAsyncClose() throws Exception { + RedisClient redis = mock(); + RedisURI uri = RedisURI.create("redis://localhost:6379"); + var catalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayRegionLeaseRedisScriptContribution())); + var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis, uri, catalog); + StatefulRedisConnection connection = mock(); + RedisAsyncCommands commands = mock(); + RedisFuture principal = mock(); + RedisFuture scriptLoad = mock(); + CompletableFuture close = new CompletableFuture<>(); + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + var source = mock(CanonicalGameplayRegionRuntimeStatusRepository.Source.class); + var preparation = + mock(CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation.class); + UUID operationId = UUID.randomUUID(); + String sourceDigest = "a".repeat(64); + when(source.tenantId()).thenReturn(tenantId); + when(source.gameInstanceId()).thenReturn(gameInstanceId); + when(source.regionId()).thenReturn(regionId); + when(preparation.source()).thenReturn(source); + when(preparation.operationId()).thenReturn(operationId); + when(preparation.sourceDigest()).thenReturn(sourceDigest); + when(preparation.regionEpoch()).thenReturn(1L); + when(redis.connectAsync(eq(ByteArrayCodec.INSTANCE), any(RedisURI.class))) + .thenReturn( + ConnectionFuture.from( + new InetSocketAddress("localhost", 6379), + CompletableFuture.completedFuture(connection))); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.async()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(principal); + when(principal.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn("gamesession_coord_app"); + when(commands.scriptLoad(any(byte[].class))).thenReturn(scriptLoad); + var descriptor = + catalog.require(CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_ID); + byte[] script; + try (var scriptResource = + CanonicalGameplayRegionLeaseRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + assertThat(scriptResource).isNotNull(); + script = scriptResource.readAllBytes(); + } + String loadedSha = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(script)); + when(scriptLoad.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(loadedSha); + stubRedisTime(commands); + when(connection.closeAsync()).thenReturn(close); + RedisFuture probed = mock(); + when(commands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) + .thenReturn(probed); + when(probed.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(1L); + RuntimeIdentity identity = + new RuntimeIdentity( + "game-session-service", + "controlled-instance", + "localhost", + CLOCK.instant(), + "controlled-test", + "controlled-sha", + "controlled-image"); + Semaphore operations = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, "OPERATIONS")); + int operationMaximum = + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_IN_FLIGHT_OPERATIONS; + Semaphore background = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, + "BACKGROUND_OPERATIONS")); + int backgroundMaximum = + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_BACKGROUND_OPERATIONS; + + CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization prepared = null; + ExecutorService closer = Executors.newSingleThreadExecutor(); + try { + prepared = + owner + .forHandoffDeadline(CLOCK, CLOCK.millis() + 4000) + .prepareTimelineInitialization(preparation, Duration.ofSeconds(30), identity); + assertPermitRemainsHeld(operations, operationMaximum); + assertPermitRemainsHeld(background, backgroundMaximum); + + var preparedInitialization = prepared; + closer.submit(preparedInitialization::close).get(1, TimeUnit.SECONDS); + verify(connection, timeout(1000)).closeAsync(); + assertPermitRemainsHeld(operations, operationMaximum); + assertPermitRemainsHeld(background, backgroundMaximum); + var probeArguments = org.mockito.ArgumentCaptor.forClass(byte[][].class); + verify(commands, org.mockito.Mockito.times(1)) + .evalsha(any(), any(), any(), probeArguments.capture()); + verify(commands).time(); + assertThat(probeArguments.getValue()[1]) + .containsExactly("PROBE".getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + + close.complete(null); + assertThat(operations.tryAcquire(operationMaximum, 2, TimeUnit.SECONDS)).isTrue(); + operations.release(operationMaximum); + assertThat(background.tryAcquire(backgroundMaximum, 2, TimeUnit.SECONDS)).isTrue(); + background.release(backgroundMaximum); + verify(connection, org.mockito.Mockito.times(1)).closeAsync(); + // Closing must not dispatch INITIALIZE or repeat the preparation probe. + verify(commands, org.mockito.Mockito.times(1)) + .evalsha(any(), any(), any(), any(byte[][].class)); + } finally { + close.complete(null); + closer.shutdown(); + try { + assertThat(closer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } finally { + if (prepared != null) prepared.close(); + } + } + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void timelineInitializationUsesPreparedPermitWhileOtherBackgroundSlotIsOccupied(boolean composed) + throws Exception { + RedisClient redis = mock(); + RedisURI uri = RedisURI.create("redis://localhost:6379"); + var catalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayRegionLeaseRedisScriptContribution())); + var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis, uri, catalog); + StatefulRedisConnection connection = mock(); + RedisAsyncCommands commands = mock(); + RedisFuture principal = mock(); + RedisFuture scriptLoad = mock(); + RedisFuture initialized = mock(); + CompletableFuture close = new CompletableFuture<>(); + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + var source = mock(CanonicalGameplayRegionRuntimeStatusRepository.Source.class); + var preparation = + mock(CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation.class); + UUID operationId = UUID.randomUUID(); + String sourceDigest = "a".repeat(64); + when(source.tenantId()).thenReturn(tenantId); + when(source.gameInstanceId()).thenReturn(gameInstanceId); + when(source.regionId()).thenReturn(regionId); + when(preparation.source()).thenReturn(source); + when(preparation.operationId()).thenReturn(operationId); + when(preparation.sourceDigest()).thenReturn(sourceDigest); + when(preparation.regionEpoch()).thenReturn(1L); + when(redis.connectAsync(eq(ByteArrayCodec.INSTANCE), any(RedisURI.class))) + .thenReturn( + ConnectionFuture.from( + new InetSocketAddress("localhost", 6379), + CompletableFuture.completedFuture(connection))); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.async()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(principal); + when(principal.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn("gamesession_coord_app"); + when(commands.scriptLoad(any(byte[].class))).thenReturn(scriptLoad); + var descriptor = + catalog.require(CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_ID); + byte[] script; + try (var scriptResource = + CanonicalGameplayRegionLeaseRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + assertThat(scriptResource).isNotNull(); + script = scriptResource.readAllBytes(); + } + String loadedSha = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(script)); + when(scriptLoad.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(loadedSha); + var localMillis = new AtomicLong(CLOCK.millis()); + var sampledTime = new java.util.concurrent.atomic.AtomicBoolean(); + Clock delayedSampleClock = mock(); + when(delayedSampleClock.millis()).thenAnswer(ignored -> localMillis.get()); + when(delayedSampleClock.instant()) + .thenAnswer(ignored -> Instant.ofEpochMilli(localMillis.get())); + long samplingDelayMillis = 2_000L; + RedisFuture> redisTime = mock(); + when(commands.time()).thenReturn(redisTime); + when(redisTime.get(anyLong(), eq(TimeUnit.MILLISECONDS))) + .thenAnswer(ignored -> { + localMillis.addAndGet(samplingDelayMillis); + sampledTime.set(true); + return List.of( + "1700000000".getBytes(java.nio.charset.StandardCharsets.US_ASCII), + "123456".getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + }); + when(connection.closeAsync()).thenReturn(close); + 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( + "game-session-service", + "controlled-instance", + "localhost", + CLOCK.instant(), + "controlled-test", + "controlled-sha", + "controlled-image"); + var permitConstructor = + CanonicalGameplayRegionRuntimeStatusRepository.InitialInitializationPermit.class + .getDeclaredConstructor(UUID.class, String.class); + permitConstructor.setAccessible(true); + var permit = permitConstructor.newInstance(operationId, sourceDigest); + Semaphore operations = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, "OPERATIONS")); + int operationMaximum = + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_IN_FLIGHT_OPERATIONS; + Semaphore background = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, + "BACKGROUND_OPERATIONS")); + int backgroundMaximum = + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_BACKGROUND_OPERATIONS; + CountDownLatch otherBackgroundStarted = new CountDownLatch(1); + CountDownLatch releaseOtherBackground = new CountDownLatch(1); + + CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization prepared = null; + CompletableFuture otherBackground = null; + CompletableFuture initialization = null; + long handoffBudgetMillis = 4_000L; + long handoffDeadline = delayedSampleClock.millis() + handoffBudgetMillis; + try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { + try { + otherBackground = + CompletableFuture.supplyAsync( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + delayedSampleClock, + handoffDeadline, + budget -> { + otherBackgroundStarted.countDown(); + awaitUninterruptibly(releaseOtherBackground); + return true; + }), + executor); + assertThat(otherBackgroundStarted.await(2, TimeUnit.SECONDS)).isTrue(); + if (composed) { + initialization = + CompletableFuture.supplyAsync( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + delayedSampleClock, + handoffDeadline, + budget -> { + try (var session = + owner + .forInstallation(delayedSampleClock, budget) + .prepareTimelineInitialization( + preparation, Duration.ofSeconds(30), identity)) { + return session.initialize(permit); + } + }), + executor); + } else { + prepared = + owner + .forHandoffDeadline(delayedSampleClock, handoffDeadline) + .prepareTimelineInitialization(preparation, Duration.ofSeconds(30), identity); + var session = prepared; + initialization = + CompletableFuture.supplyAsync(() -> session.initialize(permit), executor); + } + verify(connection, timeout(1000)).closeAsync(); + verify(commands).time(); + var scriptArguments = org.mockito.ArgumentCaptor.forClass(byte[][].class); + verify(commands, org.mockito.Mockito.times(2)) + .evalsha( + any(), + eq(ScriptOutputType.INTEGER), + any(byte[][].class), + scriptArguments.capture()); + byte[][] probe = scriptArguments.getAllValues().getFirst(); + byte[][] arguments = scriptArguments.getValue(); + assertThat(new String(probe[1], java.nio.charset.StandardCharsets.US_ASCII)) + .isEqualTo("PROBE"); + assertThat(new String(arguments[1], java.nio.charset.StandardCharsets.US_ASCII)) + .isEqualTo("INITIALIZE"); + assertThat(new String(arguments[7], java.nio.charset.StandardCharsets.US_ASCII)) + .isEqualTo("1"); + assertThat(arguments[8]).containsExactly(probe[8]); + long redisDeadline = + Long.parseLong(new String(arguments[8], java.nio.charset.StandardCharsets.US_ASCII)); + assertThat(sampledTime).isTrue(); + assertThat(redisDeadline) + .isBetween( + REDIS_TIME_MILLIS + 1, + REDIS_TIME_MILLIS + handoffBudgetMillis - samplingDelayMillis); + assertThat(initialization.isDone()).isFalse(); + assertThat(background.availablePermits()).isZero(); + assertThat(operations.availablePermits()).isEqualTo(operationMaximum - 2); + + close.complete(null); + assertThat(initialization.get(2, TimeUnit.SECONDS)).isNotNull(); + releaseOtherBackground.countDown(); + assertThat(otherBackground.get(2, TimeUnit.SECONDS)).isTrue(); + assertThat(operations.tryAcquire(operationMaximum, 2, TimeUnit.SECONDS)).isTrue(); + operations.release(operationMaximum); + assertThat(background.tryAcquire(backgroundMaximum, 2, TimeUnit.SECONDS)).isTrue(); + background.release(backgroundMaximum); + verify(connection).closeAsync(); + } finally { + releaseOtherBackground.countDown(); + if (prepared != null) prepared.close(); + close.complete(null); + } + } + } + + private static void stubRedisTime(RedisAsyncCommands commands) throws Exception { + RedisFuture> redisTime = mock(); + when(commands.time()).thenReturn(redisTime); + when(redisTime.get(anyLong(), eq(TimeUnit.MILLISECONDS))) + .thenReturn( + List.of( + "1700000000".getBytes(java.nio.charset.StandardCharsets.US_ASCII), + "123456".getBytes(java.nio.charset.StandardCharsets.US_ASCII))); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void transferReadbackRetainsAdmissionUntilAsyncRedisCloseCompletes(boolean cancelCaller) @@ -338,6 +952,8 @@ void transferReadbackRetainsAdmissionUntilAsyncRedisCloseCompletes(boolean cance try { assertThat(readbackReturned.await(2, TimeUnit.SECONDS)).isTrue(); assertThat(closeStarted.await(2, TimeUnit.SECONDS)).isTrue(); + assertPermitRemainsHeld(operations, operationMaximum); + assertPermitRemainsHeld(background, backgroundMaximum); assertThat(close).isNotDone(); assertThat(caller.isDone()).isFalse(); assertThat(operations.availablePermits()).isEqualTo(operationMaximum - 1); @@ -365,6 +981,13 @@ void transferReadbackRetainsAdmissionUntilAsyncRedisCloseCompletes(boolean cance verify(connection).closeAsync(); } + private static void assertPermitRemainsHeld(Semaphore permits, int maximum) + throws InterruptedException { + boolean acquired = permits.tryAcquire(maximum, 100, TimeUnit.MILLISECONDS); + if (acquired) permits.release(maximum); + assertThat(acquired).isFalse(); + } + @Test void actualOwnerReadReturnsAtDeadlineAndLateAcquisitionNeverExecutes() throws Exception { ConnectionProvider provider = mock(); @@ -731,6 +1354,7 @@ void uncertainProviderReleaseRetainsOnePermitAndExposesItThroughMicrometer(boole var autoCommitFailure = new AtomicReference(); var borrowed = new AtomicReference(); var logicalFinishes = new AtomicInteger(); + var savepoint = mock(java.sql.Savepoint.class); try { assertThatThrownBy(() -> CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackgroundCleanup( @@ -744,6 +1368,12 @@ void uncertainProviderReleaseRetainsOnePermitAndExposesItThroughMicrometer(boole Connection proxy = java.util.Objects.requireNonNull(scoped.acquire()); scoped.acquire(); borrowed.set(proxy); + try { + proxy.rollback(savepoint); + proxy.rollback(); + } catch (java.sql.SQLException failure) { + throw new AssertionError(failure); + } if (!fatalCleanup) { assertThatThrownBy(() -> scoped.release(proxy)) .hasMessage("Controlled uncertain pool return"); @@ -779,7 +1409,8 @@ void uncertainProviderReleaseRetainsOnePermitAndExposesItThroughMicrometer(boole (AtomicInteger) ReflectionTestUtils.getField(captured.get(), "outstandingConnections")) .hasValue(2); - verify(first, never()).rollback(); + verify(first).rollback(savepoint); + verify(first).rollback(); verify(first, never()).setAutoCommit(true); verify(provider).release(first); verify(provider).release(second); 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 825bedea16..9d1ad9b2c2 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 @@ -4003,6 +4003,17 @@ private static ControlledSecondBinding controlledSecondBinding( }) .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 -> { @@ -4012,6 +4023,17 @@ private static ControlledSecondBinding controlledSecondBinding( }) .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)); @@ -4072,7 +4094,7 @@ private static ControlledSecondBinding controlledSecondBinding( .read(Mockito.any(ReadPreseededActorRuntimeReferenceRequest.class)); return new ControlledSecondBinding( new CanonicalGameplayRegionOwnerCompositionFixture.SecondBinding( - secondRequest, currentTarget, entityReferenceClient), + secondRequest, currentTarget, secondWorldRegionResolver, entityReferenceClient), secondWorldRegionResolver); }