From 69335821c767ac81947f20a83ad56f79f9083464 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 01:28:55 +1300 Subject: [PATCH 01/52] Prepare strict Account capacity reservations and bounded recovery --- .../account-service/api-contracts.md | 9 +- .../account-service/runtime-and-data.md | 4 +- .../subscription-management.md | 4 +- .../system-architecture-versioning-runtime.md | 4 +- .../player-access-and-session.md | 16 + protos/account/v1/account_service.proto | 3 + .../v1/tenant_capacity_admission.proto | 70 +++ .../AccountTenantCapacityRepository.java | 247 +++++++++++ .../AccountTenantCapacityWorkloadGuard.java | 69 +++ ...ccountPlayerAdmissionEntitlementOwner.java | 26 +- .../service/AccountTenantCapacityOwner.java | 267 ++++++++++++ .../AccountTenantCapacityRecoveryWorker.java | 398 +++++++++++++++++ .../AccountTenantCapacityGrpcService.java | 128 ++++++ .../V1040__account_tenant_capacity_owner.sql | 321 ++++++++++++++ ...acityMigrationPostgresIntegrationTest.java | 107 +++++ ...titlementOwnerPostgresIntegrationTest.java | 13 + ...tionCompletionPostgresIntegrationTest.java | 326 ++++++++++++++ ...ccountTenantCapacityWorkloadGuardTest.java | 117 +++++ ...ntPlayerAdmissionEntitlementOwnerTest.java | 56 +++ .../AccountTenantCapacityOwnerTest.java | 248 +++++++++++ .../capacity/CapacityAdmissionDigest.java | 188 ++++++++ .../capacity/TenantCapacityAdmission.java | 401 ++++++++++++++++++ .../capacity-admission-v1.schema.json | 19 + .../capacity/CapacityAdmissionDigestTest.java | 165 +++++++ .../CapacityAdmissionTestFixture.java | 285 +++++++++++++ .../capacity-admission-v1-vectors.json | 190 +++++++++ .../test_capacity_admission_vectors.py | 129 ++++++ .../TenantCapacityAdmissionGrpcCodec.java | 228 ++++++++++ .../TenantCapacityAdmissionGrpcCodecTest.java | 149 +++++++ .../client/AccountTenantCapacityClient.java | 94 ++++ .../AccountTenantCapacityClientMtlsTest.java | 164 +++++++ 31 files changed, 4427 insertions(+), 18 deletions(-) create mode 100644 protos/account/v1/tenant_capacity_admission.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java create mode 100644 services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java create mode 100644 services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java create mode 100644 services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java create mode 100644 services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json create mode 100644 services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 578e13c10b..b6d3016057 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -149,7 +149,7 @@ Explicit playtest grants remain partial: registered Account persistence and inte Account has unregistered individual Creator Party, hosted-terms catalog, and individual acceptance storage in V84/V85 through `IndividualCreatorPartyRepository` and `HostedTermsRepository`, with focused repository test sources. These are storage foundations only: authenticated party provisioning and signer verification, operative legal publication, a registered acceptance API/UI, organization acceptance, party transfer, and a commit-bound currentness gate for Game Design writes remain unavailable or unproved. The canonical authority and capability limits are recorded in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. -`CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. +`CommitTenantCapacityAdmission` has a prepared proto RPC, shared strict contract/codec, durable Account evaluation/usage/reservation storage and owner/finalization/recovery code, and a Game Session caller adapter. These components remain unregistered and unqualified for live admission; the [strict tenant-capacity owner tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the supported source boundary, focused proof and remaining producer, physical and runtime gates. The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Current `JoinPublicProductionMembership` receiving returns `AUTH_UNAVAILABLE` before bootstrap/scope, target, entitlement, or membership reads or mutation; the Gateway route is blocked. Current status, preserved positive component obligations, and proof history are in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` before bootstrap or scope validation, replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. @@ -211,8 +211,11 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **target-state internal RPC** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. + +The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. + - `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only. The legacy account-targeted gRPC handler returns `FAILED_PRECONDITION` before parsing selectors or reading Account data because no authorized internal caller is configured; the target tenant-only transport and authorization remain unimplemented. This containment does not change the separately authorized REST/service export path. - `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. - Pending-deletion access is a separate opaque Account credential, not a JWT or normal account session. The non-export deletion-specific routes are `GET /accounts/{accountId}/deletion`, `POST /accounts/{accountId}/deletion/cancel`, and `POST /accounts/{accountId}/deletion/billing-settlement`; each is classified `pending_deletion_scoped` for its exact action and bound to the Account-owned deletion workflow registry. The account export lifecycle is state-dependent but always uses the canonical asynchronous `POST /accounts/{accountId}/exports`, `GET /accounts/{accountId}/exports/{exportId}`, and `GET /accounts/{accountId}/exports/{exportId}/content` resources: active accounts use the ordinary authenticated account subject, while pending-deletion accounts use the pending-deletion credential and `pending_deletion_scoped` classification on that same lifecycle. These target routes are not currently routable. @@ -439,7 +442,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | Security-locked export recovery | `/accounts/{accountId}/exports/**` while the account is `security_locked` | Account-issued `security-lock-export` credential from the Account-owned recovery workflow; no ordinary JWT, pending-deletion credential, or support-only access | Exact global account subject and export-job binding, no tenant selector, single-use initiation and expiring status/content authorization. The credential authorizes only this export lifecycle and cannot restore login, cancel deletion, mutate billing, or enter gameplay. | | Pending-deletion access | `/accounts/{accountId}/deletion`, `/accounts/{accountId}/deletion/cancel`, `/accounts/{accountId}/exports/**`, `/accounts/{accountId}/deletion/billing-settlement` | Opaque `pending-deletion-access` credential through the Account-owned workflow registry | Target-only exact `pending_deletion_scoped` route classification for deletion-specific routes and the canonical asynchronous export lifecycle. Once the account enters pending deletion, this row takes precedence over ordinary control-plane classification: `control-ui` authority is revoked and cannot access export or any other pending-deletion route. | | Internal service gRPC | `Authenticate`, `GetCallerTenantMembership`, `GetTenantMembershipForAccount`, `GetTenantMembershipForRuntime`, `GetTenantEntitlementsForRuntime`, `ListPresenceVisibilityPolicies`, payment and profile gRPC APIs | Authenticated mTLS workload identity plus method-level authorization | Internal service surfaces are not edge-exposed directly; an end-user REST JWT is not a substitute for the declared workload and method contract. Ordinary REST/admin JWTs are validated by the consuming service, not by Gateway; the gameplay-connect JWT is the separate Gateway handshake-validation exception. | -| Target internal capacity RPC | `CommitTenantCapacityAdmission` | Disjunctive method-level caller policy: exact Game Session mTLS identity plus typed `PlayerExecutionContext` and live player-binding checks, or exact World Management mTLS identity plus tenant/operation-bound instance-lifecycle context and live lifecycle checks | Target-only and not present in the current proto or service implementation. | +| Prepared internal capacity RPC | `CommitTenantCapacityAdmission` | Target disjunctive method-level caller policy: exact Game Session mTLS identity plus typed `PlayerExecutionContext` and live player-binding checks, or exact World Management mTLS identity plus tenant/operation-bound instance-lifecycle context and live lifecycle checks | Proto, strict codec, Account ledger/owner and Game Session adapter are prepared but unregistered; live owner/readback qualification and admission remain held. See [strict tenant-capacity owner status](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). | `/auth/login` and `/auth/player-bootstrap` may share the same underlying credential-verification and abuse-policy implementation, but they are separate authentication products. `/auth/login` establishes a `control-ui` control-plane session for admin/creator surfaces; `/auth/player-bootstrap` establishes only the short-lived `player-bootstrap` gameplay-discovery context. Neither endpoint may substitute one profile for the other. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index b2de36b601..0d996fff21 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -80,7 +80,9 @@ Recovery/verification foundations are live. Password-reset completion now uses a Current Account public bootstrap, `IssueDirectTextConnectScope`, `JoinPublicProductionMembership`, and connect-token receiving methods return `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads; the numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; unknown JOIN outcome recovery and Logging receipt receiver/readback remain #2848, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). -The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints compare the complete reservation inventory with usage; eligibility reads and issuer-local counters cannot initialize or replace it. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. + +The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The unregistered canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). No runtime bean, RPC, authenticated caller or signer/registry composition is activated; deployed timing parity remains unproved. diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index ea6dd50a10..3c6ee18739 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -13,7 +13,7 @@ Payment-instrument ownership, explicit per-subscription binding, initial billing ## Implementation Status -The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. Account now has unregistered customer-first-dispatch and exact-customer saved-method owner sources, but these prerequisites do not create a subscription or enable a caller path. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it lacks the caller-supplied stable `requestId`, exact instrument-selection input, and immutable creation-operation identities. Account computes the versioned `requestDigest` from normalized request fields; that digest is not a caller-supplied request field. Account must also resolve the authoritative billing owner, which is not supplied as a request field. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The durable authority/usage ledger and reservation lifecycle for strict capacity admission are also not implemented. +The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. Account now has unregistered customer-first-dispatch and exact-customer saved-method owner sources, but these prerequisites do not create a subscription or enable a caller path. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it lacks the caller-supplied stable `requestId`, exact instrument-selection input, and immutable creation-operation identities. Account computes the versioned `requestDigest` from normalized request fields; that digest is not a caller-supplied request field. Account must also resolve the authoritative billing owner, which is not supplied as a request field. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The strict capacity owner and durable usage/reservation source are locally prepared but remain unregistered and unqualified; see [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The target `CreateSubscription` request accepts a high-entropy stable caller-supplied `requestId` as the sole logical create-operation key, along with the normalized tenant, plan, and instrument-selection inputs. Account resolves the authoritative billing owner and computes a versioned `requestDigest` from those normalized inputs and the resolved owner; neither the digest nor billing-owner resolution is supplied as a request field. Account captures the resolved owner's authority version/generation and validates that exact fence in the same local intent/outbox transaction before persisting the pair or creating provider work; an owner change or generation/version mismatch fails closed. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same `subscriptionId`, durable operation, and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`. The provider `subscription_provisioning_request_id` and cleanup identity remain separate provider-operation keys and must not replace the caller identity. @@ -205,7 +205,7 @@ Downstream services depend on billing events for timely entitlement enforcement, - **Periodic refresh** – even when events are flowing, every healthy runtime consumer must refresh or reconcile cached entitlements at least once per 60 seconds so extended event outages meet the `<=60-second` delayed/missed-event SLA rather than causing unbounded drift. - `CreateSubscription` – Create one hosting subscription for an immutable `tenantId` and initial `plan_code`. The caller supplies a high-entropy stable `requestId`; Account resolves the authoritative billing owner and computes and persists a versioned `requestDigest` from the normalized create tuple, including that owner, immutable `tenantId`, initial `plan_code`, and exact instrument-selection input. The digest and resolved billing owner are not request fields. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same durable operation and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`; the caller identity is distinct from provider operation identities. It rejects an existing `subscriptionId`, expected row version, update operation ID, or any other update-only field. Creation must resolve the authoritative billing owner before its subscription row exists, capture the owner's authority version/generation, authorize the actor against that resolved owner (or require the explicit audited cross-tenant handoff), and require either an explicit saved `paymentInstrumentId` or deterministic instrument-selection input that resolves to exactly one saved instrument owned by that owner. In one local Account transaction, Account locks or CAS-validates the resolved owner and exact captured version/generation before committing the subscription operation, immutable internal `subscriptionId` and `tenantId`, owner, owner fence, customer-operation reference, confirmed provider customer when available, instrument binding and reserved instrument version, `pending` status, immutable `subscription_provisioning_request_id`, separate cleanup/cancellation provider-operation identity, and outbox work item before customer reconciliation or provider creation. An owner-fence mismatch fails closed before any provider operation. The worker may reconcile the customer operation while the row remains pending, but its provisioning claim atomically requires a confirmed matching customer and revalidates ownership, exact instrument version, and attachability; detach racing with provisioning is serialized by that reservation/version boundary and a stale claim fails before Stripe. Creation retries retain the creation identity for lookup; cleanup retries reuse the distinct cleanup identity. Stripe customer and provider defaults are prohibited. -- `CommitTenantCapacityAdmission` – Target Account-owned internal RPC and final capacity fence described above. Its canonical callers are Game Session and World Management; it requires stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by evaluation, bounded `capacityDelta`, and a versioned `mutationDigest` over the attempt identity, fence, and complete payload. An exact identity-and-payload retry replays; any changed bundle version, snapshot/evaluation identity, entitlement field, tuple, cutoff, checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation. The initial attempt needs no rearm CAS. A new attempt requires an Account-owned CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; that CAS advances the fence without creating a second reservation. Stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. It is the only contract that can turn a fresh entitlement snapshot into a strict capacity commitment. Downstream owners cannot replace it with a local compare or cached flag. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – Target Account-owned internal RPC and final capacity fence described above. Its canonical callers are Game Session and World Management; it requires stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by evaluation, bounded `capacityDelta`, and a versioned `mutationDigest` over the attempt identity, fence, and complete payload. An exact identity-and-payload retry replays; any changed bundle version, snapshot/evaluation identity, entitlement field, tuple, cutoff, checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation. The initial attempt needs no rearm CAS. A new attempt requires an Account-owned CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; that CAS advances the fence without creating a second reservation. Stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. It is the only contract that can turn a fresh entitlement snapshot into a strict capacity commitment. Downstream owners cannot replace it with a local compare or cached flag. The shared contract, Account durable owner and private receiver, and Game Session adapter are locally prepared without runtime registration or qualification; current source/proof limits remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `UpdateSubscription` – Apply one plan, instrument, cancellation, or other supported update to an existing immutable `subscriptionId`. Period-end and immediate cancellation both use this mutation; no separate `CancelSubscription` mutation exists. It requires the target subscription identity, a distinct immutable operation-specific request ID, and the expected subscription row version/CAS; it rejects `subscription_provisioning_request_id`, creation-only fields, and any attempted `tenantId` change. Retries reuse the same update identity and guard and never reuse the initial provisioning identity. Provider activation and billing require a confirmed provider subscription ID. Caller-bound tenant variants derive actor identity from auth context; cross-tenant admin variants are separate APIs. - `GetSubscriptionTenantHighLevel` / `ListSubscriptionsTenantHighLevel` – Query subscription state for one tenant, scoped by tenant authorization. - `ListSubscriptionsCrossTenantSupportSafe` – Cross-tenant support-safe high-level listing for troubleshooting only. diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index a43c074d23..a2ae27827c 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -32,7 +32,7 @@ Purge failure status is also not durable in the current implementation: `Finaliz Asset repair now reads and verifies the existing durable version-scoped source snapshot and independently reads the retained export candidate, checks that candidate against the release attestation before writes, and conditionally writes content-addressed objects with exact object readback. Repair does not create a snapshot or candidate. This source implementation does not yet prove physical object-store or PostgreSQL behavior, restart recovery, or a global publication/purge fence; those remain unproved. -Capacity admission is also target-state only. Account's `CommitTenantCapacityAdmission` RPC and both caller integrations (Game Session and World Management) are unimplemented, as are the durable Account authority/usage ledger, the exact `capacityDelta` wire contract, the capacity-admission action-family schema and cross-language `mutationDigest/v1` golden vectors, and the reservation create/finalize/release/reconciliation lifecycle. The capacity-admission sections below are normative contracts and must not be read as evidence that these RPC, caller, ledger, schema/vector, or reservation components exist. +Capacity admission remains unregistered and unqualified. Prepared source, proof definitions and remaining activation gates are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation); the sections below remain normative target contracts rather than runtime qualification. The live Account runtime does not yet produce the complete authority evidence required by recovery and capacity-admission consumers. `roles`, `membershipAuthorityGeneration`, `authorityTuple`, and `outboxCheckpoints` remain target-state fields until Account exposes them together from one authoritative snapshot; these flows must not infer or synthesize them from the current partial response. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#implementation-status) for the owning implementation status. @@ -478,7 +478,7 @@ The serving operation is classified before the read: ### Capacity Delta Wire and Digest Contract -The target `CommitTenantCapacityAdmission` protobuf request declares `capacity_delta` as `optional int64`; its canonical JSON/proto-JSON spelling is `capacityDelta`, represented as a base-10 decimal string. Explicit protobuf presence is mandatory: generated `hasCapacityDelta()`/presence checks must be used, and a missing field, JSON `null`, wrapper message, or implicit scalar default is not the value zero. There is no accepted alternate field or numeric type. The signed wire type is intentional: negative values are representable for diagnostic rejection but are never valid capacity mutations. This is a target-state contract because the current Account proto does not expose this RPC. +The target `CommitTenantCapacityAdmission` protobuf request declares `capacity_delta` as `optional int64`; its canonical JSON/proto-JSON spelling is `capacityDelta`, represented as a base-10 decimal string. Explicit protobuf presence is mandatory: generated `hasCapacityDelta()`/presence checks must be used, and a missing field, JSON `null`, wrapper message, or implicit scalar default is not the value zero. There is no accepted alternate field or numeric type. The signed wire type is intentional: negative values are representable for diagnostic rejection but are never valid capacity mutations. Prepared wire support and remaining qualification are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The logical range is the non-negative signed-`int64` range `0 <= capacityDelta <= 9223372036854775807`, but presence and operation class are separate mandatory checks. An absent `capacityDelta` is always invalid; it must be rejected by Game Session and World Management before calling Account and again by Account before any commitment, reservation, usage mutation, or owner activation CAS. A present zero is valid only after the operation has been classified as eligible entitlement-preserving non-expanding recovery or one-for-one replacement and the complete Account evidence proves that classification; it reserves and changes no usage. A present positive value is valid only for a capacity-creating activation/cutover and must also be no greater than the operation's net requested capacity, available Account quota, and remaining plan entitlement. Account, Game Session, and World Management must apply these same absent/zero/positive rules, rather than relying on a generated getter, a local re-read, or the other caller's validation. Negative values, values outside the signed `int64` wire range, malformed decimal JSON spellings, and any parse or checked-arithmetic overflow are rejected before an Account commitment, reservation, usage mutation, or owner activation CAS. Account must perform checked addition and comparison for usage and quota; it must reject rather than wrap, saturate, narrow, or coerce through a floating-point type. 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 41a3e8d327..06912440a3 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,22 @@ Account initial/current/final creation owners, explicit initial billing-owner co PR #3389 now carries the independent Account source/transport foundation on the supported `develop` runtime. Its unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery do not replace live PLAY authority. This draft PR #3390 retains canonical UUID schema retirement, the public facade/JOIN receiving cutover, initial hosting provider-write source with its focused units, and dependent physical proof; it remains unfinished until a functioning canonical PLAY replacement is qualified. PR #3403 retains private FRESH/World preparation. The source and prior corrections remain preserved through normal ancestry; the changed comparisons do not reset review counts or grant current coverage. No new caller custody, runtime registration, admission or activation is established by the reconstruction. +### 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 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 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. + +Focused local validation on base `2e23db82384efa3221a53633dd43b45c62cd6ecc` passes 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. Physical PostgreSQL migration, fresh-bootstrap, retention/rollback, reservation finalization/release and bounded recovery/quarantine definitions remain unrun; their controlled entitlement and execution readback do not qualify genuine World lifecycle or final admission CAS. + +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 then cleared the Java scopes but was interrupted by denial of the external Harmony CLA link request; external-link validation remains blocked and was not retried. Physical PostgreSQL, concurrency, runtime, admission and finalized-usage retirement remain unrun or held. + +Remaining qualification requires the genuine current Game Session character/session owner binding and final reservation-fenced admission CAS, durable selected-owner activation/readback and Account recovery-client composition, positive fresh-source commitment/rearm concurrency and stale-worker proof, complete finalized-usage retirement on actual runtime teardown, source custody, and fresh packaged runtime proof. No bean, scheduled recovery worker, production route, LOGIN/PLAY change, live provisioning or admission is enabled. The receiving [Account API](../../architecture/microservices/account-service/api-contracts.md) and [runtime storage](../../architecture/microservices/account-service/runtime-and-data.md) retain the canonical target links and local consequences. + +The prepared recovery policy `capacity-recovery/1` retains an immutable observation per current fenced claim, with twelve bounded read attempts and the original reconciliation deadline. Unavailable, invalid, late and ambiguous reads never release the hold. Exhaustion durably quarantines the original reservation, fence, exact payload and full held quota; replay performs no further source call. No operator release, automatic expiry, replacement reservation or unaudited quarantine-resolution API is supplied. The physical fixture includes controlled-source exhaustion/quarantine proof definitions; these remain unrun. Genuine audited Account remediation from independent owner evidence remains an activation prerequisite. + ### Controlled player-admission transport composition The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](https://github.com/benhook1013/FireMUD/blob/c96af5168a9986708e209dfe1b3ffa7f471a49ec/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 56e6a9183f..0d5cc807cb 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -3,12 +3,15 @@ syntax = "proto3"; package account.v1; import "shared/v1/errors.proto"; +import "account/v1/tenant_capacity_admission.proto"; import "shared/v1/player_execution_context.proto"; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; service AccountService { + // Strict capacity owner. Available only through an explicitly composed bounded mTLS receiver. + rpc CommitTenantCapacityAdmission(CommitTenantCapacityAdmissionRequest) returns (CommitTenantCapacityAdmissionResponse); rpc Ping(PingRequest) returns (PingResponse); rpc CreateAccount(CreateAccountRequest) returns (CreateAccountResponse); rpc Authenticate(AuthenticateRequest) returns (AuthenticateResponse); diff --git a/protos/account/v1/tenant_capacity_admission.proto b/protos/account/v1/tenant_capacity_admission.proto new file mode 100644 index 0000000000..973bb17cc1 --- /dev/null +++ b/protos/account/v1/tenant_capacity_admission.proto @@ -0,0 +1,70 @@ +syntax = "proto3"; +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Singleton repeated envelopes preserve multiplicity for the strict bounded codec. +message TenantCapacityShape { + repeated int64 active_sessions = 1; + repeated int64 concurrent_game_instances = 2; + repeated int64 storage_bytes = 3; +} +// Exact PlayerExecutionContext content with strict singleton multiplicity preserved on this wire. +message TenantCapacityPlayerContext { + repeated string account_id = 1; + repeated string tenant_id = 2; + repeated string playable_state_namespace_id = 3; + repeated string game_instance_id = 4; + repeated string character_id = 5; + repeated string session_id = 6; + repeated string realm_id = 7; + repeated string request_id = 8; + repeated string playable_state_scope = 9; +} +message TenantCapacityWorldContext { + repeated string tenant_id = 1; + repeated string operation_id = 2; + repeated string lifecycle_id = 3; + repeated string game_instance_id = 4; + repeated string owner_id = 5; + repeated int64 owner_fence = 6; +} +message TenantCapacityAdmissionAttempt { + repeated string tenant_id = 1; + repeated string request_id = 2; + repeated string admission_id = 3; + repeated string admission_attempt_id = 4; + repeated int64 capacity_rearm_fence = 5; + repeated string target_namespace = 6; + // Exactly one typed alternative, never a caller-supplied workload identity. + repeated TenantCapacityPlayerContext player_context = 7; + repeated TenantCapacityWorldContext world_context = 8; + repeated string operation = 9; + repeated TenantCapacityShape prior_shape = 10; + repeated TenantCapacityShape requested_shape = 11; + // Exact existing Account canonical bundle; content parsing cannot register its authority. + repeated bytes canonical_account_evidence = 12; + repeated string mutation_digest = 13; +} +message CommitTenantCapacityAdmissionRequest { + repeated TenantCapacityAdmissionAttempt attempt = 1; + // Mandatory presence. Proto JSON is a canonical base-10 decimal string, not a JSON number. + optional int64 capacity_delta = 2; +} +message TenantCapacityAdmissionCommitment { + repeated string tenant_id = 1; + repeated string request_id = 2; + repeated string admission_id = 3; + repeated string admission_attempt_id = 4; + repeated int64 capacity_rearm_fence = 5; + repeated string mutation_digest = 6; + repeated string reservation_id = 7; + repeated int64 reservation_fence = 8; + repeated string expires_at = 9; + repeated string state = 10; + repeated string snapshot_identity = 11; + repeated string evaluation_identity = 12; +} +message CommitTenantCapacityAdmissionResponse { + repeated TenantCapacityAdmissionCommitment commitment = 1; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java new file mode 100644 index 0000000000..90e392668f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -0,0 +1,247 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-local primitives only, always in the owning writable transaction. No bean or seed API. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private owner transaction collaborator.") +public final class AccountTenantCapacityRepository { + private final DSLContext dsl; + + public AccountTenantCapacityRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Called by the actual Account player evaluator before its final source transaction commits. */ + public void retainPlayerEvaluation(RuntimePlayerAdmissionEntitlementEvidence source) { + retain(Evidence.player(source)); + } + + private void retain(Evidence evidence) { + transaction(); + int inserted = + dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations " + + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (evaluation_identity) DO NOTHING", + evidence.evaluationIdentity(), + evidence.snapshotIdentity(), + evidence.tenantId(), + evidence.callerWorkload(), + evidence.owner().service(), + evidence.canonicalBytes(), + at(evidence.evaluatedAt()), + at(evidence.expiresAt())); + if (inserted != 0 && inserted != 1) throw unavailable(); + requireRetained(evidence); + } + + public void requireRetained(Evidence evidence) { + transaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ? FOR SHARE", + evidence.evaluationIdentity()); + if (row == null + || !evidence.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !evidence.snapshotIdentity().equals(row.get("snapshot_identity", String.class)) + || !evidence.callerWorkload().equals(row.get("caller_workload", String.class)) + || !evidence.owner().service().equals(row.get("owner_service", String.class)) + || !Arrays.equals(evidence.canonicalBytes(), row.get("canonical_evidence", byte[].class)) + || !evidence + .evaluatedAt() + .truncatedTo(java.time.temporal.ChronoUnit.MICROS) + .equals(time(row, "evaluated_at")) + || !evidence + .expiresAt() + .truncatedTo(java.time.temporal.ChronoUnit.MICROS) + .equals(time(row, "expires_at"))) throw unavailable(); + } + + public Record find(Identity id) { + transaction(); + return dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? FOR UPDATE", + id.tenantId(), + id.requestId(), + id.admissionId()); + } + + public Record usage(Request request) { + transaction(); + Record usage = + dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = ? FOR UPDATE", + request.identity().tenantId(), + request.context().owner().service()); + if (usage == null) throw unavailable(); + return usage; + } + + public Result exact(Request request, Record row) { + if (!request.mutationDigest().equals(row.get("mutation_digest", String.class)) + || !request.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class)) + || request.capacityRearmFence() != number(row, "capacity_rearm_fence") + || !Arrays.equals( + CapacityAdmissionDigest.preimage(request), row.get("canonical_payload", byte[].class)) + || !request.evidence().callerWorkload().equals(row.get("caller_workload", String.class))) + throw conflict(); + return result(row); + } + + public void requirePriorHistory(Request prior, Request next) { + transaction(); + if (!prior.identity().equals(next.identity()) + || prior.admissionAttemptId().equals(next.admissionAttemptId()) + || next.capacityRearmFence() != Math.incrementExact(prior.capacityRearmFence())) + throw conflict(); + Record history = + dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_attempt_history WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? FOR SHARE", + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId()); + if (history == null + || number(history, "capacity_rearm_fence") != prior.capacityRearmFence() + || !prior.mutationDigest().equals(history.get("mutation_digest", String.class)) + || !Arrays.equals( + CapacityAdmissionDigest.preimage(prior), history.get("canonical_payload", byte[].class)) + || history.get("owner_readback", byte[].class) == null) throw conflict(); + } + + public Result create(Request request, Instant expiresAt) { + Record usage = usage(request); + long delta = Objects.requireNonNull(request.capacityDelta()); + long occupied = Math.addExact(number(usage, "held_units"), number(usage, "used_units")); + long after = Math.addExact(occupied, delta); + if (after > request.evidence().quota()) throw quota(); + long held = Math.addExact(number(usage, "held_units"), delta); + updateUsage(request, usage, held, number(usage, "used_units")); + int created = + dsl.execute( + "INSERT INTO account_tenant_capacity_reservations " + + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, admission_attempt_id, capacity_rearm_fence, reservation_fence, mutation_digest, canonical_payload, evaluation_identity, capacity_delta, expires_at, reconcile_deadline, state, execution_status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'RESERVED', 'OWNER_EXECUTION_PENDING')", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + UUID.randomUUID(), + request.context().owner().service(), + request.evidence().callerWorkload(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + CapacityAdmissionDigest.preimage(request), + request.evidence().evaluationIdentity(), + delta, + at(expiresAt), + at(expiresAt.plusSeconds(60))); + if (created != 1) throw unavailable(); + return exact(request, Objects.requireNonNull(find(request.identity()))); + } + + public void updateUsage(Request request, Record before, long held, long used) { + transaction(); + if (held < 0 || used < 0 || Math.addExact(held, used) < 0) throw unavailable(); + long revision = number(before, "usage_revision"); + int updated = + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = ?, used_units = ?, usage_revision = ? WHERE tenant_uuid = ? AND owner_service = ? AND usage_revision = ?", + held, + used, + Math.incrementExact(revision), + request.identity().tenantId(), + request.context().owner().service(), + revision); + if (updated != 1) throw unavailable(); + } + + public Result result(Record row) { + transaction(); + Record evaluation = + dsl.fetchOne( + "SELECT snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + row.get("evaluation_identity", String.class)); + if (evaluation == null) throw unavailable(); + return new Result( + new Identity( + row.get("tenant_uuid", UUID.class), + row.get("request_id", UUID.class), + row.get("admission_id", UUID.class)), + row.get("admission_attempt_id", UUID.class), + number(row, "capacity_rearm_fence"), + row.get("mutation_digest", String.class), + row.get("reservation_id", UUID.class), + number(row, "reservation_fence"), + time(row, "expires_at"), + State.valueOf(row.get("state", String.class)), + evaluation.get("snapshot_identity", String.class), + row.get("evaluation_identity", String.class)); + } + + public static long number(Record row, String name) { + Long value = row.get(name, Long.class); + if (value == null || value < 0) throw unavailable(); + return value; + } + + public static Instant time(Record row, String name) { + OffsetDateTime value = row.get(name, OffsetDateTime.class); + if (value == null) throw unavailable(); + return value.toInstant(); + } + + public static OffsetDateTime at(Instant instant) { + return instant.truncatedTo(java.time.temporal.ChronoUnit.MICROS).atOffset(ZoneOffset.UTC); + } + + public static void transaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw unavailable(); + } + + public static CapacityException conflict() { + return new CapacityException("IDEMPOTENCY_CONFLICT"); + } + + public static CapacityException unavailable() { + return new CapacityException("ENTITLEMENT_UNAVAILABLE"); + } + + public static CapacityException quota() { + return new CapacityException("TENANT_BILLING_BLOCKED"); + } + + public static final class CapacityException extends IllegalStateException { + private final String code; + + public CapacityException(String code) { + super(code); + this.code = code; + } + + public String code() { + return code; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java new file mode 100644 index 0000000000..88e1694a6f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.accountservice.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.util.Set; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Sole producer of the receiver's private exact-method TLS caller assertion. */ +public final class AccountTenantCapacityWorkloadGuard implements ServerInterceptor { + private final Context.Key caller = Context.key("tenant-capacity-authenticated-peer"); + private final Set allowed; + + public AccountTenantCapacityWorkloadGuard(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + allowed = + Set.of( + TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION), + TenantCapacityAdmission.expectedWorkload(namespace, Owner.WORLD_MANAGEMENT)); + } + + public String requireAuthenticatedCaller() { + String value = caller.get(); + if (!allowed.contains(value == null ? "" : value) || ambient()) + throw Status.UNAUTHENTICATED.asRuntimeException(); + return value; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + var peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); + if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); + if (ambient() + || !allowed.contains(peer.orElseThrow().uri()) + || !AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() + .getFullMethodName() + .equals(call.getMethodDescriptor().getFullMethodName())) + return deny(call, Status.PERMISSION_DENIED); + return Contexts.interceptCall( + Context.current().withValue(caller, peer.orElseThrow().uri()), call, headers, next); + } + + private static boolean ambient() { + return SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + private static ServerCall.Listener deny( + ServerCall call, Status status) { + call.close( + status.withDescription("Exact capacity owner workload and method required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index 3fd6669121..3f84927d2b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -555,7 +555,7 @@ private static void requireSupportedTarget( || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) throw unavailable(); } - private static RuntimePlayerAdmissionEntitlementEvidence capture( + private RuntimePlayerAdmissionEntitlementEvidence capture( Request request, CurrentPlayer player, PublishedRealmEvidence target, @@ -614,15 +614,21 @@ private static RuntimePlayerAdmissionEntitlementEvidence capture( RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); sources.put("worldCaptureId", world.captureId().toString()); sources.put("worldRowVersion", Long.toString(world.rowVersion())); - return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - request.requestId(), - request.authenticatedCallerWorkload(), - request.connectScopeId(), - player.snapshot(), - binding, - facts, - sources, - time); + var evidence = + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + request.requestId(), + request.authenticatedCallerWorkload(), + request.connectScopeId(), + player.snapshot(), + binding, + facts, + sources, + time); + // Retain only inside this actual evaluator's final source transaction. A supplied bundle + // cannot register itself as capacity authority, and commit failure returns no evidence. + new net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository(dsl) + .retainPlayerEvaluation(evidence); + return evidence; } private static Map facts( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java new file mode 100644 index 0000000000..2e5d350338 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -0,0 +1,267 @@ +package net.firedevops.firemud.accountservice.service; + +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.number; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.time.Clock; +import java.time.Instant; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +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.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered strict Account capacity authority. Caller identity must come from the bounded mTLS + * receiver. No caller can register a bundle, initialize usage, attest an execution result, or cause + * a final Game Session/World activation here. World capacity remains held without its current + * lifecycle/evaluation producer. The scalar shape is deliberately restricted to an exact new player + * binding; non-expanding recovery stays held until Account has authoritative prior-shape evidence. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private Account owner collaborators.") +public final class AccountTenantCapacityOwner { + private final DSLContext dsl; + private final AccountRepository accounts; + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships; + private final AccountGameplayDelegationIssuanceRepository issuances; + private final AccountConnectScopeRepository scopes; + private final AccountTenantCapacityRepository capacity; + private final TransactionTemplate transaction; + private final Clock clock; + private final String namespace; + + public AccountTenantCapacityOwner( + DSLContext dsl, + AccountRepository accounts, + AccountCanonicalRuntimeMembershipSnapshotRepository memberships, + AccountGameplayDelegationIssuanceRepository issuances, + AccountConnectScopeRepository scopes, + PlatformTransactionManager transactions, + Clock clock, + String namespace) { + this.dsl = Objects.requireNonNull(dsl); + this.accounts = Objects.requireNonNull(accounts); + this.memberships = Objects.requireNonNull(memberships); + this.issuances = Objects.requireNonNull(issuances); + this.scopes = Objects.requireNonNull(scopes); + this.capacity = new AccountTenantCapacityRepository(dsl); + this.clock = Objects.requireNonNull(clock); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setTimeout(5); + } + + public Result commit(Request request, String authenticatedCaller) { + requireCaller(request, authenticatedCaller); + request.requireCommittable(); + return inTransaction( + () -> { + lockPlayerAccount(request); + Record existing = capacity.find(request.identity()); + // Replay/conflict is resolved before current-source reads and any usage write. + if (existing != null) return capacity.exact(request, existing); + if (request.capacityRearmFence() != 1) throw conflict(); + current(request); + requireSupportedShape(request); + return capacity.create(request, request.evidence().expiresAt()); + }); + } + + /** Only the Account-owned recovery worker calls this after storing terminal no-commit proof. */ + Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { + prior.requireCommittable(); + next.requireCommittable(); + if (!prior.identity().equals(next.identity()) + || prior.admissionAttemptId().equals(next.admissionAttemptId()) + || next.capacityRearmFence() != Math.incrementExact(prior.capacityRearmFence()) + || !prior.context().equals(next.context()) + || prior.operation() != next.operation() + || !prior.priorShape().equals(next.priorShape()) + || !prior.requestedShape().equals(next.requestedShape()) + || !Objects.equals(prior.capacityDelta(), next.capacityDelta()) + || !Objects.equals( + prior.evidence().fields().get("authorityTuple"), + next.evidence().fields().get("authorityTuple"))) throw conflict(); + return inTransaction( + () -> { + lockPlayerAccount(next); + Record row = capacity.find(prior.identity()); + if (row == null) throw conflict(); + if (next.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class))) { + capacity.requirePriorHistory(prior, next); + return capacity.exact(next, row); + } + capacity.exact(prior, row); + requireClaim(row, recoveryOwner, claimFence, clock.instant()); + if (!"RESERVED".equals(row.get("state", String.class)) + || !"NOT_EXECUTED_AFTER_AUTHORIZATION" + .equals(row.get("execution_status", String.class)) + || row.get("owner_readback", byte[].class) == null) throw conflict(); + current(next); + requireSupportedShape(next); + int history = + dsl.execute( + "INSERT INTO account_tenant_capacity_attempt_history " + + "(tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId(), + prior.capacityRearmFence(), + prior.mutationDigest(), + CapacityAdmissionDigest.preimage(prior), + row.get("owner_readback", byte[].class)); + if (history != 1) throw unavailable(); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, capacity_rearm_fence = ?, reservation_fence = ?, mutation_digest = ?, canonical_payload = ?, evaluation_identity = ?, expires_at = ?, reconcile_deadline = ?, next_reconcile_at = NULL, recovery_attempt_count = 0, execution_status = 'OWNER_EXECUTION_PENDING', owner_readback = NULL, owner_readback_digest = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND capacity_rearm_fence = ? AND mutation_digest = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", + next.admissionAttemptId(), + next.capacityRearmFence(), + Math.incrementExact(number(row, "reservation_fence")), + next.mutationDigest(), + CapacityAdmissionDigest.preimage(next), + next.evidence().evaluationIdentity(), + at(next.evidence().expiresAt()), + at(next.evidence().expiresAt().plusSeconds(60)), + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId(), + prior.capacityRearmFence(), + prior.mutationDigest(), + recoveryOwner, + claimFence); + if (changed != 1) throw conflict(); + // Reservation identity and both usage columns are deliberately untouched. + return capacity.exact(next, Objects.requireNonNull(capacity.find(next.identity()))); + }); + } + + private void current(Request request) { + Instant now = clock.instant(); + request.evidence().requireCurrent(now); + // PostgreSQL stores microseconds. Floor the bound, never round an expiry forward. + if (!now.isBefore( + request.evidence().expiresAt().truncatedTo(java.time.temporal.ChronoUnit.MICROS))) + throw unavailable(); + capacity.requireRetained(request.evidence()); + if (!(request.context() instanceof PlayerContext player)) throw unavailable(); + var parsed = + RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( + request.evidence().canonicalBytes()); + var current = memberships.readCurrent(player.accountId(), request.identity().tenantId()); + if (!current.equals(parsed.membershipSource()) + || !current.membershipExists() + || !current.gameplayAdmissionAllowed() + || !"ACTIVE".equals(current.membershipLifecycleState())) throw unavailable(); + var fields = request.evidence().fields(); + if (!(fields.get("sourceReferences") instanceof Map source)) throw unavailable(); + var issuance = + issuances + .readCurrentCommittedCandidateByJti( + UUID.fromString((String) source.get("callerTokenJti"))) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + if (!issuance.identity().accountId().equals(player.accountId()) + || !issuance.identity().callerWorkload().equals(request.evidence().callerWorkload()) + || !issuance.identity().callerContextId().toString().equals(source.get("callerContextId")) + || !issuance.identity().operationId().toString().equals(source.get("callerOperationId")) + || !issuance.tokenSha256().equals(source.get("callerTokenSha256")) + || !issuance + .canonicalRegistryRecordSha256() + .equals(source.get("callerRegistryRecordSha256")) + || !issuance.commitProofSha256().equals(source.get("callerCommitProofSha256")) + || now.getEpochSecond() < issuance.identity().notBeforeEpochSecond() + || now.getEpochSecond() >= issuance.identity().expiresAtEpochSecond()) throw unavailable(); + String connect = (String) fields.get("verifiedConnectScopeId"); + var scope = + scopes + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(connect)) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + if (!scope.accountUuid().equals(player.accountId()) + || !scope.tenantUuid().equals(player.tenantId()) + || !scope.scopeDigest().equals(source.get("scopeDigest")) + || !scope.gameInstanceUuid().equals(player.gameInstanceId()) + || !scope.playableStateNamespaceUuid().equals(player.playableStateNamespaceId()) + || !scope.realmId().equals(player.realmId()) + || !scope.playableStateScope().equals(player.playableStateScope()) + || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) throw unavailable(); + } + + private static void requireSupportedShape(Request request) { + if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION + || request.operation() != TenantCapacityAdmission.Operation.CAPACITY_CREATING + || !request.priorShape().equals(new TenantCapacityAdmission.Shape(0, 0, 0)) + || !request.requestedShape().equals(new TenantCapacityAdmission.Shape(1, 0, 0)) + || !Long.valueOf(1).equals(request.capacityDelta())) throw unavailable(); + } + + private void lockPlayerAccount(Request request) { + if (!(request.context() instanceof PlayerContext player)) throw unavailable(); + accounts + .findByAccountUuidForUpdate(player.accountId()) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + } + + private void requireCaller(Request request, String caller) { + if (request == null + || !namespace.equals(request.targetNamespace()) + || !TenantCapacityAdmission.expectedWorkload(namespace, request.context().owner()) + .equals(caller) + || !request.evidence().callerWorkload().equals(caller)) throw unavailable(); + } + + static void requireClaim(Record row, UUID owner, long fence, Instant now) { + if (owner == null + || !owner.equals(row.get("recovery_owner", UUID.class)) + || fence != number(row, "recovery_claim_fence") + || !now.isBefore(AccountTenantCapacityRepository.time(row, "recovery_claim_expires_at"))) + throw conflict(); + } + + T inTransaction(Supplier action) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + return Objects.requireNonNull( + transaction.execute( + status -> { + AccountTenantCapacityRepository.transaction(); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() + != Connection.TRANSACTION_SERIALIZABLE) throw unavailable(); + }); + return action.get(); + })); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java new file mode 100644 index 0000000000..8f9bfc0835 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java @@ -0,0 +1,398 @@ +package net.firedevops.firemud.accountservice.service; + +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.number; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** + * Unregistered Account reservation recovery. Only this owner mutates reservation outcomes. Its + * protected selected-owner read client is a required dependency, not an automatically registered + * source or a caller-supplied attestation. There is deliberately no runtime implementation until + * selected owners expose exact durable activation-CAS readback. No timeout synthesizes no-commit. + */ +@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Private owner/source collaborators.") +public final class AccountTenantCapacityRecoveryWorker { + public enum Disposition { + COMMITTED, + NOT_EXECUTED_AFTER_AUTHORIZATION, + INDETERMINATE + } + + public enum NoCommitAction { + RETAIN_FOR_REARM, + RELEASE + } + + /** + * An implementation must use the exact selected owner's authenticated mTLS readback and validate + * its current owner fence and authoritative state, including durable original-attempt rejection + * and no mutation for NOT_EXECUTED_AFTER_AUTHORIZATION. Content construction is not authority. + * FENCE_REJECTED, FAILED, pending and ambiguous responses map only to INDETERMINATE. + */ + public interface ExecutionReadClient { + Observation readExact(Request request, Result reservation, Instant deadline); + } + + public record Observation( + String authenticatedOwnerWorkload, + Result reservation, + byte[] canonicalAttemptPayload, + Disposition disposition, + UUID proofId, + long currentOwnerFence, + String authoritativeStateDigest, + byte[] canonicalOwnerReadback) { + public Observation { + Objects.requireNonNull(reservation); + Objects.requireNonNull(disposition); + TenantCapacityAdmission.uuid(proofId); + if (authenticatedOwnerWorkload == null + || currentOwnerFence <= 0 + || authoritativeStateDigest == null + || !authoritativeStateDigest.matches("sha256:[0-9a-f]{64}") + || canonicalAttemptPayload == null + || canonicalAttemptPayload.length == 0 + || canonicalAttemptPayload.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES + || canonicalOwnerReadback == null + || canonicalOwnerReadback.length == 0 + || canonicalOwnerReadback.length > 256 * 1024) + throw new IllegalArgumentException("Complete owner readback required"); + canonicalAttemptPayload = canonicalAttemptPayload.clone(); + canonicalOwnerReadback = canonicalOwnerReadback.clone(); + } + + @Override + public byte[] canonicalAttemptPayload() { + return canonicalAttemptPayload.clone(); + } + + @Override + public byte[] canonicalOwnerReadback() { + return canonicalOwnerReadback.clone(); + } + + @Override + public String toString() { + return "CapacityOwnerObservation[redacted]"; + } + } + + private final AccountTenantCapacityOwner owner; + private final DSLContext dsl; + private final AccountTenantCapacityRepository capacity; + private final ExecutionReadClient source; + private final Clock clock; + private final UUID workerId = UUID.randomUUID(); + + public AccountTenantCapacityRecoveryWorker( + AccountTenantCapacityOwner owner, DSLContext dsl, ExecutionReadClient source, Clock clock) { + this.owner = Objects.requireNonNull(owner); + this.dsl = Objects.requireNonNull(dsl); + this.capacity = new AccountTenantCapacityRepository(dsl); + this.source = Objects.requireNonNull(source); + this.clock = Objects.requireNonNull(clock); + } + + /** Twelve bounded observations or the original deadline quarantine the same complete hold. */ + public Result reconcile(Request request, NoCommitAction noCommitAction) { + Objects.requireNonNull(noCommitAction); + request.requireCommittable(); + Claim claim = claim(request); + if (claim.reservation().state() != State.RESERVED) return claim.reservation(); + if (claim.noCommitProof() != null) { + if (noCommitAction == NoCommitAction.RETAIN_FOR_REARM) return claim.reservation(); + return owner.inTransaction( + () -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result current = capacity.exact(request, row); + AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); + if (!current.equals(claim.reservation()) + || !"NOT_EXECUTED_AFTER_AUTHORIZATION" + .equals(row.get("execution_status", String.class)) + || !Arrays.equals(claim.noCommitProof(), row.get("owner_readback", byte[].class))) + throw conflict(); + moveUsage(request, false); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = 'RELEASED', reservation_fence = ?, next_reconcile_at = NULL WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", + Math.incrementExact(current.reservationFence()), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + workerId, + claim.fence()); + if (changed != 1) throw conflict(); + return capacity.exact( + request, Objects.requireNonNull(capacity.find(request.identity()))); + }); + } + Observation candidate = null; + byte[] candidateProof = null; + if (claim.attempts() < 12 && clock.instant().isBefore(claim.reconcileDeadline())) { + Instant deadline = clock.instant().plusSeconds(5); + if (claim.reconcileDeadline().isBefore(deadline)) deadline = claim.reconcileDeadline(); + try { + candidate = source.readExact(request, claim.reservation(), deadline); + if (!clock.instant().isBefore(deadline)) throw unavailable(); + requireExactSource(request, claim.reservation(), candidate); + candidateProof = proof(request, candidate); + } catch (RuntimeException unavailableSource) { + // Missing, malformed, late and failed reads are indeterminate, never no-commit proof. + candidate = null; + candidateProof = null; + } + } + final Observation observed = candidate; + final byte[] exactProof = candidateProof; + return owner.inTransaction( + () -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result current = capacity.exact(request, row); + AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); + if (!current.equals(claim.reservation())) throw conflict(); + int attempt = Math.incrementExact(Math.toIntExact(number(row, "recovery_attempt_count"))); + if (attempt > 12) throw unavailable(); + Instant now = clock.instant(); + boolean indeterminate = + observed == null || observed.disposition() == Disposition.INDETERMINATE; + boolean quarantine = + indeterminate && (attempt == 12 || !now.isBefore(claim.reconcileDeadline())); + String outcome = + quarantine + ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() + : observed == null ? "SOURCE_UNAVAILABLE" : observed.disposition().name(); + int retained = + dsl.execute( + "INSERT INTO account_tenant_capacity_recovery_evidence (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, recovery_policy_version, recovery_attempt_number, observed_at, outcome, canonical_readback, readback_digest) VALUES (?, ?, ?, ?, ?, 'capacity-recovery/1', ?, ?, ?, ?, ?)", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.admissionAttemptId(), + claim.fence(), + attempt, + at(now), + outcome, + exactProof, + exactProof == null ? null : sha256(exactProof)); + if (retained != 1) throw unavailable(); + if (indeterminate) { + int updated = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_attempt_count = ?, state = ?, recovery_escalated_at = ?, next_reconcile_at = ? WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", + attempt, + quarantine + ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() + : State.RESERVED.name(), + quarantine ? at(now) : null, + quarantine + ? null + : at( + now.plusSeconds(5).isBefore(claim.reconcileDeadline()) + ? now.plusSeconds(5) + : claim.reconcileDeadline()), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + workerId, + claim.fence()); + if (updated != 1) throw conflict(); + return capacity.exact( + request, Objects.requireNonNull(capacity.find(request.identity()))); + } + boolean committed = observed.disposition() == Disposition.COMMITTED; + State next = + committed + ? State.FINALIZED + : noCommitAction == NoCommitAction.RELEASE ? State.RELEASED : State.RESERVED; + if (committed || next == State.RELEASED) moveUsage(request, committed); + long reservationFence = + next == State.RELEASED + ? Math.incrementExact(current.reservationFence()) + : current.reservationFence(); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = ?, execution_status = ?, owner_readback = ?, owner_readback_digest = ?, reservation_fence = ?, recovery_attempt_count = ?, next_reconcile_at = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND mutation_digest = ? AND reservation_fence = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", + next.name(), + committed ? "COMMITTED" : "NOT_EXECUTED_AFTER_AUTHORIZATION", + exactProof, + sha256(exactProof), + reservationFence, + attempt, + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.admissionAttemptId(), + request.mutationDigest(), + current.reservationFence(), + workerId, + claim.fence()); + if (changed != 1) throw conflict(); + return capacity.exact(request, Objects.requireNonNull(capacity.find(request.identity()))); + }); + } + + private void moveUsage(Request request, boolean committed) { + Record usage = capacity.usage(request); + long delta = Objects.requireNonNull(request.capacityDelta()); + capacity.updateUsage( + request, + usage, + Math.subtractExact(number(usage, "held_units"), delta), + committed + ? Math.addExact(number(usage, "used_units"), delta) + : number(usage, "used_units")); + } + + public Result rearm(Request prior, Request next) { + prior.requireCommittable(); + next.requireCommittable(); + java.util.Optional replay = + owner.inTransaction( + () -> { + Record row = capacity.find(next.identity()); + if (row != null + && next.admissionAttemptId() + .equals(row.get("admission_attempt_id", UUID.class))) { + capacity.requirePriorHistory(prior, next); + return java.util.Optional.of(capacity.exact(next, row)); + } + return java.util.Optional.empty(); + }); + if (replay.isPresent()) return replay.orElseThrow(); + Claim claim = claim(prior); + return owner.rearm(prior, next, workerId, claim.fence()); + } + + private Claim claim(Request request) { + return owner.inTransaction( + () -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result result = capacity.exact(request, row); + if (result.state() != State.RESERVED) + return new Claim( + result, + number(row, "recovery_claim_fence"), + Math.toIntExact(number(row, "recovery_attempt_count")), + AccountTenantCapacityRepository.time(row, "reconcile_deadline"), + row.get("owner_readback", byte[].class)); + Instant now = clock.instant(); + if (row.get("recovery_owner", UUID.class) != null + && !workerId.equals(row.get("recovery_owner", UUID.class)) + && now.isBefore( + AccountTenantCapacityRepository.time(row, "recovery_claim_expires_at"))) + throw unavailable(); + long fence = Math.incrementExact(number(row, "recovery_claim_fence")); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = ?, recovery_claim_expires_at = ?, next_reconcile_at = LEAST(?, reconcile_deadline) " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_claim_fence = ?", + workerId, + fence, + at(now.plusSeconds(15)), + at(now.plusSeconds(5)), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + number(row, "recovery_claim_fence")); + if (changed != 1) throw conflict(); + return new Claim( + result, + fence, + Math.toIntExact(number(row, "recovery_attempt_count")), + AccountTenantCapacityRepository.time(row, "reconcile_deadline"), + row.get("owner_readback", byte[].class)); + }); + } + + private static void requireExactSource(Request request, Result expected, Observation observed) { + if (observed == null + || !expected.equals(observed.reservation()) + || !TenantCapacityAdmission.expectedWorkload( + request.targetNamespace(), request.context().owner()) + .equals(observed.authenticatedOwnerWorkload()) + || !Arrays.equals( + CapacityAdmissionDigest.preimage(request), observed.canonicalAttemptPayload())) + throw unavailable(); + } + + private static byte[] proof(Request request, Observation observed) { + // Fixed content binding includes the entire attempt and exact owner readback, not a boolean. + var output = new java.io.ByteArrayOutputStream(); + for (byte[] bytes : + new byte[][] { + "account-capacity-owner-readback/v1".getBytes(java.nio.charset.StandardCharsets.US_ASCII), + CapacityAdmissionDigest.preimage(request), + observed + .reservation() + .reservationId() + .toString() + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + Long.toString(observed.reservation().reservationFence()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed + .authenticatedOwnerWorkload() + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.disposition().name().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.proofId().toString().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + Long.toString(observed.currentOwnerFence()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.authoritativeStateDigest().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.canonicalOwnerReadback() + }) { + output.writeBytes( + Integer.toString(bytes.length).getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + byte[] proof = output.toByteArray(); + if (proof.length > 1024 * 1024) throw unavailable(); + return proof; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + private record Claim( + Result reservation, + long fence, + int attempts, + Instant reconcileDeadline, + byte[] noCommitProof) { + private Claim { + noCommitProof = noCommitProof == null ? null : noCommitProof.clone(); + } + + @Override + public byte[] noCommitProof() { + return noCommitProof == null ? null : noCommitProof.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java new file mode 100644 index 0000000000..0c3784b27b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import com.google.protobuf.Any; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.protobuf.StatusProto; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Objects; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit private composition only. Other Account RPCs remain UNIMPLEMENTED on this server. */ +public final class AccountTenantCapacityGrpcService + extends AccountServiceGrpc.AccountServiceImplBase { + private final AccountTenantCapacityOwner owner; + private final AccountTenantCapacityWorkloadGuard guard; + + public AccountTenantCapacityGrpcService(AccountTenantCapacityOwner owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + guard = new AccountTenantCapacityWorkloadGuard(namespace); + } + + public Server createUnregisteredServer( + String address, KeyManagerFactory keys, TrustManagerFactory trust) { + var factory = + new BoundedGrpcServerFactory( + Objects.requireNonNull(address), + List.of(), + Objects.requireNonNull(keys), + Objects.requireNonNull(trust), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES); + factory.addService(ServerInterceptors.interceptForward(this, guard)); + return factory.createServer(); + } + + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String peer; + try { + peer = guard.requireAuthenticatedCaller(); + } catch (StatusRuntimeException denied) { + fail(observer, denied.getStatus(), "AUTH_UNAVAILABLE"); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail(observer, Status.FAILED_PRECONDITION, "ENTITLEMENT_UNAVAILABLE"); + return; + } + final net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request; + try { + request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + } catch (IllegalArgumentException | ArithmeticException invalid) { + fail(observer, Status.INVALID_ARGUMENT, "INVALID_ARGUMENT"); + return; + } + if (!request.evidence().callerWorkload().equals(peer)) { + fail(observer, Status.PERMISSION_DENIED, "AUTH_UNAVAILABLE"); + return; + } + final CommitTenantCapacityAdmissionResponse result; + try { + result = TenantCapacityAdmissionGrpcCodec.toResponse(request, owner.commit(request, peer)); + } catch (CapacityException denied) { + fail( + observer, + "IDEMPOTENCY_CONFLICT".equals(denied.code()) + ? Status.ALREADY_EXISTS + : "TENANT_BILLING_BLOCKED".equals(denied.code()) + ? Status.RESOURCE_EXHAUSTED + : Status.UNAVAILABLE, + denied.code()); + return; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException unavailable) { + fail(observer, Status.UNAVAILABLE, "ENTITLEMENT_UNAVAILABLE"); + return; + } catch (IllegalArgumentException | ArithmeticException invalid) { + fail(observer, Status.INVALID_ARGUMENT, "INVALID_ARGUMENT"); + return; + } catch (RuntimeException internal) { + fail(observer, Status.INTERNAL, "ENTITLEMENT_UNAVAILABLE"); + return; + } + try { + observer.onNext(result); + observer.onCompleted(); + } catch (RuntimeException callback) { + fail(observer, Status.INTERNAL, "ENTITLEMENT_UNAVAILABLE"); + } + } + + private static void fail(StreamObserver observer, Status status, String code) { + observer.onError( + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.getCode().value()) + .setMessage("Tenant capacity commitment did not complete") + .addDetails( + Any.pack( + ErrorDetail.newBuilder() + .setCode(code) + .setMessage("Tenant capacity commitment did not complete") + .build())) + .build())); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql b/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql new file mode 100644 index 0000000000..ceec667db8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql @@ -0,0 +1,321 @@ +-- Existing tenants are deliberately not initialized from missing usage or eligibility snapshots. +ALTER TABLE account_fresh_tenant_identity_associations ADD COLUMN capacity_birth_transaction VARCHAR(20); +ALTER TABLE account_fresh_tenant_identity_associations ALTER COLUMN capacity_birth_transaction SET DEFAULT pg_current_xact_id()::TEXT; + +CREATE TABLE account_tenant_capacity_usage ( + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + owner_service VARCHAR(40) NOT NULL CHECK (owner_service IN ('game-session-service', 'world-management-service')), + bootstrap_request_id UUID NOT NULL REFERENCES account_tenant_creation_bootstrap_operations(request_id), + creation_evidence_digest VARCHAR(71) NOT NULL CHECK (creation_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + held_units BIGINT NOT NULL CHECK (held_units >= 0), + used_units BIGINT NOT NULL CHECK (used_units >= 0), + usage_revision BIGINT NOT NULL CHECK (usage_revision > 0), + PRIMARY KEY (tenant_uuid, owner_service), + CHECK (held_units <= 9223372036854775807 - used_units) +); + +CREATE TABLE account_tenant_capacity_evaluations ( + evaluation_identity VARCHAR(71) PRIMARY KEY CHECK (evaluation_identity ~ '^sha256:[0-9a-f]{64}$'), + snapshot_identity VARCHAR(71) NOT NULL CHECK (snapshot_identity ~ '^sha256:[0-9a-f]{64}$'), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + caller_workload VARCHAR(253) NOT NULL, + owner_service VARCHAR(40) NOT NULL CHECK (owner_service IN ('game-session-service', 'world-management-service')), + canonical_evidence BYTEA NOT NULL CHECK (octet_length(canonical_evidence) BETWEEN 1 AND 262144), + evaluated_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > evaluated_at) +); + +CREATE TABLE account_tenant_capacity_reservations ( + tenant_uuid UUID NOT NULL, + request_id UUID NOT NULL CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + admission_id UUID NOT NULL CHECK (admission_id <> '00000000-0000-0000-0000-000000000000'::UUID), + reservation_id UUID NOT NULL UNIQUE CHECK (reservation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + owner_service VARCHAR(40) NOT NULL, + caller_workload VARCHAR(253) NOT NULL, + admission_attempt_id UUID NOT NULL UNIQUE, + capacity_rearm_fence BIGINT NOT NULL CHECK (capacity_rearm_fence > 0), + reservation_fence BIGINT NOT NULL CHECK (reservation_fence > 0), + mutation_digest CHAR(64) NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + canonical_payload BYTEA NOT NULL CHECK (octet_length(canonical_payload) BETWEEN 1 AND 524288), + evaluation_identity VARCHAR(71) NOT NULL REFERENCES account_tenant_capacity_evaluations(evaluation_identity), + capacity_delta BIGINT NOT NULL CHECK (capacity_delta >= 0), + expires_at TIMESTAMPTZ NOT NULL, + state VARCHAR(64) NOT NULL CHECK (state IN ('RESERVED', 'FINALIZED', 'RELEASED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), + execution_status VARCHAR(48) NOT NULL CHECK (execution_status IN ('OWNER_EXECUTION_PENDING', 'COMMITTED', 'NOT_EXECUTED_AFTER_AUTHORIZATION')), + recovery_owner UUID, + recovery_claim_fence BIGINT NOT NULL DEFAULT 0 CHECK (recovery_claim_fence >= 0), + recovery_claim_expires_at TIMESTAMPTZ, + next_reconcile_at TIMESTAMPTZ, + reconcile_deadline TIMESTAMPTZ NOT NULL, + recovery_policy_version VARCHAR(32) NOT NULL DEFAULT 'capacity-recovery/1' CHECK (recovery_policy_version = 'capacity-recovery/1'), + recovery_attempt_count INT NOT NULL DEFAULT 0 CHECK (recovery_attempt_count BETWEEN 0 AND 12), + recovery_escalated_at TIMESTAMPTZ, + owner_readback BYTEA CHECK (octet_length(owner_readback) BETWEEN 1 AND 1048576), + owner_readback_digest CHAR(64) CHECK (owner_readback_digest ~ '^[0-9a-f]{64}$'), + PRIMARY KEY (tenant_uuid, request_id, admission_id), + FOREIGN KEY (tenant_uuid, owner_service) REFERENCES account_tenant_capacity_usage(tenant_uuid, owner_service), + CHECK ((execution_status = 'OWNER_EXECUTION_PENDING') = (owner_readback IS NULL)), + CHECK ((owner_readback IS NULL) = (owner_readback_digest IS NULL)), + CHECK ((state = 'FINALIZED') = (execution_status = 'COMMITTED')), + CHECK ((state = 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION') = (recovery_escalated_at IS NOT NULL)), + CHECK (state <> 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION' OR execution_status = 'OWNER_EXECUTION_PENDING'), + CHECK (state <> 'RELEASED' OR execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'), + CHECK ((recovery_owner IS NULL) = (recovery_claim_expires_at IS NULL)) +); + +CREATE TABLE account_tenant_capacity_attempt_history ( + tenant_uuid UUID NOT NULL, + request_id UUID NOT NULL, + admission_id UUID NOT NULL, + admission_attempt_id UUID NOT NULL UNIQUE, + capacity_rearm_fence BIGINT NOT NULL CHECK (capacity_rearm_fence > 0), + mutation_digest CHAR(64) NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + canonical_payload BYTEA NOT NULL CHECK (octet_length(canonical_payload) BETWEEN 1 AND 524288), + owner_readback BYTEA NOT NULL CHECK (octet_length(owner_readback) BETWEEN 1 AND 1048576), + PRIMARY KEY (tenant_uuid, request_id, admission_id, admission_attempt_id), + FOREIGN KEY (tenant_uuid, request_id, admission_id) REFERENCES account_tenant_capacity_reservations(tenant_uuid, request_id, admission_id) +); + +CREATE TABLE account_tenant_capacity_recovery_evidence ( + tenant_uuid UUID NOT NULL, + request_id UUID NOT NULL, + admission_id UUID NOT NULL, + admission_attempt_id UUID NOT NULL, + recovery_claim_fence BIGINT NOT NULL CHECK (recovery_claim_fence > 0), + recovery_policy_version VARCHAR(32) NOT NULL CHECK (recovery_policy_version = 'capacity-recovery/1'), + recovery_attempt_number INT NOT NULL CHECK (recovery_attempt_number BETWEEN 1 AND 12), + observed_at TIMESTAMPTZ NOT NULL, + outcome VARCHAR(64) NOT NULL CHECK (outcome IN ('INDETERMINATE', 'SOURCE_UNAVAILABLE', 'COMMITTED', 'NOT_EXECUTED_AFTER_AUTHORIZATION', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), + canonical_readback BYTEA CHECK (octet_length(canonical_readback) BETWEEN 1 AND 1048576), + readback_digest CHAR(64) CHECK (readback_digest ~ '^[0-9a-f]{64}$'), + PRIMARY KEY (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence), + UNIQUE (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_attempt_number), + FOREIGN KEY (tenant_uuid, request_id, admission_id) REFERENCES account_tenant_capacity_reservations(tenant_uuid, request_id, admission_id), + CHECK ((canonical_readback IS NULL) = (readback_digest IS NULL)), + CHECK (outcome NOT IN ('COMMITTED', 'NOT_EXECUTED_AFTER_AUTHORIZATION') OR canonical_readback IS NOT NULL) +); + +-- [jooq ignore start] +-- Only a genuinely new same-transaction fresh tenant completion can establish zero usage. +-- Replaying/importing a previously committed tenant cannot turn unknown usage into zero. +CREATE FUNCTION account_tenant_capacity_bootstrap_new_tenant() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE birth account_fresh_tenant_identity_associations%ROWTYPE; +BEGIN + IF OLD.status = 'IN_PROGRESS' AND NEW.status = 'COMMITTED' THEN + SELECT * INTO birth FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid FOR SHARE; + IF birth.capacity_birth_transaction IS DISTINCT FROM pg_current_xact_id()::TEXT THEN + RETURN NEW; + END IF; + IF birth.operation_id IS DISTINCT FROM NEW.creation_operation_id + OR birth.creation_request_id IS DISTINCT FROM NEW.creation_request_id + OR NEW.baseline_event_sequence <> 0 + OR NEW.gameplay_admission_allowed IS DISTINCT FROM FALSE + OR EXISTS (SELECT 1 FROM account_tenant_membership + WHERE tenant_uuid = NEW.tenant_uuid AND gameplay_admission_allowed IS TRUE) + OR EXISTS (SELECT 1 FROM account_tenant_capacity_usage WHERE tenant_uuid = NEW.tenant_uuid) THEN + RAISE EXCEPTION 'Fresh tenant capacity baseline is not demonstrably empty' USING ERRCODE = '23514'; + END IF; + INSERT INTO account_tenant_capacity_usage + (tenant_uuid, owner_service, bootstrap_request_id, creation_evidence_digest, held_units, used_units, usage_revision) + VALUES (NEW.tenant_uuid, 'game-session-service', NEW.request_id, birth.evidence_digest, 0, 0, 1), + (NEW.tenant_uuid, 'world-management-service', NEW.request_id, birth.evidence_digest, 0, 0, 1); + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_fresh_bootstrap AFTER UPDATE ON account_tenant_creation_bootstrap_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_bootstrap_new_tenant(); + +CREATE FUNCTION account_tenant_capacity_immutable_evaluation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Capacity evaluation and historical attempt evidence is immutable' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER account_tenant_capacity_evaluation_guard BEFORE UPDATE OR DELETE ON account_tenant_capacity_evaluations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_history_guard BEFORE UPDATE OR DELETE ON account_tenant_capacity_attempt_history + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_recovery_evidence_guard BEFORE UPDATE OR DELETE ON account_tenant_capacity_recovery_evidence + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); + +CREATE FUNCTION account_tenant_capacity_usage_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.held_units <> 0 OR NEW.used_units <> 0 OR NEW.usage_revision <> 1 OR NOT EXISTS ( + SELECT 1 FROM account_tenant_creation_bootstrap_operations bootstrap + JOIN account_fresh_tenant_identity_associations birth ON birth.canonical_tenant_id = bootstrap.tenant_uuid + WHERE bootstrap.request_id = NEW.bootstrap_request_id AND bootstrap.tenant_uuid = NEW.tenant_uuid + AND bootstrap.status = 'COMMITTED' AND bootstrap.gameplay_admission_allowed IS FALSE + AND bootstrap.baseline_event_sequence = 0 + AND bootstrap.creation_operation_id = birth.operation_id + AND birth.evidence_digest = NEW.creation_evidence_digest + AND birth.capacity_birth_transaction = pg_current_xact_id()::TEXT) THEN + RAISE EXCEPTION 'Capacity usage initialization requires same-transaction new-tenant bootstrap' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_usage_birth BEFORE INSERT ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_usage_insert_guard(); + +CREATE FUNCTION account_tenant_capacity_usage_update_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid OR NEW.owner_service IS DISTINCT FROM OLD.owner_service + OR NEW.bootstrap_request_id IS DISTINCT FROM OLD.bootstrap_request_id + OR NEW.creation_evidence_digest IS DISTINCT FROM OLD.creation_evidence_digest + OR NEW.usage_revision <> OLD.usage_revision + 1 THEN + RAISE EXCEPTION 'Capacity usage identity is immutable and revision must advance once' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_usage_revision BEFORE UPDATE ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_usage_update_guard(); + +CREATE FUNCTION account_tenant_capacity_reservation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_tenant_capacity_evaluations evaluation + WHERE evaluation.evaluation_identity = NEW.evaluation_identity + AND evaluation.tenant_uuid = NEW.tenant_uuid AND evaluation.caller_workload = NEW.caller_workload + AND evaluation.owner_service = NEW.owner_service) THEN + RAISE EXCEPTION 'Capacity reservation lacks its exact retained Account evaluation' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' OR NEW.admission_attempt_id IS DISTINCT FROM OLD.admission_attempt_id) + AND EXISTS (SELECT 1 FROM account_tenant_capacity_attempt_history WHERE admission_attempt_id = NEW.admission_attempt_id) THEN + RAISE EXCEPTION 'Capacity admission attempt identity must be fresh' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'RESERVED' OR NEW.execution_status <> 'OWNER_EXECUTION_PENDING' + OR NEW.capacity_rearm_fence <> 1 OR NEW.reservation_fence <> 1 + OR NEW.recovery_owner IS NOT NULL OR NEW.recovery_claim_fence <> 0 OR NEW.owner_readback IS NOT NULL + OR NEW.recovery_attempt_count <> 0 OR NEW.recovery_escalated_at IS NOT NULL THEN + RAISE EXCEPTION 'Capacity reservation must begin as the original pending attempt' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.admission_id IS DISTINCT FROM OLD.admission_id OR NEW.reservation_id IS DISTINCT FROM OLD.reservation_id + OR NEW.owner_service IS DISTINCT FROM OLD.owner_service OR NEW.caller_workload IS DISTINCT FROM OLD.caller_workload + OR NEW.capacity_delta IS DISTINCT FROM OLD.capacity_delta OR NEW.recovery_claim_fence < OLD.recovery_claim_fence + OR NEW.recovery_policy_version IS DISTINCT FROM OLD.recovery_policy_version THEN + RAISE EXCEPTION 'Capacity reservation identity and hold are immutable' USING ERRCODE = '23514'; + END IF; + IF NEW.recovery_owner IS DISTINCT FROM OLD.recovery_owner + OR NEW.recovery_claim_expires_at IS DISTINCT FROM OLD.recovery_claim_expires_at + OR NEW.recovery_claim_fence <> OLD.recovery_claim_fence THEN + IF NEW.recovery_claim_fence <> OLD.recovery_claim_fence + 1 OR NEW.recovery_owner IS NULL + OR NEW.recovery_claim_expires_at <= clock_timestamp() + OR (OLD.recovery_owner IS DISTINCT FROM NEW.recovery_owner + AND OLD.recovery_claim_expires_at > clock_timestamp()) THEN + RAISE EXCEPTION 'Capacity recovery claim must monotonically fence its exact current owner' USING ERRCODE = '23514'; + END IF; + END IF; + IF NEW.admission_attempt_id IS DISTINCT FROM OLD.admission_attempt_id THEN + IF OLD.state <> 'RESERVED' OR OLD.execution_status <> 'NOT_EXECUTED_AFTER_AUTHORIZATION' + OR OLD.owner_readback IS NULL OR OLD.recovery_owner IS NULL + OR OLD.recovery_claim_expires_at <= clock_timestamp() + OR NEW.recovery_owner IS DISTINCT FROM OLD.recovery_owner + OR NEW.recovery_claim_fence <> OLD.recovery_claim_fence + OR NEW.capacity_rearm_fence <> OLD.capacity_rearm_fence + 1 + OR NEW.reservation_fence <> OLD.reservation_fence + 1 + OR NEW.state <> 'RESERVED' OR NEW.execution_status <> 'OWNER_EXECUTION_PENDING' + OR NEW.recovery_attempt_count <> 0 OR NEW.recovery_escalated_at IS NOT NULL + OR NEW.owner_readback IS NOT NULL OR NEW.owner_readback_digest IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM account_tenant_capacity_attempt_history history + WHERE history.tenant_uuid = OLD.tenant_uuid AND history.request_id = OLD.request_id + AND history.admission_id = OLD.admission_id AND history.admission_attempt_id = OLD.admission_attempt_id + AND history.capacity_rearm_fence = OLD.capacity_rearm_fence + AND history.mutation_digest = OLD.mutation_digest AND history.canonical_payload = OLD.canonical_payload + AND history.owner_readback = OLD.owner_readback) THEN + RAISE EXCEPTION 'Capacity rearm requires exact durable terminal no-commit and current recovery claim' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.capacity_rearm_fence <> OLD.capacity_rearm_fence + OR NEW.mutation_digest IS DISTINCT FROM OLD.mutation_digest OR NEW.canonical_payload IS DISTINCT FROM OLD.canonical_payload + OR NEW.evaluation_identity IS DISTINCT FROM OLD.evaluation_identity OR NEW.expires_at IS DISTINCT FROM OLD.expires_at + OR NEW.reconcile_deadline IS DISTINCT FROM OLD.reconcile_deadline THEN + RAISE EXCEPTION 'Changed capacity attempt is an idempotency conflict' USING ERRCODE = '23514'; + END IF; + IF OLD.state <> 'RESERVED' THEN + IF NEW IS DISTINCT FROM OLD THEN + RAISE EXCEPTION 'Terminal capacity result is immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.recovery_attempt_count <> OLD.recovery_attempt_count THEN + IF NEW.recovery_attempt_count <> OLD.recovery_attempt_count + 1 + OR NEW.recovery_owner IS NULL OR NEW.recovery_claim_expires_at <= clock_timestamp() + OR NOT EXISTS (SELECT 1 FROM account_tenant_capacity_recovery_evidence evidence + WHERE evidence.tenant_uuid = OLD.tenant_uuid AND evidence.request_id = OLD.request_id + AND evidence.admission_id = OLD.admission_id AND evidence.admission_attempt_id = OLD.admission_attempt_id + AND evidence.recovery_claim_fence = NEW.recovery_claim_fence + AND evidence.recovery_attempt_number = NEW.recovery_attempt_count) THEN + RAISE EXCEPTION 'Capacity recovery must retain each bounded observation under its current claim' USING ERRCODE = '23514'; + END IF; + END IF; + IF NEW.state = 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION' THEN + IF OLD.execution_status <> 'OWNER_EXECUTION_PENDING' + OR (NEW.recovery_attempt_count < 12 AND clock_timestamp() < OLD.reconcile_deadline) + OR NEW.recovery_escalated_at IS NULL + OR NEW.next_reconcile_at IS NOT NULL THEN + RAISE EXCEPTION 'Capacity quarantine requires exhausted bounded recovery and preserves the original hold' USING ERRCODE = '23514'; + END IF; + END IF; + IF OLD.execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION' + AND (NEW.execution_status <> OLD.execution_status OR NEW.owner_readback IS DISTINCT FROM OLD.owner_readback + OR NEW.owner_readback_digest IS DISTINCT FROM OLD.owner_readback_digest) THEN + RAISE EXCEPTION 'Terminal capacity no-commit evidence cannot be replaced' USING ERRCODE = '23514'; + END IF; + IF NEW.state <> OLD.state OR NEW.execution_status <> OLD.execution_status THEN + IF NEW.recovery_owner IS NULL OR NEW.recovery_claim_fence = 0 + OR NEW.recovery_claim_expires_at <= clock_timestamp() + OR (NEW.state <> 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION' AND NEW.owner_readback IS NULL) THEN + RAISE EXCEPTION 'Only current Account recovery claim may transition capacity evidence' USING ERRCODE = '23514'; + END IF; + END IF; + IF (NEW.state = 'RELEASED' AND NEW.reservation_fence <> OLD.reservation_fence + 1) + OR (NEW.state <> 'RELEASED' AND NEW.reservation_fence <> OLD.reservation_fence) THEN + RAISE EXCEPTION 'Capacity release must durably fence the original reservation' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_reservation_fences BEFORE INSERT OR UPDATE ON account_tenant_capacity_reservations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_reservation_guard(); + +-- The complete durable reservation inventory, not a local issuer counter, owns usage. +CREATE FUNCTION account_tenant_capacity_exact_usage() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE held NUMERIC; used NUMERIC; actual account_tenant_capacity_usage%ROWTYPE; +BEGIN + SELECT * INTO actual FROM account_tenant_capacity_usage + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service FOR UPDATE; + SELECT COALESCE(sum(capacity_delta) FILTER (WHERE state IN ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0), + COALESCE(sum(capacity_delta) FILTER (WHERE state = 'FINALIZED'), 0) + INTO held, used FROM account_tenant_capacity_reservations + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service; + IF actual.tenant_uuid IS NULL OR held <> actual.held_units OR used <> actual.used_units THEN + RAISE EXCEPTION 'Capacity usage differs from its complete durable reservation inventory' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_tenant_capacity_usage_complete AFTER INSERT OR UPDATE ON account_tenant_capacity_usage + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_exact_usage(); +CREATE CONSTRAINT TRIGGER account_tenant_capacity_reservation_complete AFTER INSERT OR UPDATE ON account_tenant_capacity_reservations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_exact_usage(); +CREATE TRIGGER account_tenant_capacity_usage_no_delete BEFORE DELETE ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_reservation_no_delete BEFORE DELETE ON account_tenant_capacity_reservations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_usage_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_usage + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_reservation_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_reservations + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_evaluation_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_evaluations + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_history_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_attempt_history + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_recovery_evidence_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_recovery_evidence + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..5eaa18c30a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -0,0 +1,107 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** Real forward migration with retained tenant provenance. No existing usage is guessed. */ +class AccountTenantCapacityMigrationPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @Test + void existingTenantStaysUninitializedAndAPlainNewImportCannotInitializeCapacity() { + String schema = "capacity_migration_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1038") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var repository = new FreshTenantIdentityAssociationRepository(dsl, "prod"); + var existing = source(); + transaction.executeWithoutResult(status -> repository.importVerified(existing)); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var retained = transaction.execute(status -> repository.read(existing.canonicalTenantId())); + assertThat(retained).contains(existing); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT capacity_birth_transaction FROM account_fresh_tenant_identity_associations WHERE canonical_tenant_id = ?", + existing.canonicalTenantId())) + .get("capacity_birth_transaction")) + .isNull(); + var later = source(); + transaction.executeWithoutResult(status -> repository.importVerified(later)); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT capacity_birth_transaction FROM account_fresh_tenant_identity_associations WHERE canonical_tenant_id = ?", + later.canonicalTenantId())) + .get("capacity_birth_transaction")) + .isNotNull(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static FreshTenantCreationEvidence source() { + UUID request = UUID.randomUUID(), operation = UUID.randomUUID(), tenant = UUID.randomUUID(); + String slug = "capacity-" + UUID.randomUUID().toString().substring(0, 8); + String digest = GameTenantCreationDigest.requestDigest("prod", request, slug, "Capacity", null); + long row = Math.abs((long) tenant.hashCode()) + 1; + return new FreshTenantCreationEvidence( + 1, + "prod", + request, + operation, + digest, + tenant, + row, + slug, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", request, operation, digest, tenant, row, slug, "NEW_GAME_ROW")); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 6fc7537379..0de1522123 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -330,6 +330,18 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { .containsExactlyEntriesOf(Map.of(f.tenantId.toString(), "2")); assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); + var retained = + f.dsl.fetchOne( + "SELECT canonical_evidence, snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + value.fields().get("evaluationIdentity")); + assertThat(retained).isNotNull(); + assertThat(retained.get("canonical_evidence", byte[].class)).isEqualTo(value.canonicalBytes()); + assertThat(retained.get("snapshot_identity", String.class)) + .isEqualTo(value.fields().get("snapshotIdentity")); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + // This old fixture tenant was imported before creator completion. Eligibility evaluation + // never invents an empty capacity baseline for it. + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); var binding = (Map) value.fields().get("target"); assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); assertThat(binding.get("playableStateNamespaceId")) @@ -412,6 +424,7 @@ public void beforeCommit(boolean readOnly) { assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) .hasMessageContaining("controlled final source commit refusal"); assertThat(competingWriterRefused.get()).isTrue(); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_evaluations"))).isZero(); var unlocked = f.transaction.execute( status -> f.accounts.findByAccountUuidForUpdate(f.account.getAccountUuid())); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 0d552450fc..f817135544 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -360,6 +360,327 @@ void fullStoredOwnerCompletionCommitsAllReceiptsAndExactReplayWithoutReconsumpti assertThat(c.dsl.fetchCount(DSL.table("account_audit_outbox"))).isEqualTo(2); } + @Test + void capacityOwnerPersistenceFinalizesOneOriginalReservationAndUsageExactlyOnce() { + var f = capacityPersistenceFixture(); + var calls = new java.util.concurrent.atomic.AtomicInteger(); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + calls.incrementAndGet(); + return capacityObservation( + request, + reservation, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.COMMITTED); + }, + java.time.Clock.systemUTC()); + var result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.FINALIZED); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(1); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("used_units", Long.class)) + .isEqualTo(17); + } + + @Test + void capacityIndeterminateReadbackCannotReleaseAndTerminalNoCommitReleasesSameHold() { + var f = capacityPersistenceFixture(); + var disposition = + new java.util.concurrent.atomic.AtomicReference<>( + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.INDETERMINATE); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> + capacityObservation(request, reservation, disposition.get()), + java.time.Clock.systemUTC()); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(f.initial); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isEqualTo(17); + // This is controlled source/claim proof, not production selected-owner CAS qualification. + disposition.set( + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.NOT_EXECUTED_AFTER_AUTHORIZATION); + var released = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(released.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.RELEASED); + assertThat(released.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(released.reservationFence()).isEqualTo(f.initial.reservationFence() + 1); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(released); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isZero(); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))) + .isEqualTo(1); + } + + @Test + void capacityChangedAttemptConflictsWithoutUsageMutationAndIncompleteLedgerCannotBeSeeded() { + var f = capacityPersistenceFixture(); + var changed = + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( + f.request.identity(), + UUID.randomUUID(), + f.request.capacityRearmFence(), + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(); + assertThatThrownBy( + () -> + f.context.transaction.execute( + status -> f.repository.exact(changed, f.repository.find(changed.identity())))) + .hasMessage("IDEMPOTENCY_CONFLICT"); + assertThatThrownBy( + () -> + f.context.transaction.executeWithoutResult( + status -> + f.context.dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units + 1, usage_revision = usage_revision + 1 WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()))) + .isInstanceOf(RuntimeException.class); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isEqualTo(17); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))) + .isEqualTo(1); + } + + @Test + void boundedIndeterminateCapacityRecoveryQuarantinesTheOriginalCompleteHold() { + var f = capacityPersistenceFixture(); + var calls = new java.util.concurrent.atomic.AtomicInteger(); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + calls.incrementAndGet(); + throw new IllegalStateException("Controlled selected-owner unavailability"); + }, + java.time.Clock.systemUTC()); + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result result = + f.initial; + for (int attempt = 0; attempt < 12; attempt++) { + result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.reservationFence()).isEqualTo(f.initial.reservationFence()); + } + assertThat(result.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State + .QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); + assertThat(calls).hasValue(12); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(12); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_recovery_evidence"))) + .isEqualTo(12); + var usage = + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()); + assertThat(usage.get("held_units", Long.class)).isEqualTo(17); + assertThat(usage.get("used_units", Long.class)).isZero(); + var retained = + f.context.dsl.fetchOne( + "SELECT recovery_attempt_count, recovery_escalated_at, next_reconcile_at FROM account_tenant_capacity_reservations WHERE reservation_id = ?", + result.reservationId()); + assertThat(retained.get("recovery_attempt_count", Integer.class)).isEqualTo(12); + assertThat(retained.get("recovery_escalated_at")).isNotNull(); + assertThat(retained.get("next_reconcile_at")).isNull(); + } + + /** Genuine same-transaction fresh creation; controlled entitlement and owner execution source. */ + private static CapacityPersistenceFixture capacityPersistenceFixture() { + StorageContext c = storageContext(); + var fixture = storageFixture(c); + var assembled = assembleStoredOwner(c, fixture, new AccountAuditOutboxRepository(c.dsl)); + assembled.owner.complete( + fixture.intent.creationOperationId(), + assembled.terminal, + assembled.environment, + assembled.recent); + UUID tenant = assembled.terminal.evidence().receipt().orElseThrow().canonicalTenantId(); + var base = + net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.worldRequest( + 17L); + var now = java.time.Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS); + String json = + new String(base.evidence().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) + .replace(base.identity().tenantId().toString(), tenant.toString()) + .replace( + net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.NOW + .toString(), + now.toString()); + var evidence = + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence.parse( + json.getBytes(java.nio.charset.StandardCharsets.UTF_8), + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner + .WORLD_MANAGEMENT); + var context = + (net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext) + base.context(); + var request = + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity( + tenant, base.identity().requestId(), base.identity().admissionId()), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .WorldContext( + tenant, + context.operationId(), + context.lifecycleId(), + context.gameInstanceId(), + context.ownerId(), + context.ownerFence()), + base.operation(), + base.priorShape(), + base.requestedShape(), + evidence, + base.capacityDelta(), + null) + .withDigest(); + var repository = + new net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository(c.dsl); + var initial = + c.transaction.execute( + status -> { + // Controlled fixture evidence deliberately bypasses the absent World producer. + // Production + // has no route to perform this insertion and World admission remains unavailable. + c.dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + evidence.evaluationIdentity(), + evidence.snapshotIdentity(), + tenant, + evidence.callerWorkload(), + evidence.owner().service(), + evidence.canonicalBytes(), + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository + .at(evidence.evaluatedAt()), + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository + .at(evidence.expiresAt())); + return repository.create(request, evidence.expiresAt()); + }); + var owner = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner( + c.dsl, + c.accounts, + mock( + net.firedevops.firemud.accountservice.repository + .AccountCanonicalRuntimeMembershipSnapshotRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountGameplayDelegationIssuanceRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + .class), + c.manager, + java.time.Clock.systemUTC(), + "prod"); + return new CapacityPersistenceFixture(c, request, repository, owner, initial); + } + + private static net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Observation + capacityObservation( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result reservation, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition + disposition) { + return new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Observation( + request.evidence().callerWorkload(), + reservation, + net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest.preimage(request), + disposition, + request.admissionAttemptId(), + 7, + "sha256:" + "e".repeat(64), + "controlled-owner-readback".getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + } + + private record CapacityPersistenceFixture( + StorageContext context, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository repository, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner owner, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result initial) {} + @Test void expiredCreatedSettlesSharedSourceHoldWithoutAnyAccountCreatorCompletion() { StorageContext c = storageContext(15, 0); @@ -763,6 +1084,8 @@ c.dsl, new DraftAuthorizationFenceRepository(c.dsl)), } private static void assertAtomicRowsBeforeFinal(StorageContext c) { + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isEqualTo(2); + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); for (String table : List.of( "account_fresh_tenant_identity_associations", @@ -776,6 +1099,9 @@ private static void assertAtomicRowsBeforeFinal(StorageContext c) { } private static void assertAtomicRows(StorageContext c, int expected) { + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))) + .isEqualTo(2 * expected); + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); for (String table : List.of( "account_fresh_tenant_identity_associations", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java new file mode 100644 index 0000000000..60fc27cb14 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Context; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class AccountTenantCapacityWorkloadGuardTest { + private final AccountTenantCapacityWorkloadGuard guard = + new AccountTenantCapacityWorkloadGuard("firemud"); + + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void onlyExactTlsGameSessionAndMethodCanInstallPrivateAssertion() throws Exception { + var method = AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod(); + assertThat(invoke(method, tls("firemud", "game-session-service"))).isNull(); + assertThat(invoke(method, tls("firemud", "world-management-service"))).isNull(); + assertThatThrownBy(guard::requireAuthenticatedCaller) + .isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, tls("other", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(invoke(method, tls("firemud", "account-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + invoke(AccountServiceGrpc.getGetProfileMethod(), tls("firemud", "game-session-service")) + .getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + @Test + void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { + var method = AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/game-session-service") + .orElseThrow()) + .run( + () -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedCaller) + .isInstanceOf(StatusRuntimeException.class); + }); + for (boolean internal : List.of(true, false)) { + if (internal) + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "instance"); + else SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, tls("firemud", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private Status invoke(MethodDescriptor method, SSLSession ssl) { + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(method); + when(call.getAttributes()) + .thenReturn( + ssl == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, ssl).build()); + AtomicInteger starts = new AtomicInteger(); + ServerCallHandler next = + (ignored, headers) -> { + assertThat(guard.requireAuthenticatedCaller()) + .isIn( + "spiffe://firemud/ns/firemud/sa/game-session-service", + "spiffe://firemud/ns/firemud/sa/world-management-service"); + starts.incrementAndGet(); + return new ServerCall.Listener() {}; + }; + guard.interceptCall(call, new Metadata(), next); + var captured = ArgumentCaptor.forClass(Status.class); + verify(call, org.mockito.Mockito.atMostOnce()).close(captured.capture(), any(Metadata.class)); + assertThat(starts.get()).isEqualTo(captured.getAllValues().isEmpty() ? 1 : 0); + return captured.getAllValues().isEmpty() ? null : captured.getValue(); + } + + private static SSLSession tls(String namespace, String service) throws Exception { + var leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/" + namespace + "/sa/" + service))); + var ssl = mock(SSLSession.class); + when(ssl.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + return ssl; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index e577f8de6c..0264e0ff0f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -134,6 +134,12 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); assertThat(value.fields().get("requestId")).isEqualTo(f.request.requestId().toString()); assertThat(value.fields().get("callerWorkload")).isEqualTo(PEER); + assertThat(f.retainedCapacity).hasSize(1); + assertThat( + f.retainedCapacity + .get(value.fields().get("evaluationIdentity")) + .get("canonical_evidence", byte[].class)) + .containsExactly(value.canonicalBytes()); assertThat(value.membershipSource().accountId()).isEqualTo(ACCOUNT.toString()); assertThat(value.membershipSource().tenantId()).isEqualTo(TENANT.toString()); assertThat(value.membershipSource().membershipExists()).isFalse(); @@ -157,6 +163,17 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa verifyNoInteractions(f.hosting, f.observer); } + @Test + void capacityRetentionFailureRollsBackSourceCaptureWithoutReturningEvidence() throws Exception { + Fixture f = new Fixture(true); + f.refuseCapacityRetention = true; + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isInstanceOf(DataAccessException.class) + .hasMessage("Controlled capacity retention refusal"); + assertThat(f.retainedCapacity).isEmpty(); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + @Test void existingMembershipCarriesItsIndependentVersionAndPositiveCheckpoint() throws Exception { Fixture f = new Fixture(true); @@ -868,6 +885,8 @@ private static final class Fixture { private final CanonicalGameplayAdmissionDecisionReadClient targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); private final RecordingTransactions transactions = new RecordingTransactions(); + private final Map retainedCapacity = new LinkedHashMap<>(); + private boolean refuseCapacityRetention; private final java.util.concurrent.atomic.AtomicReference time = new java.util.concurrent.atomic.AtomicReference<>(NOW); private final FreshTenantCreationEvidence source = source(); @@ -955,6 +974,43 @@ private Fixture(boolean exists, String stateScope) throws Exception { PEER); controlledTarget(targets); var dsl = mock(DSLContext.class); + // Controlled retention content, not physical atomicity or Account source authentication. + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (!sql.startsWith("INSERT INTO account_tenant_capacity_evaluations ")) + throw new AssertionError(sql); + if (refuseCapacityRetention) + throw new DataAccessException("Controlled capacity retention refusal"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + Object[] values = (Object[]) invocation.getRawArguments()[1]; + String id = (String) values[0]; + if (retainedCapacity.containsKey(id)) return 0; + var row = mock(org.jooq.Record.class); + when(row.get("evaluation_identity", String.class)).thenReturn(id); + when(row.get("snapshot_identity", String.class)).thenReturn((String) values[1]); + when(row.get("tenant_uuid", UUID.class)).thenReturn((UUID) values[2]); + when(row.get("caller_workload", String.class)).thenReturn((String) values[3]); + when(row.get("owner_service", String.class)).thenReturn((String) values[4]); + when(row.get("canonical_evidence", byte[].class)) + .thenReturn(((byte[]) values[5]).clone()); + when(row.get("evaluated_at", java.time.OffsetDateTime.class)) + .thenReturn((java.time.OffsetDateTime) values[6]); + when(row.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn((java.time.OffsetDateTime) values[7]); + retainedCapacity.put(id, row); + return 1; + }); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (!sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) + throw new AssertionError(sql); + Object[] values = (Object[]) invocation.getRawArguments()[1]; + return retainedCapacity.get((String) values[0]); + }); var connection = mock(Connection.class); when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); doAnswer( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java new file mode 100644 index 0000000000..3d2e8e3961 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -0,0 +1,248 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.time.Clock; +import java.time.ZoneOffset; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Controlled ordering/denial only. Physical transaction and positive current-source proof are + * separate. + */ +class AccountTenantCapacityOwnerTest { + @AfterEach + void clear() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() + throws Exception { + var f = new Fixture(true); + var result = f.owner.commit(f.request, f.request.evidence().callerWorkload()); + assertThat(result.reservationId()).isEqualTo(f.reservation); + assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload())).isEqualTo(result); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void changedAttemptOrPayloadOrFenceConflictsBeforeAnyCurrentSourceOrUsageMutation() + throws Exception { + var f = new Fixture(false); + for (Request changed : + java.util.List.of( + new Request( + f.request.identity(), + UUID.randomUUID(), + f.request.capacityRearmFence(), + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(), + new Request( + f.request.identity(), + f.request.admissionAttemptId(), + 2, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(), + new Request( + f.request.identity(), + f.request.admissionAttemptId(), + f.request.capacityRearmFence(), + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .Shape(2, 0, 0), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest())) { + assertThatThrownBy(() -> f.owner.commit(changed, changed.evidence().callerWorkload())) + .hasMessage("IDEMPOTENCY_CONFLICT"); + } + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void matchingContentWithoutAccountRetainedAuthorityCannotCreateUsage() throws Exception { + var f = new Fixture(false); + f.existing = false; + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void wrongPeerOrAbsentDeltaNeverStartsAccountWork() throws Exception { + var f = new Fixture(false); + assertThatThrownBy( + () -> f.owner.commit(f.request, "spiffe://firemud/ns/prod/sa/world-management-service")) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + var absent = + new Request( + f.request.identity(), + f.request.admissionAttemptId(), + 1, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + null, + null) + .withDigest(); + assertThatThrownBy(() -> f.owner.commit(absent, absent.evidence().callerWorkload())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships = + mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class); + private final AccountGameplayDelegationIssuanceRepository issuances = + mock(AccountGameplayDelegationIssuanceRepository.class); + private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + private final Request request = CapacityAdmissionTestFixture.playerRequest(); + private final UUID reservation = UUID.randomUUID(); + private final AccountTenantCapacityOwner owner; + private boolean existing = true; + + private Fixture(boolean expired) throws Exception { + when(accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenReturn(Optional.of(new Account())); + Connection connection = mock(Connection.class); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); + doAnswer( + invocation -> { + invocation.getArgument(0, ConnectionRunnable.class).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + Record row = mock(Record.class); + when(row.get("tenant_uuid", UUID.class)).thenReturn(request.identity().tenantId()); + when(row.get("request_id", UUID.class)).thenReturn(request.identity().requestId()); + when(row.get("admission_id", UUID.class)).thenReturn(request.identity().admissionId()); + when(row.get("admission_attempt_id", UUID.class)).thenReturn(request.admissionAttemptId()); + when(row.get("reservation_id", UUID.class)).thenReturn(reservation); + when(row.get("capacity_rearm_fence", Long.class)).thenReturn(1L); + when(row.get("reservation_fence", Long.class)).thenReturn(1L); + when(row.get("mutation_digest", String.class)).thenReturn(request.mutationDigest()); + when(row.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(request)); + when(row.get("caller_workload", String.class)) + .thenReturn(request.evidence().callerWorkload()); + when(row.get("evaluation_identity", String.class)) + .thenReturn(request.evidence().evaluationIdentity()); + when(row.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(request.evidence().expiresAt())); + when(row.get("state", String.class)).thenReturn("RESERVED"); + Record evaluation = mock(Record.class); + when(evaluation.get("snapshot_identity", String.class)) + .thenReturn(request.evidence().snapshotIdentity()); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (sql.startsWith("SELECT * FROM account_tenant_capacity_reservations ")) + return existing ? row : null; + if (sql.startsWith( + "SELECT snapshot_identity FROM account_tenant_capacity_evaluations ")) + return evaluation; + if (sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) + return null; + throw new AssertionError(sql); + }); + owner = + new AccountTenantCapacityOwner( + dsl, + accounts, + memberships, + issuances, + scopes, + new ControlledTransactions(), + Clock.fixed( + CapacityAdmissionTestFixture.NOW.plusSeconds(expired ? 60 : 1), ZoneOffset.UTC), + "prod"); + } + } + + private static final class ControlledTransactions implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction( + @org.jspecify.annotations.Nullable TransactionDefinition definition) { + assertThat(definition).isNotNull(); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getTimeout()).isEqualTo(5); + assertThat(definition.isReadOnly()).isFalse(); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java new file mode 100644 index 0000000000..5536f68777 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.Normalizer; +import java.util.Base64; +import java.util.HexFormat; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Shape; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext; + +/** The capacity-admission/1 action-family mapping of ADR 0047 mutationDigest/v1. */ +public final class CapacityAdmissionDigest { + public static final int MAX_PREIMAGE_BYTES = 512 * 1024; + public static final int MAX_SEGMENT_BYTES = 384 * 1024; + public static final int MAX_STRING_BYTES = 352 * 1024; + + private CapacityAdmissionDigest() {} + + public static byte[] preimage(Request request) { + var output = new ByteArrayOutputStream(); + segment(output, ascii("mutationDigest/v1")); + field(output, "actionFamilySchemaId", string(TenantCapacityAdmission.SCHEMA_ID)); + field(output, "actionFamilySchemaVersion", string(TenantCapacityAdmission.SCHEMA_VERSION)); + field( + output, + "scope", + object( + "tenantId", string(request.identity().tenantId().toString()), + "requestId", string(request.identity().requestId().toString()), + "admissionId", string(request.identity().admissionId().toString()))); + byte[] context; + if (request.context() instanceof PlayerContext player) { + context = + object( + "accountId", + string(player.accountId().toString()), + "tenantId", + string(player.tenantId().toString()), + "playableStateNamespaceId", + string(player.playableStateNamespaceId().toString()), + "gameInstanceId", + string(player.gameInstanceId().toString()), + "characterId", + string(player.characterId().toString()), + "sessionId", + string(player.sessionId().toString()), + "realmId", + string(player.realmId().toString()), + "requestId", + string(player.requestId().toString()), + "playableStateScope", + string(player.playableStateScope())); + } else { + var world = (WorldContext) request.context(); + context = + object( + "tenantId", + string(world.tenantId().toString()), + "operationId", + string(world.operationId().toString()), + "lifecycleId", + string(world.lifecycleId().toString()), + "gameInstanceId", + string(world.gameInstanceId().toString()), + "ownerId", + string(world.ownerId().toString()), + "ownerFence", + number(world.ownerFence())); + } + field( + output, + "target", + object( + "ownerService", + string(request.context().owner().service()), + "targetNamespace", + string(request.targetNamespace()), + "ownerContext", + context)); + field( + output, + "expectedVersion", + object( + "admissionAttemptId", string(request.admissionAttemptId().toString()), + "capacityRearmFence", number(request.capacityRearmFence()))); + field( + output, + "mutation", + object( + "operation", + string(request.operation().name()), + "priorShape", + shape(request.priorShape()), + "requestedShape", + shape(request.requestedShape()), + "accountEvidence", + string(Base64.getEncoder().encodeToString(request.evidence().canonicalBytes())), + "capacityDelta", + request.capacityDelta() == null + ? value("absent", false, new byte[0]) + : number(request.capacityDelta()))); + field(output, "auditReason", string("capacity-admission")); + if (output.size() > MAX_PREIMAGE_BYTES) throw invalid(); + return output.toByteArray(); + } + + public static String digest(Request request) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage(request))); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + private static byte[] shape(Shape shape) { + return object( + "activeSessions", + number(shape.activeSessions()), + "concurrentGameInstances", + number(shape.concurrentGameInstances()), + "storageBytes", + number(shape.storageBytes())); + } + + private static byte[] number(long value) { + if (value < 0) throw invalid(); + return value("number", true, ascii(Long.toString(value))); + } + + private static byte[] string(String value) { + if (value == null || value.length() > MAX_STRING_BYTES) throw invalid(); + for (int index = 0; index < value.length(); index++) { + char c = value.charAt(index); + if (Character.isHighSurrogate(c)) { + if (++index >= value.length() || !Character.isLowSurrogate(value.charAt(index))) + throw invalid(); + } else if (Character.isLowSurrogate(c)) throw invalid(); + } + byte[] bytes = + Normalizer.normalize(value, Normalizer.Form.NFC).getBytes(StandardCharsets.UTF_8); + if (bytes.length > MAX_STRING_BYTES) throw invalid(); + return value("string", true, bytes); + } + + private static byte[] object(Object... fields) { + if (fields.length % 2 != 0 || fields.length > 32) throw invalid(); + var output = new ByteArrayOutputStream(); + segment(output, ascii(Integer.toString(fields.length / 2))); + for (int index = 0; index < fields.length; index += 2) { + field(output, (String) fields[index], (byte[]) fields[index + 1]); + } + return value("object", true, output.toByteArray()); + } + + private static byte[] value(String type, boolean present, byte[] payload) { + var output = new ByteArrayOutputStream(); + segment(output, ascii(type)); + output.write(present ? '1' : '0'); + segment(output, payload); + return output.toByteArray(); + } + + private static void field(ByteArrayOutputStream output, String name, byte[] value) { + segment(output, ascii(name)); + output.writeBytes(value); + if (output.size() > MAX_PREIMAGE_BYTES) throw invalid(); + } + + private static void segment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_SEGMENT_BYTES) throw invalid(); + output.writeBytes(ascii(Integer.toString(bytes.length))); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid capacity-admission/1 canonical value"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java new file mode 100644 index 0000000000..bfc478c83f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java @@ -0,0 +1,401 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Content contract only. Neither construction nor a digest authenticates Account or an owner. */ +public final class TenantCapacityAdmission { + public static final String SCHEMA_ID = "capacity-admission"; + public static final String SCHEMA_VERSION = "1"; + public static final int MAX_EVIDENCE_BYTES = 256 * 1024; + + private TenantCapacityAdmission() {} + + public enum Owner { + GAME_SESSION("game-session-service", "maxActiveSessions"), + WORLD_MANAGEMENT("world-management-service", "maxConcurrentGameInstances"); + + private final String service; + private final String quota; + + Owner(String service, String quota) { + this.service = service; + this.quota = quota; + } + + public String service() { + return service; + } + + public String quota() { + return quota; + } + } + + public enum Operation { + CAPACITY_CREATING, + NON_EXPANDING_RECOVERY + } + + public enum State { + RESERVED, + FINALIZED, + RELEASED, + QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION + } + + public record Identity(UUID tenantId, UUID requestId, UUID admissionId) { + public Identity { + uuid(tenantId); + uuid(requestId); + uuid(admissionId); + } + } + + /** Complete target resource shape, not the aggregate tenant usage counter. */ + public record Shape(long activeSessions, long concurrentGameInstances, long storageBytes) { + public Shape { + if (activeSessions < 0 || concurrentGameInstances < 0 || storageBytes < 0) throw invalid(); + } + + public long units(Owner owner) { + return owner == Owner.GAME_SESSION ? activeSessions : concurrentGameInstances; + } + } + + public sealed interface OwnerContext permits PlayerContext, WorldContext { + Owner owner(); + + UUID tenantId(); + + UUID gameInstanceId(); + } + + /** The exact typed PlayerExecutionContext, validated against Account's retained evaluation. */ + public record PlayerContext( + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + UUID gameInstanceId, + UUID characterId, + UUID sessionId, + UUID realmId, + UUID requestId, + String playableStateScope) + implements OwnerContext { + public PlayerContext { + uuid(accountId); + uuid(tenantId); + uuid(playableStateNamespaceId); + uuid(gameInstanceId); + uuid(characterId); + uuid(sessionId); + uuid(realmId); + uuid(requestId); + if (!"SHARED".equals(playableStateScope) && !"PRIVATE".equals(playableStateScope)) + throw invalid(); + } + + @Override + public Owner owner() { + return Owner.GAME_SESSION; + } + } + + /** Separate tenant/operation lifecycle context; never inferred from a player context. */ + public record WorldContext( + UUID tenantId, + UUID operationId, + UUID lifecycleId, + UUID gameInstanceId, + UUID ownerId, + long ownerFence) + implements OwnerContext { + public WorldContext { + uuid(tenantId); + uuid(operationId); + uuid(lifecycleId); + uuid(gameInstanceId); + uuid(ownerId); + if (ownerFence <= 0) throw invalid(); + } + + @Override + public Owner owner() { + return Owner.WORLD_MANAGEMENT; + } + } + + /** Exact, strictly decoded existing Account bundle. Bytes are never replaced by a subset/hash. */ + public static final class Evidence { + private final byte[] bytes; + private final Owner owner; + private final Map fields; + + private Evidence(byte[] bytes, Owner owner) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_EVIDENCE_BYTES) throw invalid(); + this.owner = Objects.requireNonNull(owner); + this.bytes = bytes.clone(); + fields = + owner == Owner.GAME_SESSION + ? RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(bytes).fields() + : RuntimeTenantOperationEntitlementEvidence.parseCanonical(bytes).fields(); + } + + public static Evidence player(RuntimePlayerAdmissionEntitlementEvidence value) { + return new Evidence(Objects.requireNonNull(value).canonicalBytes(), Owner.GAME_SESSION); + } + + public static Evidence world(RuntimeTenantOperationEntitlementEvidence value) { + return new Evidence(Objects.requireNonNull(value).canonicalBytes(), Owner.WORLD_MANAGEMENT); + } + + public static Evidence parse(byte[] bytes, Owner owner) { + return new Evidence(bytes, owner); + } + + public byte[] canonicalBytes() { + return bytes.clone(); + } + + public Map fields() { + return owner == Owner.GAME_SESSION + ? RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(bytes).fields() + : RuntimeTenantOperationEntitlementEvidence.parseCanonical(bytes).fields(); + } + + public Owner owner() { + return owner; + } + + public UUID tenantId() { + return UUID.fromString(text("tenantId")); + } + + public String snapshotIdentity() { + return text("snapshotIdentity"); + } + + public String evaluationIdentity() { + return text("evaluationIdentity"); + } + + public String callerWorkload() { + return text("callerWorkload"); + } + + public Instant evaluatedAt() { + return Instant.parse(text("evaluatedAt")); + } + + public Instant expiresAt() { + Instant freshness = evaluatedAt().plusSeconds(15); + if (owner == Owner.GAME_SESSION) { + Instant validity = Instant.parse(text("validUntil")); + if (validity.isBefore(freshness)) return validity; + } + return freshness; + } + + public void requireCurrent(Instant now) { + if (now.isBefore(evaluatedAt()) || !now.isBefore(expiresAt())) throw invalid(); + } + + public long quota() { + Object raw = fields.get("quotas"); + if (!(raw instanceof Map quotas) + || !(quotas.get(owner.quota()) instanceof String value)) throw invalid(); + return decimal(value); + } + + public boolean permitsCreation() { + return Boolean.TRUE.equals(fields.get("gameplayAvailable")) + && Boolean.TRUE.equals( + fields.get( + owner == Owner.GAME_SESSION + ? "allowNewGameplayBindings" + : "allowNewInstanceStarts")); + } + + private String text(String field) { + if (!(fields.get(field) instanceof String value)) throw invalid(); + return value; + } + + @Override + public boolean equals(Object other) { + return other instanceof Evidence value + && owner == value.owner + && Arrays.equals(bytes, value.bytes); + } + + @Override + public int hashCode() { + return 31 * owner.hashCode() + Arrays.hashCode(bytes); + } + + @Override + public String toString() { + return "CapacityEvidence[redacted]"; + } + } + + public record Request( + Identity identity, + UUID admissionAttemptId, + long capacityRearmFence, + String targetNamespace, + OwnerContext context, + Operation operation, + Shape priorShape, + Shape requestedShape, + Evidence evidence, + Long capacityDelta, + String mutationDigest) { + public Request { + Objects.requireNonNull(identity); + uuid(admissionAttemptId); + if (capacityRearmFence <= 0 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw invalid(); + Objects.requireNonNull(context); + Objects.requireNonNull(operation); + Objects.requireNonNull(priorShape); + Objects.requireNonNull(requestedShape); + Objects.requireNonNull(evidence); + if (!identity.tenantId().equals(context.tenantId()) + || !identity.tenantId().equals(evidence.tenantId()) + || context.owner() != evidence.owner() + || !expectedWorkload(targetNamespace, context.owner()).equals(evidence.callerWorkload())) + throw invalid(); + if (capacityDelta != null && capacityDelta < 0) throw invalid(); + if (mutationDigest != null && !mutationDigest.matches("[0-9a-f]{64}")) throw invalid(); + } + + public Request withDigest() { + return new Request( + identity, + admissionAttemptId, + capacityRearmFence, + targetNamespace, + context, + operation, + priorShape, + requestedShape, + evidence, + capacityDelta, + CapacityAdmissionDigest.digest(this)); + } + + public void requireCommittable() { + if (capacityDelta == null + || mutationDigest == null + || !mutationDigest.equals(CapacityAdmissionDigest.digest(this)) + || !identity.requestId().toString().equals(evidence.fields().get("requestId"))) + throw invalid(); + long net = + Math.subtractExact( + requestedShape.units(context.owner()), priorShape.units(context.owner())); + if (operation == Operation.CAPACITY_CREATING) { + if (capacityDelta <= 0 || net <= 0 || capacityDelta > net || !evidence.permitsCreation()) + throw invalid(); + // A scalar commitment cannot hide expansion in another resource dimension. + if (context.owner() == Owner.GAME_SESSION + ? requestedShape.concurrentGameInstances() > priorShape.concurrentGameInstances() + : requestedShape.activeSessions() > priorShape.activeSessions()) throw invalid(); + if (requestedShape.storageBytes() > priorShape.storageBytes()) throw invalid(); + } else if (capacityDelta != 0 + || requestedShape.activeSessions() > priorShape.activeSessions() + || requestedShape.concurrentGameInstances() > priorShape.concurrentGameInstances() + || requestedShape.storageBytes() > priorShape.storageBytes()) throw invalid(); + if (context instanceof PlayerContext player) { + if (!identity.requestId().equals(player.requestId())) throw invalid(); + var fields = evidence.fields(); + if (!player.accountId().toString().equals(fields.get("callerAccountId")) + || !(fields.get("target") instanceof Map target) + || !targetNamespace.equals(target.get("targetNamespace")) + || !player.realmId().toString().equals(target.get("realmId")) + || !player + .playableStateNamespaceId() + .toString() + .equals(target.get("playableStateNamespaceId")) + || !player.gameInstanceId().toString().equals(target.get("gameInstanceId")) + || !player.playableStateScope().equals(target.get("playableStateScope"))) + throw invalid(); + } else if (!identity.requestId().equals(((WorldContext) context).operationId())) + throw invalid(); + } + + @Override + public String toString() { + return "TenantCapacityRequest[redacted]"; + } + } + + public record Result( + Identity identity, + UUID admissionAttemptId, + long capacityRearmFence, + String mutationDigest, + UUID reservationId, + long reservationFence, + Instant expiresAt, + State state, + String snapshotIdentity, + String evaluationIdentity) { + public Result { + Objects.requireNonNull(identity); + uuid(admissionAttemptId); + uuid(reservationId); + if (capacityRearmFence <= 0 + || reservationFence <= 0 + || mutationDigest == null + || !mutationDigest.matches("[0-9a-f]{64}")) throw invalid(); + Objects.requireNonNull(expiresAt); + Objects.requireNonNull(state); + if (snapshotIdentity == null + || !snapshotIdentity.matches("sha256:[0-9a-f]{64}") + || evaluationIdentity == null + || !evaluationIdentity.matches("sha256:[0-9a-f]{64}")) throw invalid(); + } + + public void requireBinding(Request request) { + if (!identity.equals(request.identity()) + || !admissionAttemptId.equals(request.admissionAttemptId()) + || capacityRearmFence != request.capacityRearmFence() + || !mutationDigest.equals(request.mutationDigest()) + || !snapshotIdentity.equals(request.evidence().snapshotIdentity()) + || !evaluationIdentity.equals(request.evidence().evaluationIdentity()) + || !expiresAt.isAfter(request.evidence().evaluatedAt()) + || expiresAt.isAfter(request.evidence().expiresAt())) throw invalid(); + } + } + + public static long decimal(String value) { + if (value == null || !value.matches("0|[1-9][0-9]{0,18}")) throw invalid(); + try { + return Long.parseLong(value); + } catch (NumberFormatException overflow) { + throw invalid(); + } + } + + public static String expectedWorkload(String namespace, Owner owner) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw invalid(); + return "spiffe://firemud/ns/" + namespace + "/sa/" + owner.service(); + } + + public static UUID uuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) throw invalid(); + return value; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact bounded tenant capacity admission required"); + } +} diff --git a/services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json b/services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json new file mode 100644 index 0000000000..9048e0c312 --- /dev/null +++ b/services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json @@ -0,0 +1,19 @@ +{ + "actionFamilySchemaId": "capacity-admission", + "actionFamilySchemaVersion": "1", + "encoding": "mutationDigest/v1", + "outerFieldOrder": ["actionFamilySchemaId", "actionFamilySchemaVersion", "scope", "target", "expectedVersion", "mutation", "auditReason"], + "scope": {"order": ["tenantId", "requestId", "admissionId"], "types": ["string", "string", "string"]}, + "target": {"order": ["ownerService", "targetNamespace", "ownerContext"], "types": ["string", "string", "object"]}, + "playerContext": {"order": ["accountId", "tenantId", "playableStateNamespaceId", "gameInstanceId", "characterId", "sessionId", "realmId", "requestId", "playableStateScope"], "types": ["string", "string", "string", "string", "string", "string", "string", "string", "string"]}, + "worldContext": {"order": ["tenantId", "operationId", "lifecycleId", "gameInstanceId", "ownerId", "ownerFence"], "types": ["string", "string", "string", "string", "string", "number"]}, + "expectedVersion": {"order": ["admissionAttemptId", "capacityRearmFence"], "types": ["string", "number"]}, + "mutation": {"order": ["operation", "priorShape", "requestedShape", "accountEvidence", "capacityDelta"], "types": ["string", "object", "object", "string", "number-or-absent"]}, + "shape": {"order": ["activeSessions", "concurrentGameInstances", "storageBytes"], "types": ["number", "number", "number"]}, + "accountEvidence": {"content": "RFC 4648 padded base64 of the complete strict canonical account-auth-evidence-bundle/v1 bytes", "variants": {"game-session-service": "PLAYER_ADMISSION", "world-management-service": "TENANT_OPERATION"}, "validation": "Decode with the existing closed variant codec, including canonical re-encoding equality, before framing. This member binds every byte including bundleVersion, snapshotIdentity, evaluationIdentity, entitlement fields, complete authorityTuple, tenantBillingCutoff and outboxCheckpoints. No digest/subset/loose JSON substitute is accepted."}, + "auditReason": {"type": "string", "constant": "capacity-admission"}, + "capacityDelta": {"wire": "optional int64", "json": "canonical unsigned ASCII decimal string", "minimum": "0", "maximum": "9223372036854775807", "absentEncodingOnly": true, "absentCommitment": "REJECT", "null": "REJECT", "negative": "REJECT"}, + "limits": {"requestWireBytes": 294912, "evidenceBytes": 262144, "preimageBytes": 524288, "segmentBytes": 393216, "normalizedStringBytes": 360448, "objectMembers": 16, "numericBytes": 19, "numericScale": 0, "maximumCompositeDepth": 5}, + "sourceLimits": "The existing PLAYER_ADMISSION and TENANT_OPERATION strict decoders apply their bounded raw UTF-8, duplicate-key, nesting, token, member, array and canonical-reencoding checks before this family is framed.", + "status": "Published source contract and proof definitions only. World lifecycle and authoritative zero-delta prior-shape producers are held; this schema does not activate them." +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java new file mode 100644 index 0000000000..d7cc00ea89 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.common.account.capacity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Operation; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Shape; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +/** Shared vectors prove content encoding only, never a current Account or runtime grant. */ +class CapacityAdmissionDigestTest { + @Test + void sharedCorpusFixesCompleteEvidenceAndAbsentZeroPositiveBoundaryPreimages() throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + for (var vector : corpus.path("vectors")) { + Long delta = + vector.path("capacityDelta").isNull() + ? null + : TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText()); + Request base = CapacityAdmissionTestFixture.worldRequest(delta); + assertThat(Base64.getEncoder().encodeToString(base.evidence().canonicalBytes())) + .isEqualTo(corpus.path("request").path("canonicalAccountEvidenceBase64").asText()); + Request action = base; + if (vector.has("operation")) { + var prior = vector.path("priorShape"); + var requested = vector.path("requestedShape"); + action = + new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + Operation.valueOf(vector.path("operation").asText()), + new Shape( + TenantCapacityAdmission.decimal(prior.get(0).asText()), + TenantCapacityAdmission.decimal(prior.get(1).asText()), + TenantCapacityAdmission.decimal(prior.get(2).asText())), + new Shape( + TenantCapacityAdmission.decimal(requested.get(0).asText()), + TenantCapacityAdmission.decimal(requested.get(1).asText()), + TenantCapacityAdmission.decimal(requested.get(2).asText())), + base.evidence(), + delta, + null) + .withDigest(); + } + assertThat(HexFormat.of().formatHex(CapacityAdmissionDigest.preimage(action))) + .as(vector.path("name").asText()) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(CapacityAdmissionDigest.digest(action)) + .isEqualTo(vector.path("sha256").asText()); + Request exact = action; + if (vector.path("commitAllowed").asBoolean()) exact.requireCommittable(); + else + assertThatThrownBy(exact::requireCommittable) + .isInstanceOf(IllegalArgumentException.class); + } + } + assertThat(CapacityAdmissionTestFixture.worldRequest(null).mutationDigest()) + .isNotEqualTo(CapacityAdmissionTestFixture.worldRequest(0L).mutationDigest()); + } + + @Test + void decimalWireGrammarRejectsNegativesOverflowAndMalformedSpellingsBeforeHash() { + for (String value : + List.of("9223372036854775808", "-1", "+1", "01", "1e0", "1.0", " 1", "1 ")) { + assertThatThrownBy(() -> TenantCapacityAdmission.decimal(value)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat(TenantCapacityAdmission.decimal("0")).isZero(); + assertThat(TenantCapacityAdmission.decimal("9223372036854775807")).isEqualTo(Long.MAX_VALUE); + assertThatThrownBy(() -> assertThat(Math.addExact(Long.MAX_VALUE, 1)).isPositive()) + .isInstanceOf(ArithmeticException.class); + } + + @Test + void evidenceIsStrictCanonicalAndCompleteChangedFieldsAlterDigest() { + Request original = CapacityAdmissionTestFixture.worldRequest(17L); + String json = new String(original.evidence().canonicalBytes(), StandardCharsets.UTF_8); + for (String changed : + List.of( + " " + json, + json.replaceFirst("\"outboxSequence\":\"3\"", "\"outboxSequence\":\"4\""), + "{\"bundleVersion\":\"1\"," + json.substring(1))) { + assertThatThrownBy( + () -> + Evidence.parse(changed.getBytes(StandardCharsets.UTF_8), Owner.WORLD_MANAGEMENT)) + .isInstanceOf(IllegalArgumentException.class); + } + Evidence changed = + Evidence.parse( + json.replace("\"entitlementVersion\":\"7\"", "\"entitlementVersion\":\"8\"") + .getBytes(StandardCharsets.UTF_8), + Owner.WORLD_MANAGEMENT); + Request mutation = + new Request( + original.identity(), + original.admissionAttemptId(), + original.capacityRearmFence(), + original.targetNamespace(), + original.context(), + original.operation(), + original.priorShape(), + original.requestedShape(), + changed, + original.capacityDelta(), + null) + .withDigest(); + assertThat(mutation.mutationDigest()).isNotEqualTo(original.mutationDigest()); + byte[] copy = changed.canonicalBytes(); + copy[0] = 0; + assertThat(changed.canonicalBytes()[0]).isEqualTo((byte) '{'); + } + + @Test + void zeroCannotHideAnyChangedExpandingShape() { + Request original = CapacityAdmissionTestFixture.worldRequest(0L); + Request zero = + new Request( + original.identity(), + original.admissionAttemptId(), + original.capacityRearmFence(), + original.targetNamespace(), + original.context(), + Operation.NON_EXPANDING_RECOVERY, + new Shape(0, 1, 0), + new Shape(0, 1, 0), + original.evidence(), + 0L, + null) + .withDigest(); + zero.requireCommittable(); + for (Shape shape : List.of(new Shape(1, 1, 0), new Shape(0, 2, 0), new Shape(0, 1, 1))) { + var expanding = + new Request( + zero.identity(), + zero.admissionAttemptId(), + zero.capacityRearmFence(), + zero.targetNamespace(), + zero.context(), + zero.operation(), + zero.priorShape(), + shape, + zero.evidence(), + 0L, + null) + .withDigest(); + assertThatThrownBy(expanding::requireCommittable) + .isInstanceOf(IllegalArgumentException.class); + assertThat(expanding.mutationDigest()).isNotEqualTo(zero.mutationDigest()); + } + } +} diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java new file mode 100644 index 0000000000..8aa017c4b5 --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java @@ -0,0 +1,285 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; + +/** + * Controlled content only. Nothing here authenticates a source, initializes usage or admits play. + */ +public final class CapacityAdmissionTestFixture { + public static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + public static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + public static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); + public static final UUID ADMISSION = UUID.fromString("44444444-4444-4444-8444-444444444444"); + public static final UUID ATTEMPT = UUID.fromString("55555555-5555-4555-8555-555555555555"); + public static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + public static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final String HASH = "a".repeat(64); + + private CapacityAdmissionTestFixture() {} + + public static RuntimePlayerAdmissionEntitlementEvidence playerEvidence() { + return capture(target(), facts(), sources(), NOW); + } + + public static TenantCapacityAdmission.Request playerRequest() { + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(TENANT, REQUEST, ADMISSION), + ATTEMPT, + 1, + "prod", + new TenantCapacityAdmission.PlayerContext( + ACCOUNT, TENANT, REQUEST, REQUEST, ACCOUNT, ADMISSION, REQUEST, REQUEST, "SHARED"), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(1, 0, 0), + TenantCapacityAdmission.Evidence.player(playerEvidence()), + 1L, + null) + .withDigest(); + } + + public static TenantCapacityAdmission.Request worldRequest(Long delta) { + String tenant = TENANT.toString(); + String stream = "account:auth-authority:v1:tenant/" + tenant; + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-auth-evidence-bundle/v1"); + fields.put("variant", "TENANT_OPERATION"); + fields.put("bundleVersion", "1"); + fields.put("authorityAvailability", "AVAILABLE"); + fields.put("tenantId", tenant); + fields.put("requestId", REQUEST.toString()); + fields.put("callerWorkload", "spiffe://firemud/ns/prod/sa/world-management-service"); + fields.put("sourceKind", "PAID_HOSTING"); + fields.put("subscriptionStatus", "active"); + fields.put("provisioningStatus", null); + fields.put("gameplayAvailable", true); + fields.put("allowPublicJoin", true); + fields.put("allowNewGameplayBindings", true); + fields.put("allowNewInstanceStarts", true); + fields.put( + "quotas", + Map.of( + "maxActiveSessions", + "100", + "maxConcurrentGameInstances", + Long.toString(Long.MAX_VALUE), + "maxStorageBytes", + "1048576")); + fields.put("entitlementVersion", "7"); + fields.put("tenantBillingSequence", "11"); + fields.put("tenantAuthorityGeneration", "5"); + fields.put("evaluatedAt", NOW.toString()); + fields.put("snapshotIdentity", "sha256:" + "a".repeat(64)); + fields.put("evaluationIdentity", "sha256:" + "b".repeat(64)); + fields.put( + "authorityTuple", + Map.of( + "tenantAuthorityGeneration", + Map.of(tenant, "5"), + "tenantBillingCutoff", + Map.of( + tenant, + Map.of( + "tenantAuthorityGeneration", + "5", + "tenantBillingSequence", + "11", + "outboxStreamKey", + stream, + "outboxSequence", + "3")))); + fields.put( + "outboxCheckpoints", + List.of( + Map.of( + "outboxStreamKey", + stream, + "outboxSequence", + "3", + "sourceEventId", + ACCOUNT.toString(), + "sourceEventDigest", + "sha256:" + "a".repeat(64)))); + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(TENANT, REQUEST, ADMISSION), + ATTEMPT, + 1, + "prod", + new TenantCapacityAdmission.WorldContext( + TENANT, REQUEST, ADMISSION, ACCOUNT, ATTEMPT, 7), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(0, Long.MAX_VALUE, 0), + TenantCapacityAdmission.Evidence.world( + RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields)), + delta, + null) + .withDigest(); + } + + private static RuntimePlayerAdmissionEntitlementEvidence capture( + Map target, + Map facts, + Map source, + Instant at) { + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); + } + + private static Map target() { + Map target = new LinkedHashMap<>(); + target.put("targetClass", "PUBLIC_PRODUCTION"); + target.put("characterCreationPolicy", "PRESEEDED_ONLY"); + target.put("targetNamespace", "prod"); + target.put("tenantId", TENANT.toString()); + target.put("tenantSlug", "tenant"); + target.put("worldSlug", "world"); + target.put("realmId", REQUEST.toString()); + target.put("realmSlug", "production"); + target.put("playableStateNamespaceId", REQUEST.toString()); + target.put("playableStateScope", "SHARED"); + target.put("gameInstanceId", REQUEST.toString()); + target.put("canonicalVersionId", REQUEST.toString()); + target.put("catalogRevision", "7"); + target.put("pointerVersion", "3"); + target.put("activeWorldEpoch", "5"); + target.put("evaluatedAt", NOW.minusSeconds(20).toString()); + target.put("connectScopeExpiresAt", NOW.plusSeconds(120).toString()); + return target; + } + + private static Map facts() { + Map facts = new LinkedHashMap<>(); + facts.put("sourceKind", "NON_PAID_DEMO"); + facts.put("subscriptionStatus", null); + facts.put("provisioningStatus", null); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) facts.put(flag, true); + facts.put( + "quotas", + Map.of( + "maxActiveSessions", + "3", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "4096")); + facts.put("entitlementVersion", "1"); + facts.put("tenantBillingSequence", "1"); + facts.put("tenantAuthorityGeneration", "2"); + return facts; + } + + private static Map sources() { + Map source = new LinkedHashMap<>(); + source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); + source.put("paidReceiptValidUntil", null); + for (String key : + List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + source.put(key, REQUEST.toString()); + for (String key : + List.of( + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "admissionPointerSnapshotDigest")) source.put(key, HASH); + for (String key : + List.of( + "scopeDigest", + "entitlementSourceDigest", + "gameSessionOwnerProofDigest", + "publishedPolicySetDigest", + "worldLifecycleDigest")) source.put(key, "sha256:" + HASH); + source.put("worldRowVersion", "0"); + return source; + } + + private static Snapshot membership() { + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", REQUEST, "world", "World", null); + var source = + new FreshTenantCreationEvidence( + 1, + "prod", + REQUEST, + REQUEST, + requestDigest, + TENANT, + 17, + "world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", REQUEST, REQUEST, requestDigest, TENANT, 17, "world", "NEW_GAME_ROW")); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + REQUEST, "sha256:" + HASH, TENANT, source.creationRequestId(), source.requestDigest()); + var billing = + new TenantAuthorityEventV1Codec.BillingReceipt( + TENANT, + REQUEST, + "sha256:" + HASH, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(TENANT), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(REQUEST), + "sha256:" + HASH); + var event = TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, billing); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(TENANT.toString(), "2"), + Map.of(TENANT.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of( + Map.of( + TENANT.toString(), + new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + return new Snapshot( + "firemud-account-service", + ACCOUNT.toString(), + TENANT.toString(), + false, + "MISSING", + false, + Map.of(TENANT.toString(), "1"), + "1", + List.of(), + tuple, + "1", + List.of( + new Checkpoint(prefix + "account/" + ACCOUNT, "0"), + new Checkpoint(prefix + "issuer/firemud-account-service", "0"), + new Checkpoint(prefix + "membership/" + ACCOUNT + "/" + TENANT, "0"), + new Checkpoint(event.outboxStreamKey(), "1")), + List.of( + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)))); + } +} diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json new file mode 100644 index 0000000000..7e1632b65d --- /dev/null +++ b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json @@ -0,0 +1,190 @@ +{ + "schema": "capacity-admission/1", + "validation": "UNRUN: artifact authoring only; not source or runtime proof", + "request": { + "tenantId": "22222222-2222-4222-8222-222222222222", + "requestId": "33333333-3333-4333-8333-333333333333", + "admissionId": "44444444-4444-4444-8444-444444444444", + "admissionAttemptId": "55555555-5555-4555-8555-555555555555", + "capacityRearmFence": "1", + "targetNamespace": "prod", + "ownerService": "world-management-service", + "ownerContext": { + "tenantId": "22222222-2222-4222-8222-222222222222", + "operationId": "33333333-3333-4333-8333-333333333333", + "lifecycleId": "44444444-4444-4444-8444-444444444444", + "gameInstanceId": "11111111-1111-4111-8111-111111111111", + "ownerId": "55555555-5555-4555-8555-555555555555", + "ownerFence": "7" + }, + "operation": "CAPACITY_CREATING", + "priorShape": [ + "0", + "0", + "0" + ], + "requestedShape": [ + "0", + "9223372036854775807", + "0" + ], + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5VHVwbGUiOnsidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiI1In0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiMyIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiI1IiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMTEifX19LCJidW5kbGVWZXJzaW9uIjoiMSIsImNhbGxlcldvcmtsb2FkIjoic3BpZmZlOi8vZmlyZW11ZC9ucy9wcm9kL3NhL3dvcmxkLW1hbmFnZW1lbnQtc2VydmljZSIsImVudGl0bGVtZW50VmVyc2lvbiI6IjciLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDJUMDA6MDA6MDBaIiwiZXZhbHVhdGlvbklkZW50aXR5Ijoic2hhMjU2OmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLCJnYW1lcGxheUF2YWlsYWJsZSI6dHJ1ZSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMyIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInNvdXJjZUV2ZW50RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzb3VyY2VFdmVudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIn1dLCJwcm92aXNpb25pbmdTdGF0dXMiOm51bGwsInF1b3RhcyI6eyJtYXhBY3RpdmVTZXNzaW9ucyI6IjEwMCIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiOTIyMzM3MjAzNjg1NDc3NTgwNyIsIm1heFN0b3JhZ2VCeXRlcyI6IjEwNDg1NzYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwic2NoZW1hIjoiYWNjb3VudC1hdXRoLWV2aWRlbmNlLWJ1bmRsZS92MSIsInNuYXBzaG90SWRlbnRpdHkiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInNvdXJjZUtpbmQiOiJQQUlEX0hPU1RJTkciLCJzdWJzY3JpcHRpb25TdGF0dXMiOiJhY3RpdmUiLCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjoiNSIsInRlbmFudEJpbGxpbmdTZXF1ZW5jZSI6IjExIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YXJpYW50IjoiVEVOQU5UX09QRVJBVElPTiJ9" + }, + "vectors": [ + { + "name": "absent", + "capacityDelta": null, + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323431383a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a616273656e7430303a31313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "34da579bb6e881688bc1481a3d8fc910a7e4eee81bc008c5991d31fce179e845", + "commitAllowed": false + }, + { + "name": "present-zero", + "capacityDelta": "0", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323431393a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d62657231313a3031313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "3c80f1967fdb3d87875fc852e306681d7d8b86521f286b7f3896696ded5a9c59", + "commitAllowed": false + }, + { + "name": "present-seventeen", + "capacityDelta": "17", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323432303a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d62657231323a313731313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "61877a450478b0ce6b980f8d502ff027e5248c736444897c9dc536d924b1ee55", + "commitAllowed": true + }, + { + "name": "present-int64-max", + "capacityDelta": "9223372036854775807", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323433383a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d6265723131393a3932323333373230333638353437373538303731313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "04ba8983d5c1b5f82ed29498bbec78a6e4b8390839525112ec2c8c969f1831bc", + "commitAllowed": true + }, + { + "name": "non-expanding-zero", + "capacityDelta": "0", + "operation": "NON_EXPANDING_RECOVERY", + "priorShape": [ + "0", + "1", + "0" + ], + "requestedShape": [ + "0", + "1", + "0" + ], + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323430343a313a35393a6f7065726174696f6e363a737472696e673132323a4e4f4e5f455850414e44494e475f5245434f5645525931303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3131323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3131323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d62657231313a3031313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "c93ecc41111c5440dfa53da14b7a564a5148a5411221abe15251ad59859ee3cb", + "commitAllowed": true + } + ], + "rejected": [ + { + "name": "delta-0", + "capacityDelta": "9223372036854775808", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-1", + "capacityDelta": "-1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-2", + "capacityDelta": "+1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-3", + "capacityDelta": "01", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-4", + "capacityDelta": "1e0", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-5", + "capacityDelta": "1.0", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-6", + "capacityDelta": " 1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-7", + "capacityDelta": "1 ", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-8", + "capacityDelta": 1, + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-9", + "capacityDelta": 0.0, + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-10", + "capacityDelta": null, + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "usage-addition-overflow", + "usage": "9223372036854775807", + "held": "0", + "capacityDelta": "1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "held-addition-overflow", + "usage": "0", + "held": "9223372036854775807", + "capacityDelta": "1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "changed-shape", + "requestedShape": [ + "1", + "9223372036854775807", + "0" + ], + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "changed-cutoff-without-checkpoint", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "noncanonical-evidence-whitespace", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "duplicate-evidence-member", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + } + ] +} diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py new file mode 100644 index 0000000000..d3c77a6a61 --- /dev/null +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -0,0 +1,129 @@ +"""Independent capacity-admission/1 corpus consumer. Encoding proof, not runtime authority.""" +import base64 +import hashlib +import json +from pathlib import Path +import re +import unicodedata +import unittest + +MAX = 9223372036854775807 + + +def decimal(value): + if not isinstance(value, str) or not re.fullmatch(r"0|[1-9][0-9]{0,18}", value): + raise ValueError("canonical int64 decimal string required") + result = int(value) + if result > MAX: + raise ValueError("int64 overflow") + return result + + +def segment(value): + if len(value) > 393216: + raise ValueError("segment bound") + return str(len(value)).encode("ascii") + b":" + value + + +def value(kind, payload, present=True): + return segment(kind.encode("ascii")) + (b"1" if present else b"0") + segment(payload) + + +def string(text): + encoded = unicodedata.normalize("NFC", text).encode("utf-8", "strict") + if len(encoded) > 360448: + raise ValueError("string bound") + return value("string", encoded) + + +def number(text): + return value("number", str(decimal(text)).encode("ascii")) + + +def obj(fields): + return value("object", segment(str(len(fields)).encode("ascii")) + b"".join( + segment(key.encode("ascii")) + item for key, item in fields)) + + +def shape(values): + return obj(list(zip(("activeSessions", "concurrentGameInstances", "storageBytes"), + (number(v) for v in values)))) + + +def reject_duplicates(pairs): + result = {} + for key, item in pairs: + if key in result: + raise ValueError("duplicate member") + result[key] = item + return result + + +def evidence(encoded): + raw = base64.b64decode(encoded, validate=True) + if not 0 < len(raw) <= 262144: + raise ValueError("evidence bound") + parsed = json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=reject_duplicates) + canonical = json.dumps(parsed, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + if raw != canonical or parsed["schema"] != "account-auth-evidence-bundle/v1" or parsed["variant"] != "TENANT_OPERATION": + raise ValueError("exact canonical variant required") + tenant = parsed["tenantId"] + cutoff = parsed["authorityTuple"]["tenantBillingCutoff"][tenant] + points = parsed["outboxCheckpoints"] + if len(points) != 1 or any(cutoff[k] != points[0][k] for k in ("outboxStreamKey", "outboxSequence")): + raise ValueError("cutoff checkpoint mismatch") + return encoded + + +def preimage(request, candidate): + context = request["ownerContext"] + fields = [ + ("actionFamilySchemaId", string("capacity-admission")), + ("actionFamilySchemaVersion", string("1")), + ("scope", obj([(key, string(request[key])) for key in ("tenantId", "requestId", "admissionId")])), + ("target", obj([("ownerService", string(request["ownerService"])), + ("targetNamespace", string(request["targetNamespace"])), + ("ownerContext", obj([(key, string(context[key])) for key in + ("tenantId", "operationId", "lifecycleId", "gameInstanceId", "ownerId")] + + [("ownerFence", number(context["ownerFence"]))]))])), + ("expectedVersion", obj([("admissionAttemptId", string(request["admissionAttemptId"])), + ("capacityRearmFence", number(request["capacityRearmFence"]))])), + ("mutation", obj([("operation", string(candidate.get("operation", request["operation"]))), + ("priorShape", shape(candidate.get("priorShape", request["priorShape"]))), + ("requestedShape", shape(candidate.get("requestedShape", request["requestedShape"]))), + ("accountEvidence", string(evidence(request["canonicalAccountEvidenceBase64"]))), + ("capacityDelta", value("absent", b"", False) if candidate["capacityDelta"] is None + else number(candidate["capacityDelta"]))])), + ("auditReason", string("capacity-admission"))] + result = segment(b"mutationDigest/v1") + b"".join(segment(key.encode("ascii")) + item for key, item in fields) + if len(result) > 524288: + raise ValueError("preimage bound") + return result + + +class CapacityAdmissionVectors(unittest.TestCase): + def test_shared_golden_preimages_and_digests(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + digests = [] + for candidate in corpus["vectors"]: + with self.subTest(candidate["name"]): + encoded = preimage(corpus["request"], candidate) + self.assertEqual(encoded.hex(), candidate["preimageHex"]) + digest = hashlib.sha256(encoded).hexdigest() + self.assertEqual(digest, candidate["sha256"]) + digests.append(digest) + self.assertNotEqual(digests[0], digests[1]) + + def test_rejected_delta_candidates_and_checked_addition(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + for candidate in corpus["rejected"]: + if candidate["name"].startswith("delta-"): + with self.subTest(candidate["name"]), self.assertRaises(ValueError): + decimal(candidate["capacityDelta"]) + if "usage" in candidate: + occupied = decimal(candidate["usage"]) + decimal(candidate["held"]) + decimal(candidate["capacityDelta"]) + self.assertGreater(occupied, MAX) + + +if __name__ == "__main__": + unittest.main() diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java new file mode 100644 index 0000000000..53232eeda6 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -0,0 +1,228 @@ +package net.firedevops.firemud.common.account.capacity; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.account.v1.TenantCapacityAdmissionAttempt; +import net.firedevops.firemud.account.v1.TenantCapacityAdmissionCommitment; +import net.firedevops.firemud.account.v1.TenantCapacityPlayerContext; +import net.firedevops.firemud.account.v1.TenantCapacityShape; +import net.firedevops.firemud.account.v1.TenantCapacityWorldContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Operation; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.OwnerContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Shape; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext; + +/** Strict bounded content mapping. TLS identity and source authority are never codec inputs. */ +public final class TenantCapacityAdmissionGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 288 * 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = 4096; + public static final long CALL_DEADLINE_SECONDS = 5; + + private TenantCapacityAdmissionGrpcCodec() {} + + public static CommitTenantCapacityAdmissionRequest toRequest(Request value) { + value.requireCommittable(); + var attempt = + TenantCapacityAdmissionAttempt.newBuilder() + .addTenantId(value.identity().tenantId().toString()) + .addRequestId(value.identity().requestId().toString()) + .addAdmissionId(value.identity().admissionId().toString()) + .addAdmissionAttemptId(value.admissionAttemptId().toString()) + .addCapacityRearmFence(value.capacityRearmFence()) + .addTargetNamespace(value.targetNamespace()) + .addOperation(value.operation().name()) + .addPriorShape(shape(value.priorShape())) + .addRequestedShape(shape(value.requestedShape())) + .addCanonicalAccountEvidence(ByteString.copyFrom(value.evidence().canonicalBytes())) + .addMutationDigest(value.mutationDigest()); + if (value.context() instanceof PlayerContext player) attempt.addPlayerContext(player(player)); + else attempt.addWorldContext(world((WorldContext) value.context())); + var wire = + CommitTenantCapacityAdmissionRequest.newBuilder() + .addAttempt(attempt) + .setCapacityDelta(value.capacityDelta()) + .build(); + clean(wire, MAX_REQUEST_WIRE_BYTES); + return wire; + } + + public static Request parseRequest(CommitTenantCapacityAdmissionRequest wire) { + clean(wire, MAX_REQUEST_WIRE_BYTES); + if (!wire.hasCapacityDelta() || wire.getCapacityDelta() < 0) throw invalid(); + var attempt = one(wire.getAttemptList()); + clean(attempt, MAX_REQUEST_WIRE_BYTES); + OwnerContext context; + if (attempt.getPlayerContextCount() == 1 && attempt.getWorldContextCount() == 0) + context = player(one(attempt.getPlayerContextList())); + else if (attempt.getWorldContextCount() == 1 && attempt.getPlayerContextCount() == 0) + context = world(one(attempt.getWorldContextList())); + else throw invalid(); + var request = + new Request( + new Identity( + uuid(one(attempt.getTenantIdList())), + uuid(one(attempt.getRequestIdList())), + uuid(one(attempt.getAdmissionIdList()))), + uuid(one(attempt.getAdmissionAttemptIdList())), + one(attempt.getCapacityRearmFenceList()), + one(attempt.getTargetNamespaceList()), + context, + Operation.valueOf(one(attempt.getOperationList())), + shape(one(attempt.getPriorShapeList())), + shape(one(attempt.getRequestedShapeList())), + Evidence.parse( + one(attempt.getCanonicalAccountEvidenceList()).toByteArray(), context.owner()), + wire.getCapacityDelta(), + one(attempt.getMutationDigestList())); + request.requireCommittable(); + return request; + } + + public static CommitTenantCapacityAdmissionResponse toResponse(Request request, Result result) { + result.requireBinding(request); + var wire = + CommitTenantCapacityAdmissionResponse.newBuilder() + .addCommitment( + TenantCapacityAdmissionCommitment.newBuilder() + .addTenantId(result.identity().tenantId().toString()) + .addRequestId(result.identity().requestId().toString()) + .addAdmissionId(result.identity().admissionId().toString()) + .addAdmissionAttemptId(result.admissionAttemptId().toString()) + .addCapacityRearmFence(result.capacityRearmFence()) + .addMutationDigest(result.mutationDigest()) + .addReservationId(result.reservationId().toString()) + .addReservationFence(result.reservationFence()) + .addExpiresAt(result.expiresAt().toString()) + .addState(result.state().name()) + .addSnapshotIdentity(result.snapshotIdentity()) + .addEvaluationIdentity(result.evaluationIdentity())) + .build(); + clean(wire, MAX_RESPONSE_WIRE_BYTES); + return wire; + } + + public static Result requireResponse( + Request request, CommitTenantCapacityAdmissionResponse wire) { + clean(wire, MAX_RESPONSE_WIRE_BYTES); + var result = one(wire.getCommitmentList()); + clean(result, MAX_RESPONSE_WIRE_BYTES); + String expires = one(result.getExpiresAtList()); + Instant instant = Instant.parse(expires); + if (!instant.toString().equals(expires)) throw invalid(); + var parsed = + new Result( + new Identity( + uuid(one(result.getTenantIdList())), + uuid(one(result.getRequestIdList())), + uuid(one(result.getAdmissionIdList()))), + uuid(one(result.getAdmissionAttemptIdList())), + one(result.getCapacityRearmFenceList()), + one(result.getMutationDigestList()), + uuid(one(result.getReservationIdList())), + one(result.getReservationFenceList()), + instant, + State.valueOf(one(result.getStateList())), + one(result.getSnapshotIdentityList()), + one(result.getEvaluationIdentityList())); + parsed.requireBinding(request); + return parsed; + } + + private static TenantCapacityShape shape(Shape value) { + return TenantCapacityShape.newBuilder() + .addActiveSessions(value.activeSessions()) + .addConcurrentGameInstances(value.concurrentGameInstances()) + .addStorageBytes(value.storageBytes()) + .build(); + } + + private static Shape shape(TenantCapacityShape wire) { + clean(wire, 128); + return new Shape( + one(wire.getActiveSessionsList()), + one(wire.getConcurrentGameInstancesList()), + one(wire.getStorageBytesList())); + } + + private static TenantCapacityPlayerContext player(PlayerContext player) { + return TenantCapacityPlayerContext.newBuilder() + .addAccountId(player.accountId().toString()) + .addTenantId(player.tenantId().toString()) + .addPlayableStateNamespaceId(player.playableStateNamespaceId().toString()) + .addGameInstanceId(player.gameInstanceId().toString()) + .addCharacterId(player.characterId().toString()) + .addSessionId(player.sessionId().toString()) + .addRealmId(player.realmId().toString()) + .addRequestId(player.requestId().toString()) + .addPlayableStateScope(player.playableStateScope()) + .build(); + } + + private static PlayerContext player(TenantCapacityPlayerContext wire) { + clean(wire, 1024); + return new PlayerContext( + uuid(one(wire.getAccountIdList())), + uuid(one(wire.getTenantIdList())), + uuid(one(wire.getPlayableStateNamespaceIdList())), + uuid(one(wire.getGameInstanceIdList())), + uuid(one(wire.getCharacterIdList())), + uuid(one(wire.getSessionIdList())), + uuid(one(wire.getRealmIdList())), + uuid(one(wire.getRequestIdList())), + one(wire.getPlayableStateScopeList())); + } + + private static TenantCapacityWorldContext world(WorldContext value) { + return TenantCapacityWorldContext.newBuilder() + .addTenantId(value.tenantId().toString()) + .addOperationId(value.operationId().toString()) + .addLifecycleId(value.lifecycleId().toString()) + .addGameInstanceId(value.gameInstanceId().toString()) + .addOwnerId(value.ownerId().toString()) + .addOwnerFence(value.ownerFence()) + .build(); + } + + private static WorldContext world(TenantCapacityWorldContext wire) { + clean(wire, 1024); + return new WorldContext( + uuid(one(wire.getTenantIdList())), + uuid(one(wire.getOperationIdList())), + uuid(one(wire.getLifecycleIdList())), + uuid(one(wire.getGameInstanceIdList())), + uuid(one(wire.getOwnerIdList())), + one(wire.getOwnerFenceList())); + } + + private static UUID uuid(String raw) { + UUID parsed = UUID.fromString(raw); + if (!parsed.toString().equals(raw)) throw invalid(); + return TenantCapacityAdmission.uuid(parsed); + } + + private static T one(List values) { + if (values.size() != 1) throw invalid(); + return values.getFirst(); + } + + private static void clean(Message message, int maximum) { + if (message == null + || message.getSerializedSize() > maximum + || !message.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact bounded capacity protobuf required"); + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java new file mode 100644 index 0000000000..59f209338b --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -0,0 +1,149 @@ +package net.firedevops.firemud.common.account.capacity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import org.junit.jupiter.api.Test; + +class TenantCapacityAdmissionGrpcCodecTest { + @Test + void exactBothAlternativesRoundTripWithCompleteBundleAndReservationBinding() { + for (Request request : + List.of( + CapacityAdmissionTestFixture.playerRequest(), + CapacityAdmissionTestFixture.worldRequest(17L))) { + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + assertThat(wire.hasCapacityDelta()).isTrue(); + assertThat(TenantCapacityAdmissionGrpcCodec.parseRequest(wire)).isEqualTo(request); + Result result = result(request); + assertThat( + TenantCapacityAdmissionGrpcCodec.requireResponse( + request, TenantCapacityAdmissionGrpcCodec.toResponse(request, result))) + .isEqualTo(result); + } + } + + @Test + void absentNegativeDuplicateUnknownAndMixedCallerContextFailBeforeCommit() { + Request request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(999, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var world = + TenantCapacityAdmissionGrpcCodec.toRequest(CapacityAdmissionTestFixture.worldRequest(17L)); + for (var bad : + List.of( + wire.toBuilder().clearCapacityDelta().build(), + wire.toBuilder().setCapacityDelta(-1).build(), + wire.toBuilder().addAttempt(wire.getAttempt(0)).build(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setAttempt( + 0, + wire.getAttempt(0).toBuilder() + .addWorldContext(world.getAttempt(0).getWorldContext(0))) + .build(), + wire.toBuilder() + .setAttempt(0, wire.getAttempt(0).toBuilder().addCapacityRearmFence(1)) + .build(), + wire.toBuilder() + .setAttempt( + 0, + wire.getAttempt(0).toBuilder() + .setPlayerContext( + 0, + wire.getAttempt(0).getPlayerContext(0).toBuilder() + .addSessionId( + wire.getAttempt(0).getPlayerContext(0).getSessionId(0)))) + .build(), + wire.toBuilder() + .setAttempt( + 0, + wire.getAttempt(0).toBuilder() + .setPlayerContext( + 0, + wire.getAttempt(0).getPlayerContext(0).toBuilder() + .setUnknownFields(unknown))) + .build())) { + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.parseRequest(bad)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void presentZeroSurvivesOnlyExplicitNonExpandingClassification() { + Request base = CapacityAdmissionTestFixture.worldRequest(0L); + Request zero = + new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + TenantCapacityAdmission.Operation.NON_EXPANDING_RECOVERY, + new TenantCapacityAdmission.Shape(0, 1, 0), + new TenantCapacityAdmission.Shape(0, 1, 0), + base.evidence(), + 0L, + null) + .withDigest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(zero); + assertThat(wire.hasCapacityDelta()).isTrue(); + assertThat(TenantCapacityAdmissionGrpcCodec.parseRequest(wire).capacityDelta()).isZero(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRequest(base)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void responseCannotSubstituteAttemptDigestFenceOrEvidenceIdentity() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); + for (var bad : + List.of( + wire.toBuilder().addCommitment(wire.getCommitment(0)).build(), + wire.toBuilder() + .setCommitment(0, wire.getCommitment(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(), + wire.toBuilder() + .setCommitment( + 0, wire.getCommitment(0).toBuilder().setMutationDigest(0, "b".repeat(64))) + .build(), + wire.toBuilder() + .setCommitment( + 0, + wire.getCommitment(0).toBuilder() + .setEvaluationIdentity(0, "sha256:" + "b".repeat(64))) + .build(), + wire.toBuilder() + .setCommitment( + 0, + wire.getCommitment(0).toBuilder() + .setExpiresAt(0, request.evidence().expiresAt().plusSeconds(1).toString())) + .build())) { + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(request, bad)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static Result result(Request request) { + return new Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.randomUUID(), + 1, + CapacityAdmissionTestFixture.NOW.plusSeconds(15), + State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java new file mode 100644 index 0000000000..94e43379f5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.time.Clock; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** + * Unregistered exact Account capacity adapter. It performs no admission or owner activation CAS. + */ +public final class AccountTenantCapacityClient + extends AbstractReloadingBlockingGrpcClient { + private final String namespace; + private final String expectedPeer; + + public AccountTenantCapacityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace, + Clock clock) { + super( + endpoints, + requireFileBackedMtls(tls, "Tenant capacity commitment"), + channels, + AccountTenantCapacityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + this.expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + Objects.requireNonNull(clock); + } + + public void init() throws IOException { + requireNoAmbientSql("Capacity client initialization requires no SQL transaction"); + initOnce("Capacity client is closed", "Account capacity unavailable"); + } + + /** + * The caller must obtain its typed context from current owned player state, not text/metadata. + * Retries retain this exact request. A timeout is indeterminate and never allocates another ID. + */ + public Result commit(Request request) { + requireNoAmbientSql("Capacity commitment requires no ambient SQL"); + request.requireCommittable(); + if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION + || !namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Exact Game Session context required"); + var stub = + requireInitializedStub("Account capacity unavailable") + .withDeadlineAfter( + TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withMaxOutboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withMaxInboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + Result result = + TenantCapacityAdmissionGrpcCodec.requireResponse( + request, + stub.commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request))); + // Exact retry may replay an expired/terminal reservation. Returning it grants no activation; + // the selected owner's final CAS must compare its current reservation fence and expiry. + return result; + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountServiceGrpc.AccountServiceBlockingStub buildStub(ManagedChannel channel) { + return AccountServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeer)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java new file mode 100644 index 0000000000..b2f458f359 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.time.Clock; +import java.time.ZoneOffset; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** Real loopback mTLS with a controlled Account result; not Account sources or final admission. */ +@Timeout(90) +class AccountTenantCapacityClientMtlsTest { + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Capacity client test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "client", "spiffe://firemud/ns/prod/sa/game-session-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/prod/sa/account-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong", "spiffe://firemud/ns/prod/sa/world-management-service", true)); + } + + @Test + void exactAccountPeerReceivesCompleteRequestAndExactRetryKeepsReservation() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("account", calls, false); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var first = client.commit(request); + assertThat(client.commit(request)).isEqualTo(first); + assertThat(first.identity()).isEqualTo(request.identity()); + assertThat(calls).hasValue(2); + } finally { + stop(server); + } + } + + @Test + void wrongAccountPeerIsRejectedBeforeRequestBodyRelease() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("wrong", calls, false); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.commit(CapacityAdmissionTestFixture.playerRequest())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + + @Test + void changedResponseFenceCannotSubstituteForOriginalCommitment() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("account", calls, true); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.commit(CapacityAdmissionTestFixture.playerRequest())) + .isInstanceOf(IllegalArgumentException.class); + } finally { + stop(server); + } + } + + private static AccountTenantCapacityClient client(Server server) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new AccountTenantCapacityClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + "prod", + Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC)); + } + + private static Server server(String identity, AtomicInteger calls, boolean wrongFence) + throws Exception { + UUID reservationId = UUID.randomUUID(); + var service = + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo("spiffe://firemud/ns/prod/sa/game-session-service"); + var request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + var result = + new TenantCapacityAdmission.Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + reservationId, + 1, + request.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + var response = TenantCapacityAdmissionGrpcCodec.toResponse(request, result); + if (wrongFence) + response = + response.toBuilder() + .setCommitment( + 0, response.getCommitment(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(); + observer.onNext(response); + observer.onCompleted(); + } + }; + var peer = pki.identity(identity); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(peer.privateKey(), peer.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } +} From fb56d3bc465155644323c472496e91e3a0433853 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 05:30:31 +1300 Subject: [PATCH 02/52] Repair tenant capacity persistence and proof contracts --- .../AccountTenantCapacityRepository.java | 4 +-- .../service/AccountTenantCapacityOwner.java | 2 +- .../AccountTenantCapacityRecoveryWorker.java | 6 ++-- ...alJoinScopePersistenceIntegrationTest.java | 11 +++--- ...tionCompletionPostgresIntegrationTest.java | 2 +- .../test_capacity_admission_vectors.py | 2 +- ...untRuntimeStubServerCompatibilityTest.java | 36 +++++++++++++++++-- 7 files changed, 49 insertions(+), 14 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java index 90e392668f..9ab7e4ac68 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -42,7 +42,7 @@ private void retain(Evidence evidence) { dsl.execute( "INSERT INTO account_tenant_capacity_evaluations " + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (evaluation_identity) DO NOTHING", + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (evaluation_identity) DO NOTHING", evidence.evaluationIdentity(), evidence.snapshotIdentity(), evidence.tenantId(), @@ -141,7 +141,7 @@ public Result create(Request request, Instant expiresAt) { dsl.execute( "INSERT INTO account_tenant_capacity_reservations " + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, admission_attempt_id, capacity_rearm_fence, reservation_fence, mutation_digest, canonical_payload, evaluation_identity, capacity_delta, expires_at, reconcile_deadline, state, execution_status) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'RESERVED', 'OWNER_EXECUTION_PENDING')", + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING')", request.identity().tenantId(), request.identity().requestId(), request.identity().admissionId(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 2e5d350338..6be3066e64 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -142,7 +142,7 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { if (history != 1) throw unavailable(); int changed = dsl.execute( - "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, capacity_rearm_fence = ?, reservation_fence = ?, mutation_digest = ?, canonical_payload = ?, evaluation_identity = ?, expires_at = ?, reconcile_deadline = ?, next_reconcile_at = NULL, recovery_attempt_count = 0, execution_status = 'OWNER_EXECUTION_PENDING', owner_readback = NULL, owner_readback_digest = NULL " + "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, capacity_rearm_fence = ?, reservation_fence = ?, mutation_digest = ?, canonical_payload = ?, evaluation_identity = ?, expires_at = ?::timestamptz, reconcile_deadline = ?::timestamptz, next_reconcile_at = NULL, recovery_attempt_count = 0, execution_status = 'OWNER_EXECUTION_PENDING', owner_readback = NULL, owner_readback_digest = NULL " + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND capacity_rearm_fence = ? AND mutation_digest = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", next.admissionAttemptId(), next.capacityRearmFence(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java index 8f9bfc0835..eae84aa246 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java @@ -184,7 +184,7 @@ public Result reconcile(Request request, NoCommitAction noCommitAction) { : observed == null ? "SOURCE_UNAVAILABLE" : observed.disposition().name(); int retained = dsl.execute( - "INSERT INTO account_tenant_capacity_recovery_evidence (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, recovery_policy_version, recovery_attempt_number, observed_at, outcome, canonical_readback, readback_digest) VALUES (?, ?, ?, ?, ?, 'capacity-recovery/1', ?, ?, ?, ?, ?)", + "INSERT INTO account_tenant_capacity_recovery_evidence (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, recovery_policy_version, recovery_attempt_number, observed_at, outcome, canonical_readback, readback_digest) VALUES (?, ?, ?, ?, ?, 'capacity-recovery/1', ?, ?::timestamptz, ?, ?, ?)", request.identity().tenantId(), request.identity().requestId(), request.identity().admissionId(), @@ -199,7 +199,7 @@ public Result reconcile(Request request, NoCommitAction noCommitAction) { if (indeterminate) { int updated = dsl.execute( - "UPDATE account_tenant_capacity_reservations SET recovery_attempt_count = ?, state = ?, recovery_escalated_at = ?, next_reconcile_at = ? WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", + "UPDATE account_tenant_capacity_reservations SET recovery_attempt_count = ?, state = ?, recovery_escalated_at = ?::timestamptz, next_reconcile_at = ?::timestamptz WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", attempt, quarantine ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() @@ -307,7 +307,7 @@ private Claim claim(Request request) { long fence = Math.incrementExact(number(row, "recovery_claim_fence")); int changed = dsl.execute( - "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = ?, recovery_claim_expires_at = ?, next_reconcile_at = LEAST(?, reconcile_deadline) " + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = ?, recovery_claim_expires_at = ?::timestamptz, next_reconcile_at = LEAST(?::timestamptz, reconcile_deadline) " + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_claim_fence = ?", workerId, fence, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index 9faf1e3893..fb699d93fc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -361,20 +361,23 @@ void receivingUpgradeFromParent1036PreservesCanonicalRowsAndHistory() { current.migrate(); current.validate(); assertThat(current.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1038")); + .isEqualTo(MigrationVersion.fromVersion("1040")); List> upgradedHistory = flywayHistory(setupDsl); - assertThat(upgradedHistory).hasSize(parentHistory.size() + 2); + assertThat(upgradedHistory).hasSize(parentHistory.size() + 3); assertThat(upgradedHistory.subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); List> addedHistory = upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); - assertThat(addedHistory).extracting(row -> row.get("version")).containsExactly("1037", "1038"); + assertThat(addedHistory) + .extracting(row -> row.get("version")) + .containsExactly("1037", "1038", "1040"); assertThat(addedHistory) .extracting(row -> row.get("script")) .containsExactly( "V1037__canonical_join_failure_and_attempt_diagnostics.sql", - "V1038__canonical_join_existing_membership_terminal.sql"); + "V1038__canonical_join_existing_membership_terminal.sql", + "V1040__account_tenant_capacity_owner.sql"); assertThat(addedHistory) .allSatisfy( row -> { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index f817135544..8d29b9c7da 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -622,7 +622,7 @@ private static CapacityPersistenceFixture capacityPersistenceFixture() { // Production // has no route to perform this insertion and World admission remains unavailable. c.dsl.execute( - "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", evidence.evaluationIdentity(), evidence.snapshotIdentity(), tenant, diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py index d3c77a6a61..52e6bcf179 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -2,10 +2,10 @@ import base64 import hashlib import json -from pathlib import Path import re import unicodedata import unittest +from pathlib import Path MAX = 9223372036854775807 diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 41d828031e..e10500d552 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -1,17 +1,21 @@ package net.firedevops.firemud.test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.List; import java.util.Set; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; @@ -39,6 +43,9 @@ class AccountRuntimeStubServerCompatibilityTest { "RequestEmailVerification", "VerifyEmail", "VerifyEmailLoginOtp"); + // Private runtime mutations require their actual bounded mTLS owner, never fake authority. + private static final Set UNIMPLEMENTED_RUNTIME_METHODS = + Set.of("CommitTenantCapacityAdmission"); @Test void accountServiceMethodSetIsFullyCategorized() { @@ -49,15 +56,40 @@ void accountServiceMethodSetIsFullyCategorized() { assertThat(actualMethods) .containsExactlyInAnyOrderElementsOf( - java.util.stream.Stream.concat( + java.util.stream.Stream.of( AccountRuntimeStubServer.implementedRuntimeMethodNames().stream(), - NON_RUNTIME_METHODS.stream()) + NON_RUNTIME_METHODS.stream(), + UNIMPLEMENTED_RUNTIME_METHODS.stream()) + .flatMap(java.util.function.Function.identity()) .collect(java.util.stream.Collectors.toSet())); assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) .contains("IssueDirectTextConnectScope", "JoinPublicProductionMembership"); } + @Test + void privateCapacityMutationRemainsUnimplementedOnSharedFakeRuntimeServer() throws Exception { + assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) + .doesNotContain("CommitTenantCapacityAdmission"); + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + assertThatThrownBy( + () -> + stub.commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest.getDefaultInstance())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNIMPLEMENTED)); + } finally { + channel.shutdownNow(); + } + } + } + @Test void joinMembershipVersionsRemainUnsignedOnTheirExistingFieldNumbers() { Descriptor descriptor = From 11a2998f4e7c89086fd4a77ef65562cf823c151d Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 20:00:48 +1300 Subject: [PATCH 03/52] Complete protected target resolution in capacity composition fixture --- ...alAdmissionCompositionIntegrationTest.java | 42 ++++++++++++++++++- ...alNewFinalAdmissionCompositionFixture.java | 38 ++++++++++++++++- 2 files changed, 77 insertions(+), 3 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 7256df3888..dbbee5739e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -33,6 +33,7 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; import net.firedevops.firemud.common.security.AccountPublicJwksCache; @@ -200,6 +201,42 @@ void retainedActualCasEvidenceStillFinalizesCapacityAfterControlledServingRetire } } + @Test + void targetResolutionRefusesChangedRetainedSelectorsWithoutMutatingOwners() throws Exception { + try (Session session = session()) { + var before = session.durableImage(); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest( + session.targetSelector); + for (var changed : + java.util.List.of( + request.toBuilder().setReadRequestUuid(0, UUID.randomUUID().toString()).build(), + request.toBuilder().setAccountUuid(0, UUID.randomUUID().toString()).build(), + request.toBuilder().setTenantSlug(0, "other-tenant").build(), + request.toBuilder() + .setPointerVersion( + 0, + Long.toString(Math.incrementExact(session.targetSelector.pointerVersion()))) + .build())) { + var selector = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest(changed); + assertThatThrownBy(() -> session.reverse.resolvePublishedRealmAdmissionTarget(selector)) + .isInstanceOfSatisfying( + io.grpc.StatusRuntimeException.class, + denied -> + assertThat(denied.getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + } + var wrongNamespace = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + request.toBuilder().setTargetNamespace(0, "other").build()); + assertThatThrownBy(() -> session.reverse.resolvePublishedRealmAdmissionTarget(wrongNamespace)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured namespace"); + assertThat(session.durableImage()).isEqualTo(before); + } + } + @Test void missingCapacityInputRefusesBeforeAnyFinalSessionOrReservationMutation() throws Exception { try (Session session = session()) { @@ -330,6 +367,7 @@ private final class Session implements AutoCloseable { private AccountPublicJwksCache jwks; private String jwt; private AccountGameplayAdmissionLeaseEvidence lease; + private CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector targetSelector; private Session() throws Exception { try { @@ -437,7 +475,7 @@ private Session() throws Exception { // Actual retained PLAYER_ADMISSION evaluation, with the same original request and exact // GS target. Published/World captures remain the fixture's explicit controlled sources. var scope = account.capacityScope(gs.target()); - var selector = + targetSelector = new net.firedevops.firemud.common.gamesession .CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector( requestId, @@ -459,7 +497,7 @@ private Session() throws Exception { .evaluate( new net.firedevops.firemud.accountservice.service .AccountPlayerAdmissionEntitlementOwner.Request( - selector, scope.connectScopeId(), GS), + targetSelector, scope.connectScopeId(), GS), jwt); var binding = gs.candidate(); capacityRequest = 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 9127d49bfa..49d397f58b 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 @@ -286,6 +286,42 @@ public void getCanonicalGameplayAdmissionDecision( actualDecisionReceiver.getCanonicalGameplayAdmissionDecision(request, observer); } + @Override + public void resolvePublishedRealmAdmissionTarget( + net.firedevops.firemud.gamesession.v1.ResolvePublishedRealmAdmissionTargetRequest + request, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.gamesession.v1 + .ResolvePublishedRealmAdmissionTargetResponse> + observer) { + decisionGuard.requireAccountCaller(); + final CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector parsed; + try { + parsed = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + request); + } catch (IllegalArgumentException malformed) { + observer.onError(io.grpc.Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!requestId.equals(parsed.readRequestId()) + || !candidate().accountId().equals(parsed.accountId())) { + observer.onError(io.grpc.Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + try { + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + parsed, target()); + } catch (IllegalArgumentException changedTarget) { + observer.onError(io.grpc.Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + observer.onNext( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + parsed, target())); + observer.onCompleted(); + } + @Override public void getPublishedRealmAdmissionOwnerRead( net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest @@ -311,7 +347,7 @@ public void getPublishedRealmAdmissionOwnerRead( observer.onCompleted(); } }; - // Both handlers authenticate first. The upstream publication and World lifecycle captures + // Every handler authenticates first. The upstream publication and World lifecycle captures // remain explicitly controlled; the actual retained-decision receiver is unchanged. factory.addService( ServerInterceptors.interceptForward( From 10da26e0d5b5488af4d5f466839f80c3e4afdcfd Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 10 Nov 2026 14:39:03 +1300 Subject: [PATCH 04/52] Include V1039 in canonical join migration history proof --- .../AccountCanonicalJoinScopePersistenceIntegrationTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index 01b3c24c8d..9ca9d6efb5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -364,19 +364,20 @@ void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() .isEqualTo(MigrationVersion.fromVersion("1040")); List> upgradedHistory = flywayHistory(setupDsl); - assertThat(upgradedHistory).hasSize(parentHistory.size() + 3); + assertThat(upgradedHistory).hasSize(parentHistory.size() + 4); assertThat(upgradedHistory.subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); List> addedHistory = upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); assertThat(addedHistory) .extracting(row -> row.get("version")) - .containsExactly("1037", "1038", "1040"); + .containsExactly("1037", "1038", "1039", "1040"); assertThat(addedHistory) .extracting(row -> row.get("script")) .containsExactly( "V1037__canonical_join_failure_and_attempt_diagnostics.sql", "V1038__canonical_join_existing_membership_terminal.sql", + "V1039__hosting_unclaimed_wallet_settlement.sql", "V1040__account_tenant_capacity_owner.sql"); assertThat(addedHistory) .allSatisfy( From c4c8dea108e00a9b9e979393055f4843ea96fb84 Mon Sep 17 00:00:00 2001 From: benhook1013 Date: Tue, 10 Nov 2026 16:49:13 +1300 Subject: [PATCH 05/52] Supply canonical scope readers to capacity admission composition fixture --- ...meplayAdmissionCurrentSourcesPostgresIntegrationTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index 33fa7b7bee..c8540dcce0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -2052,6 +2052,7 @@ static final class Fixture { private final AccountTenantEntitlementOutboxRepository tenantEntitlementOutbox; private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; private final AccountDemoTenantEntitlementRepository demoEntitlements; + private final AccountConnectScopeRepository connectScopes; private final AccountJoinOperationRepository joinOperations; private final AccountCanonicalFirstJoinTerminalCoordinator joinTerminal; private final AccountGameplayAdmissionLeaseRepository leases; @@ -2110,7 +2111,7 @@ private Fixture( var retainedAssociations = mock(ApprovedLegacyTenantAssociationRepository.class); var retainedResolver = new AccountTenantIdentityResolver(retainedAssociations, TEST_NAMESPACE); - var connectScopes = new AccountConnectScopeRepository(dsl, retainedResolver, freshTenants); + this.connectScopes = new AccountConnectScopeRepository(dsl, retainedResolver, freshTenants); this.joinOperations = new AccountJoinOperationRepository(dsl, connectScopes); var membershipEvents = new AccountMembershipAuthorityEventProducer( @@ -2320,7 +2321,7 @@ net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner capacit accounts, snapshots, issuance, - new AccountConnectScopeRepository(dsl), + connectScopes, manager, Clock.systemUTC(), TEST_NAMESPACE); From 9313355040426d547f5bc0d58f20f335d4be5a57 Mon Sep 17 00:00:00 2001 From: benhook1013 Date: Tue, 10 Nov 2026 16:56:02 +1300 Subject: [PATCH 06/52] Preserve frozen issuer cohort when new capacity receipt is absent --- .../repository/CanonicalGameplayIssuerCohortSql.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java index e28a42f021..46916de314 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java @@ -34,6 +34,10 @@ final class CanonicalGameplayIssuerCohortSql { + " THEN ARRAY['original_new_abandonment_id', 'original_new_abandonment_state'," + " 'original_new_abandonment_closure_digest', 'original_new_abandonment_orphan_cleanup_id'," + " 'original_new_abandonment_resolution_id']" + + " ELSE ARRAY[]::text[] END" + // V1063 leaves old cohorts unchanged until an actual capacity receipt exists. + + " - CASE WHEN to_jsonb(t)->'original_new_capacity_execution_digest' = 'null'::jsonb" + + " THEN ARRAY['original_new_capacity_execution_digest']" + " ELSE ARRAY[]::text[] END)::text AS source_row_json" + " FROM game_session_canonical_binding_transition t WHERE t.inventory_revision <= ?" + " UNION ALL SELECT CASE WHEN r.issuer_id = ? THEN 'RESERVATION'" From e0616e5c1bc8fc7872002c923f82fd5c54c001d0 Mon Sep 17 00:00:00 2001 From: benhook1013 Date: Tue, 10 Nov 2026 17:05:24 +1300 Subject: [PATCH 07/52] Restore final Human completion lower bound with forward catalog epoch --- .../game-session-service/runtime-and-data.md | 2 +- ...ore_final_human_completion_lower_bound.sql | 94 ++++++++++++++ ...rtitionBuildRepositoryIntegrationTest.java | 14 ++ ...eFamilyCatalogPostgresIntegrationTest.java | 121 ++++++++++++++++-- 4 files changed, 217 insertions(+), 14 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1064__restore_final_human_completion_lower_bound.sql diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 61875d5229..97fc12ed60 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -88,7 +88,7 @@ Game Session's runtime-family catalog is a manually composed **LOCAL SQL** sourc The catalog seals the actual current Game Session PostgreSQL schema, not a historical union of `CREATE TABLE` statements, a prefix exclusion or a static expected-table response. Every installed table, including empty tables, requires an explicit family disposition; named mixed components additionally bind their actual columns. Sorted definition digests cover tables, columns, constraints, indexes, triggers, routines, sequences, views, types, policies and rules, alongside the actual configured Flyway history. View and materialized-view facts bind both the query definition and relation options, including security-invoker, security-barrier and materialized-view storage settings; changing options invalidates the current seal even when the query text is unchanged. Unknown or removed relations/components refuse capture; changed schema definitions, routines, classification or prior/later migration facts invalidate the sealed epoch and previously retained reads. A new epoch requires an explicit monotonic owner installation against the complete current classified schema, not automatic resampling during a read. -Flyway writes each installing migration's own history row only after its migration transaction. The seal therefore binds distinct stable V1057, V1058, V1059, V1060, V1061, V1062 and V1063 installation markers and the actual installed definitions; it excludes only those seven installing history rows without inventing or claiming their eventual checksums. After installation, capture/readback additionally require exactly one successful SQL row for each version with its exact installing script in the configured history table. All other prior and later history facts remain part of the seal. Each forward installer seals the next monotonic owner epoch only after all routine replacements: V1058 binds view options, V1059 narrows the initial-preparation public-target conflict while preserving retained private projections, V1060 installs classified private catalog revision history/current-head control relations, and V1061 adds immutable private FRESH runtime identity provenance and seals epoch `5`; V1062 adds pending source protection and its writer guards before sealing epoch `6`; V1063 adds exact original-NEW capacity execution and its final-receipt binding before sealing epoch `7`. Earlier migrations and all retained epoch, snapshot and history bytes remain immutable. Requests retained under an older epoch conflict with the current epoch rather than being rewritten or resampled. Other installation and retention obligations remain with the [database migration owner](../../system-architecture-database-migrations.md); the configured history table, rather than an assumed `flyway_schema_history` alias, is itself explicitly classified as retained control evidence. +Flyway writes each installing migration's own history row only after its migration transaction. The seal therefore binds distinct stable V1057, V1058, V1059, V1060, V1061, V1062, V1063 and V1064 installation markers and the actual installed definitions; it excludes only those eight installing history rows without inventing or claiming their eventual checksums. After installation, capture/readback additionally require exactly one successful SQL row for each version with its exact installing script in the configured history table. All other prior and later history facts remain part of the seal. Each forward installer seals the next monotonic owner epoch only after all routine replacements: V1058 binds view options, V1059 narrows the initial-preparation public-target conflict while preserving retained private projections, V1060 installs classified private catalog revision history/current-head control relations, and V1061 adds immutable private FRESH runtime identity provenance and seals epoch `5`; V1062 adds pending source protection and its writer guards before sealing epoch `6`; V1063 adds exact original-NEW capacity execution and its final-receipt binding before sealing epoch `7`; V1064 restores the final Human runtime completion row-version lower bound while preserving the full current RUNNING launch, candidate, capacity and identity guard, then seals epoch `8`. Earlier migrations and all retained epoch, snapshot and history bytes remain immutable. Requests retained under an older epoch conflict with the current epoch rather than being rewritten or resampled. Other installation and retention obligations remain with the [database migration owner](../../system-architecture-database-migrations.md); the configured history table, rather than an assumed `flyway_schema_history` alias, is itself explicitly classified as retained control evidence. Gameplay commands and remote work whose namespace partition or replacement class is unresolved remain `UNKNOWN` and blocking, never implicitly S3. Durable tick/effect recovery, selected-work manifests, remote outcomes, script-pin authority/history and region/timeline provenance remain separate blocking evidence rather than cloned gameplay payload or a FRESH manifest. Input history and reconnect context retain their distinct audit/privacy consequences. `game_manifest` remains unsupported unqualified legacy lineage, not a build or FRESH source. Catalog/pointer, original operator/LOGIN/roster/binding/account/issuer authority, installed Saga control, and their original request, nonce, fence, replay, retirement and hold guards retain their owning consequences. Classification grants neither cleanup authority nor permission to discard uncertain work. The private preparation, original allocation and lifecycle-bound catalog revision branch are included as retained control/provenance; `PREPARING` is not a private runtime, CLOSED pointer or readiness result. diff --git a/services/game-session-service/src/main/resources/db/migration/V1064__restore_final_human_completion_lower_bound.sql b/services/game-session-service/src/main/resources/db/migration/V1064__restore_final_human_completion_lower_bound.sql new file mode 100644 index 0000000000..6a0c834319 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1064__restore_final_human_completion_lower_bound.sql @@ -0,0 +1,94 @@ +-- Restore the immutable Human completion row version as a lower bound while preserving +-- the complete current RUNNING launch, candidate, capacity, and identity guards. +-- [jooq ignore start] +DO $migration$ +DECLARE + definition text; + original text := 'completion.completed_running_row_version = runtime.row_version'; + replacement text := 'completion.completed_running_row_version <= runtime.row_version'; +BEGIN + SELECT pg_get_functiondef( + (quote_ident(current_schema()) || + '.require_running_runtime_for_lease_bound_binding_decision()')::regprocedure) + INTO STRICT definition; + IF (length(definition) - length(replace(definition, original, ''))) / length(original) <> 1 THEN + RAISE EXCEPTION 'Expected exact final Human runtime completion comparison'; + END IF; + EXECUTE replace(definition, original, replacement); +END; +$migration$; + +CREATE OR REPLACE FUNCTION gs_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE SET search_path = "${serviceSchema}", pg_catalog AS $$ + SELECT ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1057__game_session_owner_runtime_family_catalog.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1057' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1058__game_session_catalog_view_options.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1058' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1059__private_lifecycle_preparation_after_catalog_allocation.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1059' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1060__private_catalog_lifecycle_revisions.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1060' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1061__private_fresh_runtime_identity_allocation.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1061' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1062__private_preparation_source_protection.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1062' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1063__original_new_tenant_capacity_execution.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1063' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1064__restore_final_human_completion_lower_bound.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1064' + ); +$$; + +DO $migration$ +DECLARE + definition text; + original text; + replacement text; +BEGIN + SELECT pg_get_functiondef( + (quote_ident(current_schema()) || + '.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) + INTO STRICT definition; + + original := $needle$AND version IS DISTINCT FROM '1063'$needle$; + replacement := original || E'\n AND version IS DISTINCT FROM ''1064'''; + IF (length(definition) - length(replace(definition, original, ''))) / length(original) <> 1 THEN + RAISE EXCEPTION 'Expected exact Game Session catalog history exclusion'; + END IF; + definition := replace(definition, original, replacement); + + original := $needle$SELECT 'MIGRATION','catalog-installation:1063','V1063__original_new_tenant_capacity_execution.sql'$needle$; + replacement := original || E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1064'',''V1064__restore_final_human_completion_lower_bound.sql'''; + IF (length(definition) - length(replace(definition, original, ''))) / length(original) <> 1 THEN + RAISE EXCEPTION 'Expected exact Game Session catalog installation marker'; + END IF; + definition := replace(definition, original, replacement); + EXECUTE definition; +END; +$migration$; + +-- Seal the next monotonic owner epoch after every function definition is installed. +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes + FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS epoch + FROM game_session_runtime_family_catalog_epoch) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java index fecf487e28..5a8ee84c4d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java @@ -2439,6 +2439,13 @@ private static List rowImages(DSLContext dsl, String tableName) { + " 'original_new_abandonment_closure_digest'," + " 'original_new_abandonment_orphan_cleanup_id', 'original_new_abandonment_resolution_id']" + " ELSE ARRAY[]::text[] END"; + // V1063 null receipt pointer is absent-equivalent; keep any populated execution digest. + image = + "(" + + image + + ") - CASE WHEN to_jsonb(retained_row)->'original_new_capacity_execution_digest'" + + " = 'null'::jsonb THEN ARRAY['original_new_capacity_execution_digest']" + + " ELSE ARRAY[]::text[] END"; } else if (tableName.equals("game_session_canonical_binding_issuer_index_obligation")) { // V1036's null release link is absent-equivalent; an actual release UUID stays significant. image = @@ -2491,6 +2498,13 @@ private static List rowImagesWithXmin(DSLContext dsl, String tableName) + " 'original_new_abandonment_closure_digest'," + " 'original_new_abandonment_orphan_cleanup_id', 'original_new_abandonment_resolution_id']" + " ELSE ARRAY[]::text[] END"; + // V1063 null receipt pointer is absent-equivalent; keep any populated execution digest. + image = + "(" + + image + + ") - CASE WHEN to_jsonb(retained_row)->'original_new_capacity_execution_digest'" + + " = 'null'::jsonb THEN ARRAY['original_new_capacity_execution_digest']" + + " ELSE ARRAY[]::text[] END"; } else if (tableName.equals("game_session_canonical_binding_issuer_index_obligation")) { // V1036's null release link is absent-equivalent; an actual release UUID stays significant. image = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 716a61c935..91849a0afc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(7); + assertThat(catalog.catalogEpoch()).isEqualTo(8); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -186,7 +186,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1060", "catalog-installation:1061", "catalog-installation:1062", - "catalog-installation:1063") + "catalog-installation:1063", + "catalog-installation:1064") .noneMatch( identity -> identity.contains(":1057:") @@ -195,7 +196,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1060:") || identity.contains(":1061:") || identity.contains(":1062:") - || identity.contains(":1063:")); + || identity.contains(":1063:") + || identity.contains(":1064:")); assertThat( f.dsl .fetchSingle( @@ -738,7 +740,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(7); + assertThat(original.catalog().catalogEpoch()).isEqualTo(8); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -872,7 +874,7 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } - for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063")) { + for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -895,11 +897,11 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "INSERT INTO " + f.history + "(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" - + " VALUES(10000,'1064','controlled later migration','SQL','V1064__probe.sql',1,current_user,0,true)"); + + " VALUES(10000,'1065','controlled later migration','SQL','V1065__probe.sql',1,current_user,0,true)"); assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } - for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063")) { + for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -920,12 +922,12 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip try (Fixture f = fixture(null)) { var original = f.owner().capture(request()); f.addComponent(); - for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 9}) { + for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 8, 10}) { assertThatThrownBy(() -> f.installEpoch(invalid)) .hasMessageContaining("exact classified installed schema"); } // Controlled explicit owner revision, not an exposed registry/runtime mutation API. - f.installEpoch(8); + f.installEpoch(9); assertThatThrownBy(() -> f.owner().capture(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().readExact(original.request())) @@ -933,9 +935,9 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip assertThat(f.evidence(original.request())) .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().capture(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(8); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(9); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count(EPOCHS)).isEqualTo(8); + assertThat(f.count(EPOCHS)).isEqualTo(9); } } @@ -972,9 +974,9 @@ void metadataEpochAndSnapshotGuardsRefuseMutationStaleBytesAndChangedExactSqlFra "INSERT INTO " + EPOCHS + "(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 8,catalog_bytes,catalog_digest FROM " + + " SELECT 9,catalog_bytes,catalog_digest FROM " + EPOCHS - + " WHERE catalog_epoch=7")) + + " WHERE catalog_epoch=8")) .hasMessageContaining("exact classified installed schema"); assertThatThrownBy( () -> @@ -1373,6 +1375,99 @@ void genuineV1061ToV1062UpgradeRetainsCensusRowsEpochsAndSnapshotsBeforeSealingE } } + @Test + void genuineV1063ToV1064CompletionRepairRetainsEpochSevenAndSnapshotsBeforeSealingEpochEight() { + try (Fixture f = fixture("1063")) { + var original = f.owner().capture(request()); + assertThat(original.catalog().catalogEpoch()).isEqualTo(7); + Map before = f.rows(f.tables()); + before.remove(f.history); + before.remove(EPOCHS); + before.remove(SNAPSHOTS); + var classifications = f.classificationRows(); + var epochs = + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e ORDER BY catalog_epoch") + .getValues(0, String.class); + var snapshots = + f.dsl + .fetch( + "SELECT to_jsonb(s)::text||':'||xmin::text FROM " + + SNAPSHOTS + + " s ORDER BY read_request_id") + .getValues(0, String.class); + var history = f.historyRows(false); + var routines = f.routines(); + routines.remove("gs_runtime_family_catalog_installed()"); + routines.remove("gs_runtime_family_catalog_bytes(p_epoch bigint)"); + routines.remove("require_running_runtime_for_lease_bound_binding_decision()"); + + migration(f.source, f.schema, f.history, "1064").migrate(); + + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat(f.classificationRows()).isEqualTo(classifications); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e WHERE catalog_epoch<=7 ORDER BY catalog_epoch") + .getValues(0, String.class)) + .isEqualTo(epochs); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(s)::text||':'||xmin::text FROM " + + SNAPSHOTS + + " s ORDER BY read_request_id") + .getValues(0, String.class)) + .isEqualTo(snapshots); + assertThat(f.historyRows(false)).hasSize(history.size() + 1); + assertThat(f.historyRows(false).subList(0, history.size())).isEqualTo(history); + assertThat(f.routines()).containsAllEntriesOf(routines); + assertThat(f.count(EPOCHS)).isEqualTo(8); + assertThat(f.evidence(original.request())) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().capture(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + + var current = f.owner().capture(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(8); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes=gs_runtime_family_catalog_bytes(8) FROM " + + EPOCHS + + " WHERE catalog_epoch=8") + .get(0, Boolean.class)) + .isTrue(); + String decisionGuard = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef((quote_ident(?)||" + + "'.require_running_runtime_for_lease_bound_binding_decision()')::regprocedure)", + f.schema) + .get(0, String.class); + assertThat(decisionGuard) + .contains("completion.completed_running_row_version <= runtime.row_version") + .doesNotContain("completion.completed_running_row_version = runtime.row_version"); + var installed = + f.dsl.fetchSingle( + "SELECT type,script,success FROM " + f.history + " WHERE version='1064'"); + assertThat(installed.get("type", String.class)).isEqualTo("SQL"); + assertThat(installed.get("script", String.class)) + .isEqualTo("V1064__restore_final_human_completion_lower_bound.sql"); + assertThat(installed.get("success", Boolean.class)).isTrue(); + migration(f.source, f.schema, f.history, "1064").validate(); + } + } + private static Request request() { return new Request(UUID.randomUUID(), "test"); } From 5672083370914f83e84c8afe963738f086ee9f11 Mon Sep 17 00:00:00 2001 From: benhook1013 Date: Tue, 10 Nov 2026 17:15:55 +1300 Subject: [PATCH 08/52] Align current catalog retention assertion with forward epoch --- .../GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 91849a0afc..d7402a5dc3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -783,7 +783,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow assertThat(f.evidence(original.request())) .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); assertThat(f.count(SNAPSHOTS)).isEqualTo(1); - assertThat(f.count(EPOCHS)).isEqualTo(7); + assertThat(f.count(EPOCHS)).isEqualTo(8); } } } From 967f547218ad8d4fdc347339cd74d3985b759eed Mon Sep 17 00:00:00 2001 From: benhook1013 Date: Tue, 10 Nov 2026 17:34:51 +1300 Subject: [PATCH 09/52] Record controlled receiving proof and remaining capacity qualification --- .../implementation-tracking/player-access-and-session.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 156bc591fc..693643b372 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -40,7 +40,9 @@ Earlier attempts remain failed: R1 stopped on integration-fixture AssertJ infere 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 and is the sole negative source for Account's authorized transition. The guarded bounded Account-only read and exact Account recovery client are prepared without runtime registration. V1063 classifies the added evidence and advances the genuine catalog frontier while retaining old epochs. -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. Physical PostgreSQL/Redis additions and affected positive composition fixtures remain **unrun**; no physical, deployed-custody or runtime qualification is claimed. +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. From 5164f737adef81e6073a88dfabff8fa0d8b331a9 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 10 Nov 2026 19:52:10 +1300 Subject: [PATCH 10/52] Tighten capacity buffer cleanup and retained migration proof --- .../account-service/runtime-and-data.md | 2 +- .../system-architecture-versioning-runtime.md | 2 +- ...meplayOriginalNewAuthenticatedSession.java | 7 +++++- ...eFamilyCatalogPostgresIntegrationTest.java | 24 +++++++++++++++---- 4 files changed, 28 insertions(+), 7 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 421e570cf0..b18dd64c36 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -70,7 +70,7 @@ The current public registration path creates only a global Account row and a pla Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` and its Account/client persistence and reservation components are locally prepared but remain manually composed and unregistered; cross-implementation vector consumption, remaining physical PostgreSQL qualification, deployed custody, and selected-owner/final activation proof remain open. The [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the capability and proof status. The current `application.yml` and `application-prod.yml` retain `GetTenantMembershipForRuntime`, `GetRealmAccessGrantForRuntime`, `GetTenantEntitlementsForRuntime`, and `ListPresenceVisibilityPolicies` in the gRPC bearer-validation bypass list. Their handlers independently require certificate-derived workload identity in the exact configured namespace: Game Session for membership and realm-grant reads, Game Session or World Management for entitlement reads, and Social & Groups for presence-policy reads. Handler and configured-interceptor tests cover permitted peers without bearer credentials and refusal of unauthorized or wrong-namespace peers. This workload-only bypass does not make the methods unauthenticated public APIs. Complete typed caller-context and tenant-binding qualification, membership/currentness consumption, and the remaining canonical admission and registry contracts remain separate gaps under the [Account API contract](./api-contracts.md); these workload checks alone do not establish readiness. diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index a2ae27827c..95f565ad03 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -486,7 +486,7 @@ For the capacity action-family schema, `capacityDelta` is a declared member of t The absent encoding exists only to produce a deterministic rejected digest vector; an absent request can never commit. -The capacity vector fixture is normative proof work for Account, Game Session, and World Management. It fixes every non-`capacityDelta` field in the published `capacity-admission/v1` schema, including the complete capacity shape used for non-expanding comparison, and publishes canonical preimage bytes plus the expected lowercase SHA-256 digest for `absent`, `present(0)`, a representative valid positive value such as `17`, and the boundary `present(9223372036854775807)`. It also publishes request candidates for `9223372036854775808`, signed negatives, malformed decimal spellings, signed-`int64`/JSON overflow, changed capacity-shape fields, and checked usage/quota addition overflow, with the expected rejection before commitment and no accepted mutation digest. Every implementation in Account and both callers must consume the same vectors and produce the same accepted/rejected result; until that schema/vector corpus and focused proof exist, capacity admission remains unsupported target state. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the focused proof and record fixture execution results in PR/CI or implementation-tracking evidence; it supplements these owner-local requirements and does not create an execution ledger. +The capacity vector fixture is normative proof work for Account, Game Session, and World Management. It fixes every non-`capacityDelta` field in the published `capacity-admission/v1` schema, including the complete capacity shape used for non-expanding comparison, and publishes canonical preimage bytes plus the expected lowercase SHA-256 digest for `absent`, `present(0)`, a representative valid positive value such as `17`, and the boundary `present(9223372036854775807)`. It also publishes request candidates for `9223372036854775808`, signed negatives, malformed decimal spellings, signed-`int64`/JSON overflow, changed capacity-shape fields, and checked usage/quota addition overflow, with the expected rejection before commitment and no accepted mutation digest. Every implementation in Account and both callers must consume the same vectors and produce the same accepted/rejected result. The [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records the existing shared schema/vector fixtures and scoped proof; complete cross-language consumption, physical owner proof and runtime qualification remain required before capacity admission is enabled. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the focused proof and record fixture execution results in PR/CI or implementation-tracking evidence; it supplements these owner-local requirements and does not create an execution ledger. The changed-capacity-shape candidates in this fixture represent expanding or unvalidated changes and therefore must reject before commitment. A changed shape with Account-authenticated proof of a non-expanding effective resource delta is covered by the eligible replacement rule and is not an unconditional rejection case. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java index d1b3d4b83f..f7adbb9f82 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java @@ -444,7 +444,12 @@ Template bindCapacityExecution( String prior = requiredText(root, "capacityExecutionDigest"); if (!"UNBOUND".equals(prior) && !execution.digest().equals(prior)) throw invalid(); root.put("capacityExecutionDigest", execution.digest()); - return new Template(canonicalNode(root), clock, canonicalSessionDurationMillis); + byte[] bound = canonicalNode(root); + try { + return new Template(bound, clock, canonicalSessionDurationMillis); + } finally { + wipe(bound); + } } catch (IOException | RuntimeException malformed) { throw invalid(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index d7402a5dc3..540bd9181e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -1378,6 +1378,9 @@ void genuineV1061ToV1062UpgradeRetainsCensusRowsEpochsAndSnapshotsBeforeSealingE @Test void genuineV1063ToV1064CompletionRepairRetainsEpochSevenAndSnapshotsBeforeSealingEpochEight() { try (Fixture f = fixture("1063")) { + f.populatePredecessor(); + assertThat(f.count("game_instances")).isGreaterThan(0L); + assertThat(f.count("gameplay_command")).isGreaterThan(0L); var original = f.owner().capture(request()); assertThat(original.catalog().catalogEpoch()).isEqualTo(7); Map before = f.rows(f.tables()); @@ -1400,6 +1403,20 @@ void genuineV1063ToV1064CompletionRepairRetainsEpochSevenAndSnapshotsBeforeSeali + " s ORDER BY read_request_id") .getValues(0, String.class); var history = f.historyRows(false); + String decisionGuardBefore = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef((quote_ident(?)||" + + "'.require_running_runtime_for_lease_bound_binding_decision()')::regprocedure)", + f.schema) + .get(0, String.class); + String oldComparison = "completion.completed_running_row_version = runtime.row_version"; + String newComparison = "completion.completed_running_row_version <= runtime.row_version"; + assertThat( + (decisionGuardBefore.length() + - decisionGuardBefore.replace(oldComparison, "").length()) + / oldComparison.length()) + .isEqualTo(1); var routines = f.routines(); routines.remove("gs_runtime_family_catalog_installed()"); routines.remove("gs_runtime_family_catalog_bytes(p_epoch bigint)"); @@ -1447,16 +1464,15 @@ void genuineV1063ToV1064CompletionRepairRetainsEpochSevenAndSnapshotsBeforeSeali + " WHERE catalog_epoch=8") .get(0, Boolean.class)) .isTrue(); - String decisionGuard = + String decisionGuardAfter = f.dsl .fetchSingle( "SELECT pg_get_functiondef((quote_ident(?)||" + "'.require_running_runtime_for_lease_bound_binding_decision()')::regprocedure)", f.schema) .get(0, String.class); - assertThat(decisionGuard) - .contains("completion.completed_running_row_version <= runtime.row_version") - .doesNotContain("completion.completed_running_row_version = runtime.row_version"); + assertThat(decisionGuardAfter) + .isEqualTo(decisionGuardBefore.replace(oldComparison, newComparison)); var installed = f.dsl.fetchSingle( "SELECT type,script,success FROM " + f.history + " WHERE version='1064'"); From 6eb1013179eb3217c4247bf6b7a24dd91cfa2db8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 00:11:40 +1300 Subject: [PATCH 11/52] Bound capacity INSTALL and CLOSE by the existing Redis operation budget --- .../game-session-service/runtime-and-data.md | 2 +- ...layOriginalNewCapacityExecutionBudget.java | 16 +- ...playOriginalNewCapacityExecutionOwner.java | 15 +- ...ayOriginalNewFinalAdmissionRedisOwner.java | 126 ++++++-- ...e-session-original-new-final-admission.lua | 8 + ...-session-original-new-final-admission.json | 2 +- ...alNewFinalAdmissionLuaIntegrationTest.java | 35 ++- ...NewFinalAdmissionOwnerIntegrationTest.java | 62 ++++ ...riginalNewCapacityExecutionBudgetTest.java | 74 +++++ ...nalNewCapacityExecutionConnectionTest.java | 18 ++ ...lNewCapacityExecutionRedisCommandTest.java | 279 ++++++++++++++++++ 11 files changed, 601 insertions(+), 36 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionRedisCommandTest.java diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 97fc12ed60..8b21d111a2 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -8,7 +8,7 @@ The seven-key tenant-slot final script atomically serializes `FINAL` against per Positive SQL terminal retention follows actual persistent session/index/atomic-outcome and final-receipt verification. That retained result survives later serving-index retirement. Retained negative replay requires the already-verified immutable SQL CLOSED proof, full original identity, exact persistent Redis CLOSED tombstone, absence of contradictory final SQL receipt/state and a fresh actual current-owner observation. Serving-index absence is never negative evidence. Missing tombstones and closure before SQL proof retention remain indeterminate. Retention-before-cleanup ordering across the earlier crash window is not yet enforced. The existing never-admitted cleanup owner accepts only untouched PREPARED dispatches; cleanup of this already-acknowledged PROVISIONAL final-admission boundary and finalized-usage retirement on real runtime teardown remain separate unfinished Account/owner work. No default owner, receiver, recovery scheduler or source custody is registered by this slice. -The capacity execution owner uses one absolute budget for each complete operation: the earlier incoming gRPC or explicit coordinator deadline, capped at five seconds. Its local SQL connection provider and transaction provider derive from the existing configuration without changing shared datasource settings. Four resource operations are admitted without a waiting queue. Acquisition, SQL and cleanup stay in the admitted worker; cancellation requests the active JDBC statement's cancellation, while a late acquisition cannot execute SQL. Statement close and pool return detach the statement under the same monitor as cancellation. A blocked driver cancellation or acquisition retains its admission slot until it exits. A throwing pool return preserves uncertain connection ownership and retains the slot rather than blindly retrying or claiming disposal. JDBC query timeouts back up cancellation; neither cancellation nor deadline return proves driver termination or an owner outcome. The separate four-slot Redis connector and all successive Redis reads consume the same remaining operation budget, rather than renewing five seconds per command. +The capacity execution owner uses one absolute budget for each complete operation: the earlier incoming gRPC or explicit coordinator deadline, capped at five seconds. Its local SQL connection provider and transaction provider derive from the existing configuration without changing shared datasource settings. Four resource operations are admitted without a waiting queue. Acquisition, SQL and cleanup stay in the admitted worker; cancellation requests the active JDBC statement's cancellation, while a late acquisition cannot execute SQL. Statement close and pool return detach the statement under the same monitor as cancellation. A blocked driver cancellation or acquisition retains its admission slot until it exits. A throwing pool return preserves uncertain connection ownership and retains the slot rather than blindly retrying or claiming disposal. JDBC query timeouts back up cancellation; neither cancellation nor deadline return proves driver termination or an owner outcome. The separate four-slot Redis connector, scoped capacity INSTALL/CLOSE writes and all successive Redis commands consume the same remaining operation budget. INSTALL and the first CLOSE mutation carry that operation's frozen absolute deadline, enforced by Redis time; completed CLOSE replay remains read-only. Other final-admission callers retain their existing connection and command policy. ## Runtime Model 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 2cdbf59c2f..30ba2a2ecd 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 @@ -38,6 +38,7 @@ final class CanonicalGameplayOriginalNewCapacityExecutionBudget { private final Clock clock; private final long explicitDeadline; private final Deadline deadline; + private final long absoluteDeadlineMillis; private final AtomicBoolean cancelled = new AtomicBoolean(); private final CompletableFuture result = new CompletableFuture<>(); private final Object resources = new Object(); @@ -57,19 +58,27 @@ private CanonicalGameplayOriginalNewCapacityExecutionBudget( this.explicitDeadline = explicitDeadline; this.cancellationThreads = Objects.requireNonNull(cancellationThreads); caller = Context.current(); + long startedMillis = clock.millis(); long nanos = TimeUnit.SECONDS.toNanos(5); if (caller.getDeadline() != null) nanos = Math.min(nanos, caller.getDeadline().timeRemaining(TimeUnit.NANOSECONDS)); if (explicitDeadline != Long.MAX_VALUE) { long remaining; try { - remaining = Math.subtractExact(explicitDeadline, clock.millis()); + remaining = Math.subtractExact(explicitDeadline, startedMillis); } catch (ArithmeticException invalid) { throw unavailable(); } nanos = Math.min(nanos, TimeUnit.MILLISECONDS.toNanos(Math.min(5000, remaining))); } if (nanos <= 0 || caller.isCancelled()) throw unavailable(); + try { + absoluteDeadlineMillis = + Math.min( + explicitDeadline, Math.addExact(startedMillis, TimeUnit.NANOSECONDS.toMillis(nanos))); + } catch (ArithmeticException invalid) { + throw unavailable(); + } Deadline local = Deadline.after(nanos, TimeUnit.NANOSECONDS); deadline = caller.getDeadline() == null ? local : local.minimum(caller.getDeadline()); } @@ -173,6 +182,11 @@ long remainingMillis() { return Math.max(1, TimeUnit.NANOSECONDS.toMillis(remainingNanos())); } + long absoluteDeadlineMillis() { + check(); + return absoluteDeadlineMillis; + } + void check() { remainingNanos(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 29f0f37293..38a9fc00d4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -198,7 +198,13 @@ void authorize( long result = scopedFinalOwner() .dispatchCapacityAction( - source, template, accountOpen, issuerOpen, execution, "INSTALL", deadline); + source, + template, + accountOpen, + issuerOpen, + execution, + "INSTALL", + budget.absoluteDeadlineMillis()); if (result != 3) throw unavailable(); } Map physical = readExecution(execution, assignment.tenantGameplayTag()); @@ -259,7 +265,10 @@ public void closeOriginalAttempt(Request request, Result reservation) { var assignment = scopedTags().assignmentForTransition(execution.transitionId()); if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class))) throw unavailable(); - long result = scopedFinalOwner().closeCapacityExecutionOnce(execution, candidate, assignment); + long result = + scopedFinalOwner() + .closeCapacityExecutionOnce( + execution, candidate, assignment, budget.absoluteDeadlineMillis()); if (result != 4) throw unavailable(); Map physical = readExecution(execution, assignment.tenantGameplayTag()); exactPhysicalBinding(physical, execution, "CLOSED"); @@ -675,7 +684,7 @@ private CanonicalGameplayTenantGameplayTagRepository scopedTags() { private CanonicalGameplayOriginalNewFinalAdmissionRedisOwner scopedFinalOwner() { return new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( - redis, scripts, clock, scopedTags()); + redis, scripts, clock, scopedTags(), this::connectForRead, budget::remainingMillis); } private T within( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index 7f566778a3..c91abe99b1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -123,12 +123,30 @@ final class CanonicalGameplayOriginalNewFinalAdmissionRedisOwner { private final RedisScriptCatalog catalog; private final Clock clock; private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + private final java.util.function.Supplier> + scopedConnection; + private final java.util.function.LongSupplier remainingCommandMillis; CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( io.lettuce.core.RedisClient redisClient, RedisScriptCatalog catalog, Clock clock, CanonicalGameplayTenantGameplayTagRepository tenantTags) { + this(redisClient, catalog, clock, tenantTags, null, null); + } + + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + io.lettuce.core.RedisClient redisClient, + RedisScriptCatalog catalog, + Clock clock, + CanonicalGameplayTenantGameplayTagRepository tenantTags, + java.util.function.Supplier> scopedConnection, + java.util.function.LongSupplier remainingCommandMillis) { + if ((scopedConnection == null) != (remainingCommandMillis == null)) + throw new IllegalArgumentException( + "Scoped connection and command budget must be supplied together"); + this.scopedConnection = scopedConnection; + this.remainingCommandMillis = remainingCommandMillis; this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); this.clock = Objects.requireNonNull(clock, "Clock is required"); @@ -291,6 +309,15 @@ long closeCapacityExecutionOnce( OriginalNewCapacityExecution execution, CanonicalGameplayOriginalNewCandidate candidate, CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { + return closeCapacityExecutionOnce( + execution, candidate, assignment, Math.addExact(clock.millis(), COMMAND_TIMEOUT_MILLIS)); + } + + long closeCapacityExecutionOnce( + OriginalNewCapacityExecution execution, + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + long absoluteDeadlineMillis) { requireNoAmbientTransaction(); requireAssignment(assignment, candidate); String accountKey = @@ -315,7 +342,7 @@ long closeCapacityExecutionOnce( 1, ascii("{}"), ascii("{}"), - Math.addExact(clock.millis(), 5000), + absoluteDeadlineMillis, ascii("closure"), execution, "CLOSE"); @@ -664,40 +691,81 @@ private long execute( OriginalNewCapacityExecution execution, String action) { requireNoAmbientTransaction(); - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { + StatefulRedisConnection connection = null; + try { + commandWaitMillis(); + connection = + scopedConnection == null + ? redisClient.connect(ByteArrayCodec.INSTANCE) + : scopedConnection.get(); RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - String sha = await(commands.scriptLoad(script)); + requirePrincipal(awaitCommand(commands::aclWhoami)); + String sha = awaitCommand(() -> commands.scriptLoad(script)); if (!digest("SHA-1", script).equals(sha)) throw unavailable(); Long result = - await( - commands.evalsha( - sha, - ScriptOutputType.INTEGER, - keyBytes(keys), - ascii(assignment.tenantId().toString()), - ascii(assignment.accountId().toString()), - ascii(assignment.playableStateNamespaceId().toString()), - ascii(candidate.bindingIdentity().characterId().toString()), - ascii(assignment.gameInstanceId().toString()), - ascii(assignment.sessionId()), - ascii(candidate.transition().bindingGeneration().toString()), - ascii(assignment.tenantGameplayTag()), - candidateBytes, - characterBytes, - templateBytes, - ascii(Long.toString(durationMillis)), - accountJson, - issuerJson, - ascii(Long.toString(absoluteDeadlineMillis)), - issuerPayload, - execution.canonicalBytes(), - ascii(action), - ascii(execution.digest()))); + awaitCommand( + () -> + commands.evalsha( + sha, + ScriptOutputType.INTEGER, + keyBytes(keys), + ascii(assignment.tenantId().toString()), + ascii(assignment.accountId().toString()), + ascii(assignment.playableStateNamespaceId().toString()), + ascii(candidate.bindingIdentity().characterId().toString()), + ascii(assignment.gameInstanceId().toString()), + ascii(assignment.sessionId()), + ascii(candidate.transition().bindingGeneration().toString()), + ascii(assignment.tenantGameplayTag()), + candidateBytes, + characterBytes, + templateBytes, + ascii(Long.toString(durationMillis)), + accountJson, + issuerJson, + ascii(Long.toString(absoluteDeadlineMillis)), + issuerPayload, + execution.canonicalBytes(), + ascii(action), + ascii(execution.digest()))); return result; } catch (RuntimeException failure) { throw unavailable(); + } finally { + if (connection != null) { + try { + if (scopedConnection == null) connection.close(); + else connection.closeAsync(); + } catch (RuntimeException cleanupFailure) { + throw unavailable(); + } + } + } + } + + private long commandWaitMillis() { + long remaining = + remainingCommandMillis == null + ? COMMAND_TIMEOUT_MILLIS + : remainingCommandMillis.getAsLong(); + if (remaining <= 0) throw unavailable(); + return Math.min(COMMAND_TIMEOUT_MILLIS, remaining); + } + + private T awaitCommand(java.util.function.Supplier> command) { + long beforeSubmission = commandWaitMillis(); + RedisFuture future = command.get(); + if (future == null) throw unavailable(); + try { + T result = future.get(Math.min(beforeSubmission, commandWaitMillis()), TimeUnit.MILLISECONDS); + commandWaitMillis(); + return result; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw unavailable(); + } catch (ExecutionException | TimeoutException failure) { + // A submitted write is indeterminate. Neither a timeout nor cleanup permits a retry. + throw unavailable(); } } diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua index 1b5ce416dc..da519f3890 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua @@ -114,6 +114,14 @@ if action == 'CLOSE' then or redis.call('SISMEMBER', KEYS[3], sessionId) ~= 1 or redis.call('TYPE', KEYS[4]).ok ~= 'set' or redis.call('PTTL', KEYS[4]) ~= -1 or redis.call('SISMEMBER', KEYS[4], sessionId) ~= 1 then return -1 end + -- Completed replay above is read-only; a first CLOSE mutation must meet this operation's deadline. + local closeTime = redis.call('TIME') + local closeSeconds, closeMicros = tonumber(closeTime[1]), tonumber(closeTime[2]) + if not closeSeconds or not closeMicros or closeSeconds < 1 or closeSeconds ~= math.floor(closeSeconds) + or closeSeconds > math.floor((9007199254740991 - 999) / 1000) + or closeMicros < 0 or closeMicros >= 1000000 or closeMicros ~= math.floor(closeMicros) then return -1 end + local closeNow = closeSeconds * 1000 + math.floor(closeMicros / 1000) + if closeNow <= 0 or closeNow >= deadline then return -1 end redis.call('HSET', KEYS[7], 'state', 'CLOSED') return 4 end diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json index f9a4feb398..25ec2651bd 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.original-new-final-admission.v1", "resourcePath": "redis/lua/game-session-original-new-final-admission.lua", - "sha256": "aa505e5b29cb7ab98c324b65c5cee57a6af0058d6d07ab1da874ed4fc4ef04dc", + "sha256": "224ffb4457c1c6113b1c76b0b9ac1e42c5016b3d51a9c1b1ac51688d2731acbc", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java index 711de9e186..7016ecf7e6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java @@ -377,7 +377,9 @@ void lostFinalReplyReplaysTheActualSessionHashAndControllerTimesWithoutNegativeC byte[] expiresAt = admin.hget(ascii(original.keys()[6]), ascii("continuityExpiresAt")); assertThat(admin.hget(ascii(original.keys()[6]), ascii("sessionSha1"))) .containsExactly(ascii(HexFormatHolder.sha1(actual))); - assertThat(eval(action(original, "CLOSE"))).isEqualTo(2L); + byte[][] expiredClose = action(original, "CLOSE").arguments().clone(); + expiredClose[14] = ascii(Long.toString(System.currentTimeMillis() - 1L)); + assertThat(eval(new ScriptCase(original.keys(), expiredClose))).isEqualTo(2L); assertThat(eval(original)).isEqualTo(2L); assertThat(admin.get(ascii(original.keys()[0]))).containsExactly(actual); assertThat(admin.hget(ascii(original.keys()[6]), ascii("admissionAt"))) @@ -386,6 +388,37 @@ void lostFinalReplyReplaysTheActualSessionHashAndControllerTimesWithoutNegativeC .containsExactly(expiresAt); } + @Test + void expiredCloseCannotMutateButFreshClosureAndExpiredReplayRemainAvailable() throws Exception { + ScriptCase original = seed(); + Map execution = new LinkedHashMap<>(); + admin + .hgetall(ascii(original.keys()[6])) + .forEach((field, value) -> execution.put(new String(field, StandardCharsets.UTF_8), value)); + byte[][] expired = action(original, "CLOSE").arguments().clone(); + expired[14] = ascii(Long.toString(System.currentTimeMillis() - 1L)); + var late = new ScriptCase(original.keys(), expired); + assertThat(eval(late)).isEqualTo(-1L); + assertHash(original.keys()[6], execution); + assertHash(original.keys()[4], accountPhysicalFields()); + assertHash(original.keys()[5], issuerPhysicalFields()); + assertThat(admin.get(ascii(original.keys()[0]))).containsExactly(original.arguments()[8]); + assertThat(admin.get(ascii(original.keys()[1]))).containsExactly(original.arguments()[9]); + assertThat(admin.scard(ascii(original.keys()[2]))).isEqualTo(1L); + assertThat(admin.scard(ascii(original.keys()[3]))).isEqualTo(1L); + assertThat(admin.sismember(ascii(original.keys()[2]), ascii(SESSION))).isTrue(); + assertThat(admin.sismember(ascii(original.keys()[3]), ascii(SESSION))).isTrue(); + for (String key : original.keys()) assertThat(admin.pttl(ascii(key))).isEqualTo(-1L); + byte[][] fresh = action(original, "CLOSE").arguments().clone(); + fresh[14] = ascii(Long.toString(System.currentTimeMillis() + 5000L)); + assertThat(eval(new ScriptCase(original.keys(), fresh))).isEqualTo(4L); + execution.put("state", ascii("CLOSED")); + assertHash(original.keys()[6], execution); + assertThat(eval(late)).isEqualTo(4L); + assertHash(original.keys()[6], execution); + assertThat(admin.get(ascii(original.keys()[0]))).containsExactly(original.arguments()[8]); + } + @Test void permanentClosureSurvivesLostReplyAndPreventsEveryDelayedSameAttemptFinal() throws Exception { ScriptCase original = seed(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index fd9fa29d73..86b2520caf 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -3,6 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.lettuce.core.AclSetuserArgs; @@ -207,6 +209,61 @@ void missingExecutionCannotBeReinstalledFromTheRetainedSqlDispatchOrUsedAsNoComm assertThat(sqlImage()).isEqualTo(rows); } + @Test + void failedInstallConnectRetainsDispatchAndNeverPermitsReinstallationOrNegativeProof() + throws Exception { + repairAccountMember(); + bridge(false); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + RedisClient failedClient = mock(RedisClient.class); + when(failedClient.connect(ByteArrayCodec.INSTANCE)) + .thenThrow(new IllegalStateException("Controlled connection failure")); + var failedOwner = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + fixture.dsl(), failedClient, catalog, CLOCK, tags); + var assignment = tags.assignmentForTransition(fixture.transitionId()); + String key = + "session:game:capacity-execution:{" + + assignment.tenantGameplayTag() + + "}:" + + controlledCapacity.request().admissionAttemptId(); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var raw = credential.template(); + var template = raw.bindCapacityExecution(controlledCapacity)) { + var account = controlledAccountOpen(); + var issuer = issuerOpen(); + assertThatThrownBy( + () -> + failedOwner.authorize( + source, template, account, issuer, controlledCapacity, deadline())) + .isInstanceOf(IllegalStateException.class); + verify(failedClient, times(1)).connect(ByteArrayCodec.INSTANCE); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("INSTALL_DISPATCHED"); + String retained = sqlImage(); + assertThatThrownBy( + () -> + capacityOwner() + .authorize(source, template, account, issuer, controlledCapacity, deadline())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .closeOriginalAttempt( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThat(admin.type(ascii(key))).isEqualTo("none"); + assertThat(sqlImage()).isEqualTo(retained); + } + } + @Test void recreatedCapacityOwnerClosesExactAttemptAndRejectsDelayedFinalCas() throws Exception { repairAccountMember(); @@ -1288,6 +1345,10 @@ private void repairAccountMember() { } private void bridge() { + bridge(true); + } + + private void bridge(boolean authorizeCapacity) { var region = CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( fixture.dsl(), @@ -1322,6 +1383,7 @@ private void bridge() { controlled.candidateDigest(), selectedOwner, controlled.selectedOwnerFence()); + if (!authorizeCapacity) return; try (var credential = new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); var raw = credential.template(); 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 ded28a31f2..648b279407 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 @@ -25,6 +25,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; @@ -367,6 +368,79 @@ void exceptionalCallbackDrainsAnAcquiredConnectionBeforeReleasingItsResourcePerm assertNoOwnedConnections(captured.get()); } + @Test + void absoluteDeadlineStaysFrozenAcrossSqlWorkAndWallClockPassage() throws Exception { + Clock clock = mock(); + AtomicLong now = new AtomicLong(1_800_000_000_000L); + when(clock.millis()).thenAnswer(ignored -> now.get()); + long originalDeadline = now.get() + 4000; + ConnectionProvider provider = mock(); + PreparedStatement statement = mock(); + when(provider.acquire()).thenReturn(preparedConnection(statement)); + when(statement.execute()) + .thenAnswer( + ignored -> { + now.addAndGet(1000); + return true; + }); + DSLContext dsl = source(provider); + + long retainedDeadline = + CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + clock, + originalDeadline, + budget -> { + assertThat(budget.absoluteDeadlineMillis()).isEqualTo(originalDeadline); + execute(budget.sql(dsl)); + assertThat(budget.remainingMillis()).isBetween(1L, 4000L); + return budget.absoluteDeadlineMillis(); + }); + + assertThat(retainedDeadline).isEqualTo(originalDeadline); + assertThat(now).hasValue(originalDeadline - 3000); + verify(statement).execute(); + } + + @Test + void defaultFiveSecondAbsoluteDeadlineDoesNotRenewAfterClockPassage() { + Clock clock = mock(); + AtomicLong now = new AtomicLong(1_800_000_000_000L); + when(clock.millis()).thenAnswer(ignored -> now.get()); + long initial = now.get(); + + long retainedDeadline = + CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + clock, + Long.MAX_VALUE, + budget -> { + long deadline = budget.absoluteDeadlineMillis(); + now.addAndGet(1000); + assertThat(budget.absoluteDeadlineMillis()).isEqualTo(deadline); + return deadline; + }); + + assertThat(retainedDeadline).isBetween(initial + 1, initial + 5000); + } + + @Test + void incomingGrpcDeadlineCapsTheFrozenAbsoluteDeadline() throws Exception { + Clock clock = + Clock.fixed(java.time.Instant.ofEpochMilli(1_800_000_000_000L), java.time.ZoneOffset.UTC); + var scheduler = Executors.newSingleThreadScheduledExecutor(); + try { + long retainedDeadline = + Context.current() + .withDeadlineAfter(2, TimeUnit.SECONDS, scheduler) + .call( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + clock, clock.millis() + 4000, budget -> budget.absoluteDeadlineMillis())); + assertThat(retainedDeadline).isBetween(clock.millis() + 1, clock.millis() + 2000); + } finally { + scheduler.shutdownNow(); + } + } + private static void assertNoOwnedConnections( CanonicalGameplayOriginalNewCapacityExecutionBudget budget) { Object monitor = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java index d1f646d3fe..6f3fe40f04 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java @@ -148,6 +148,24 @@ void standalonePackagePathEntersTheActualBudgetScopeWithoutSqlOrTagAuthority() { verifyNoInteractions(dsl, tags); } + @Test + void failedConnectionAttemptDoesNotRetainAConnectorSlot() { + RedisClient redis = mock(); + StatefulRedisConnection connection = mock(); + when(redis.connect(ByteArrayCodec.INSTANCE)) + .thenThrow(new IllegalStateException("Controlled connect failure")) + .thenReturn(connection); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.closeAsync()).thenReturn(CompletableFuture.completedFuture(null)); + var owner = owner(mock(), redis, mock()); + + assertThatThrownBy(owner::connectForRead).isInstanceOf(IllegalStateException.class); + assertThat(owner.connectForRead()).isSameAs(connection); + connection.closeAsync(); + verify(redis, org.mockito.Mockito.times(2)).connect(ByteArrayCodec.INSTANCE); + } + private static CanonicalGameplayOriginalNewCapacityExecutionOwner owner( DSLContext dsl, RedisClient redis, CanonicalGameplayTenantGameplayTagRepository tags) { return new CanonicalGameplayOriginalNewCapacityExecutionOwner( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionRedisCommandTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionRedisCommandTest.java new file mode 100644 index 0000000000..b24e71c9cf --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionRedisCommandTest.java @@ -0,0 +1,279 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.LongSupplier; +import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution; +import org.junit.jupiter.api.Test; + +/** Controlled command transport only; mock carriers do not qualify admission or source custody. */ +class CanonicalGameplayOriginalNewCapacityExecutionRedisCommandTest { + @Test + void scopedCloseUsesSuppliedConnectionAndShrinkingCommandWaits() throws Exception { + var fixture = new Fixture(); + AtomicLong remaining = new AtomicLong(500); + fixture.completeWhoami(() -> remaining.set(300)); + fixture.completeScriptLoad(() -> remaining.set(100)); + fixture.completeEvaluation(); + + assertThat( + fixture + .scoped(remaining::get) + .closeCapacityExecutionOnce( + fixture.execution, fixture.candidate, fixture.assignment, fixture.deadline)) + .isEqualTo(4); + + verify(fixture.whoami).get(500, TimeUnit.MILLISECONDS); + verify(fixture.scriptLoad).get(300, TimeUnit.MILLISECONDS); + verify(fixture.evaluation).get(100, TimeUnit.MILLISECONDS); + verifyNoInteractions(fixture.redis); + verify(fixture.connection).closeAsync(); + verify(fixture.connection, never()).close(); + } + + @Test + void expiryAfterPrincipalCheckPreventsScriptSubmission() throws Exception { + var fixture = new Fixture(); + AtomicLong remaining = new AtomicLong(500); + fixture.completeWhoami(() -> remaining.set(0)); + + assertThatThrownBy( + () -> + fixture + .scoped(checked(remaining)) + .closeCapacityExecutionOnce( + fixture.execution, fixture.candidate, fixture.assignment, fixture.deadline)) + .isInstanceOf(IllegalStateException.class); + + verifyNoInteractions(fixture.scriptLoad, fixture.evaluation); + assertThat(fixture.scriptSubmissions).hasValue(0); + assertThat(fixture.evaluationSubmissions).hasValue(0); + verify(fixture.connection).closeAsync(); + verifyNoInteractions(fixture.redis); + } + + @Test + void expiryAfterScriptLoadPreventsMutatingEvaluationSubmission() throws Exception { + var fixture = new Fixture(); + AtomicLong remaining = new AtomicLong(500); + fixture.completeWhoami(() -> {}); + fixture.completeScriptLoad(() -> remaining.set(0)); + + assertThatThrownBy( + () -> + fixture + .scoped(checked(remaining)) + .closeCapacityExecutionOnce( + fixture.execution, fixture.candidate, fixture.assignment, fixture.deadline)) + .isInstanceOf(IllegalStateException.class); + + assertThat(fixture.scriptSubmissions).hasValue(1); + assertThat(fixture.evaluationSubmissions).hasValue(0); + verifyNoInteractions(fixture.evaluation, fixture.redis); + verify(fixture.connection).closeAsync(); + } + + @Test + void timedOutEvaluationIsIndeterminateAndClosesAsynchronouslyWithoutResubmission() + throws Exception { + var fixture = new Fixture(); + fixture.completeWhoami(() -> {}); + fixture.completeScriptLoad(() -> {}); + when(fixture.evaluation.get(anyLong(), eq(TimeUnit.MILLISECONDS))) + .thenThrow(new TimeoutException("Controlled lost write reply")); + + assertThatThrownBy( + () -> + fixture + .scoped(() -> 100) + .closeCapacityExecutionOnce( + fixture.execution, fixture.candidate, fixture.assignment, fixture.deadline)) + .isInstanceOf(IllegalStateException.class); + + assertThat(fixture.evaluationSubmissions).hasValue(1); + verify(fixture.evaluation).get(100, TimeUnit.MILLISECONDS); + verify(fixture.connection).closeAsync(); + verify(fixture.connection, never()).close(); + verifyNoInteractions(fixture.redis); + } + + @Test + void unscopedCloseRetainsDirectConnectionFiveSecondWaitsAndSynchronousCleanup() throws Exception { + var fixture = new Fixture(); + fixture.completeWhoami(() -> {}); + fixture.completeScriptLoad(() -> {}); + fixture.completeEvaluation(); + when(fixture.redis.connect(ByteArrayCodec.INSTANCE)).thenReturn(fixture.connection); + + assertThat( + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + fixture.redis, fixture.catalog, Clock.systemUTC(), mock()) + .closeCapacityExecutionOnce( + fixture.execution, fixture.candidate, fixture.assignment)) + .isEqualTo(4); + + verify(fixture.redis).connect(ByteArrayCodec.INSTANCE); + verify(fixture.whoami).get(5000, TimeUnit.MILLISECONDS); + verify(fixture.scriptLoad).get(5000, TimeUnit.MILLISECONDS); + verify(fixture.evaluation).get(5000, TimeUnit.MILLISECONDS); + verify(fixture.connection).close(); + verify(fixture.connection, never()).closeAsync(); + } + + private static LongSupplier checked(AtomicLong remaining) { + return () -> { + long value = remaining.get(); + if (value <= 0) throw new IllegalStateException("Controlled expired operation"); + return value; + }; + } + + private static final class Fixture { + final RedisClient redis = mock(); + final StatefulRedisConnection connection = mock(); + final RedisFuture whoami = mock(); + final RedisFuture scriptLoad = mock(); + final RedisFuture evaluation = mock(); + final AtomicLong scriptSubmissions = new AtomicLong(); + final AtomicLong evaluationSubmissions = new AtomicLong(); + final CanonicalGameplayOriginalNewCandidate candidate = mock(); + final OriginalNewCapacityExecution execution = mock(); + final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = mock(); + final RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution())); + final long deadline = System.currentTimeMillis() + 5000; + String loadedSha; + + @SuppressWarnings("unchecked") + Fixture() { + UUID tenant = UUID.randomUUID(); + var binding = + new CanonicalGameplayBindingIdentity( + UUID.randomUUID(), + tenant, + UUID.randomUUID(), + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 1, + UUID.randomUUID().toString(), + UUID.randomUUID(), + BigInteger.ONE, + "firemud-account-service", + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + UUID transitionId = UUID.randomUUID(); + when(candidate.bindingIdentity()).thenReturn(binding); + when(candidate.transition()) + .thenReturn( + new CanonicalGameplayOriginalNewCandidate.TransitionSource( + transitionId, + binding.bindingRef(), + BigInteger.ONE, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID())); + when(candidate.canonicalBytes()) + .thenAnswer(ignored -> "controlled-candidate".getBytes(StandardCharsets.US_ASCII)); + when(assignment.isBindingTransition()).thenReturn(true); + when(assignment.transitionId()).thenReturn(transitionId); + when(assignment.tenantId()).thenReturn(tenant); + when(assignment.accountId()).thenReturn(binding.accountId()); + when(assignment.playableStateNamespaceId()).thenReturn(binding.playableStateNamespaceId()); + when(assignment.characterId()).thenReturn(binding.characterId()); + when(assignment.gameInstanceId()).thenReturn(binding.gameInstanceId()); + when(assignment.sessionId()).thenReturn(binding.sessionId()); + when(assignment.bindingRef()).thenReturn(binding.bindingRef()); + when(assignment.tenantGameplayTag()).thenReturn("g1-0123456789abcdef0123456789abcdef"); + TenantCapacityAdmission.Request request = mock(); + when(request.admissionAttemptId()).thenReturn(UUID.randomUUID()); + when(execution.request()).thenReturn(request); + when(execution.canonicalBytes()) + .thenAnswer(ignored -> "controlled-execution".getBytes(StandardCharsets.US_ASCII)); + when(execution.digest()).thenReturn("sha256:" + "a".repeat(64)); + RedisAsyncCommands commands = + mock( + RedisAsyncCommands.class, + invocation -> { + return switch (invocation.getMethod().getName()) { + case "aclWhoami" -> whoami; + case "scriptLoad" -> { + scriptSubmissions.incrementAndGet(); + loadedSha = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-1") + .digest(invocation.getArgument(0, byte[].class))); + yield scriptLoad; + } + case "evalsha" -> { + evaluationSubmissions.incrementAndGet(); + yield evaluation; + } + default -> org.mockito.Answers.RETURNS_DEFAULTS.answer(invocation); + }; + }); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + when(connection.closeAsync()).thenReturn(CompletableFuture.completedFuture(null)); + } + + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner scoped(LongSupplier remaining) { + return new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + redis, catalog, Clock.systemUTC(), mock(), () -> connection, remaining); + } + + void completeWhoami(Runnable completion) throws Exception { + when(whoami.get(anyLong(), eq(TimeUnit.MILLISECONDS))) + .thenAnswer( + ignored -> { + completion.run(); + return "gamesession_coord_app"; + }); + } + + void completeScriptLoad(Runnable completion) throws Exception { + when(scriptLoad.get(anyLong(), eq(TimeUnit.MILLISECONDS))) + .thenAnswer( + ignored -> { + completion.run(); + return loadedSha; + }); + } + + void completeEvaluation() throws Exception { + when(evaluation.get(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(4L); + } + } +} From 02f5acc151ff53fe2c66fd5139b12c9e36b99b68 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 02:14:02 +1300 Subject: [PATCH 12/52] Return fresh capacity policy denials after exact replay and source validation --- .../account-service/api-contracts.md | 2 +- .../account-service/runtime-and-data.md | 2 +- .../system-architecture-authz-route-matrix.md | 2 +- .../service/AccountTenantCapacityOwner.java | 4 +- ...alAdmissionCompositionIntegrationTest.java | 124 ++++++++++++++++++ .../AccountTenantCapacityOwnerTest.java | 65 ++++++++- .../capacity/TenantCapacityAdmission.java | 10 +- .../capacity/CapacityAdmissionDigestTest.java | 63 +++++++++ .../CapacityAdmissionTestFixture.java | 10 +- .../TenantCapacityAdmissionGrpcCodec.java | 4 +- .../TenantCapacityAdmissionGrpcCodecTest.java | 17 +++ .../client/AccountTenantCapacityClient.java | 2 +- .../AccountTenantCapacityClientMtlsTest.java | 51 +++++++ 13 files changed, 345 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f42214b7ab..787b4c64ba 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -227,7 +227,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh non-creating evidence receives the existing `TENANT_BILLING_BLOCKED`/`RESOURCE_EXHAUSTED` policy denial before usage writes; malformed identity, stale evidence, unavailable authority, conflicting retries, and unsupported shapes retain their fail-closed refusals. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index b18dd64c36..35967d3862 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -318,7 +318,7 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. +The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. `V1040` prepares immutable capacity-evaluation, attempt-history, and recovery-evidence records plus guarded reservations, but no capacity-family retention entry, horizon, or owner-safe cleanup/archive contract is defined under [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). This remains an open Account activation limitation; existing guards and holds remain in force. ### Playtest Grant Persistence and Authority Consequences diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 99fd5ccb04..be7c5a85d6 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -265,7 +265,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus validated typed player context; no circular end-user token prerequisite. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `GetTenantEntitlementsForRuntime` | `internal_workload` | Exactly one complete caller-policy alternative: Game Session mTLS plus current private delegation and typed player context for player admission, or World Management mTLS plus tenant/operation-bound instance-lifecycle context without a player delegation. Constraints within the selected alternative are conjunctive; no `control-ui` or Logging and Admin caller; not edge exposed. The read assesses eligibility only and never commits capacity. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `CommitTenantCapacityAdmission` | `internal_workload` | **Target; not currently routable.** Exactly one complete caller-policy alternative is required: Game Session presents its own exact Game Session caller workload mTLS identity to Account with typed `PlayerExecutionContext` and the live player-binding checks, or World Management presents its own exact World Management caller workload mTLS identity to Account with tenant/operation-bound instance-lifecycle context and the live lifecycle checks. Account remains the receiving authority; only those alternatives may call its exact receiving mTLS boundary. The request binds `tenantId`, stable `requestId`/`admissionId`, fresh `admissionAttemptId`, current `capacityRearmFence`, the complete Account evidence bundle including its applicable `authorityTuple`, `expected_billing_evidence`, and all `outboxCheckpoints[]`, plus a bounded `capacityDelta` whose protobuf field is `optional int64` encoded as a varint and whose canonical JSON/proto-JSON spelling is `capacityDelta` encoded as a base-10 decimal string. The machine contract explicitly distinguishes omitted (`absent`) from present zero (`present_zero`), rejects JSON `null` and boolean zero, and publishes both transport-specific golden vectors. The caller-supplied `capacity_rearm_fence` is the attempt-bound fence, while Account compares the live `capacity_admission_fence` at final commit alongside the applicable generation guards. It also carries versioned `mutationDigest` over the attempt identity, fence, and complete payload. The first attempt binds those fields without a rearm; an exact retry replays, while a changed field requires the Account-owned committed rearm CAS that advances the fence and binds the fresh attempt. Any change without that CAS is an idempotency conflict before reservation, usage, activation, or routing mutation. Account performs the final fenced reservation commit and returns the committed evidence or a canonical stale/quota/unavailable outcome; until this route is implemented, capacity-changing operations fail closed. | -| Game Session Service | `ReadOriginalNewCapacityExecution` | `internal_workload` | **Unregistered; not currently routable.** Exact same-namespace Account mTLS workload, with no user token or ambient delegated context. Bounded read-only original attempt and reservation selector. Returns complete exact binding and immutable proven final-session/SQL receipt evidence or an irreversibly closed original attempt, together with a fresh owner-fence observation distinct from the captured original fence. Missing, interrupted or contradictory evidence is unavailable, never no-commit. See [Game Session API Contracts](./microservices/game-session-service/api-contracts.md#original-new-capacity-execution-read). | +| Game Session Service | `ReadOriginalNewCapacityExecution` | `internal_workload` | **Unregistered; not currently routable.** Exact same-namespace Account mTLS workload, with no user token or ambient delegated context. Bounded read-only original attempt and reservation selector. Returns complete exact binding and immutable proven final-session/SQL receipt evidence or an irreversibly closed original attempt, together with a fresh owner-fence observation distinct from the captured original fence. Missing, interrupted, ambiguous, or contradictory execution evidence is `INDETERMINATE`; `UNAVAILABLE` means the read cannot produce an observation. Neither outcome proves non-execution. See [Game Session API Contracts](./microservices/game-session-service/api-contracts.md#original-new-capacity-execution-read). | | Account Service | `GetTenantEntitlementsTenant` | `billing_safe_tenant` | `tenantAdmin` (tenant-scoped); live `current_operator_roles` and caller-bound membership checks | | Account Service | `GetTenantEntitlementsCrossTenantSupportSafe` | `cross_tenant_support_safe` | `support` without `privileged_control`; `platformAdmin` requires `privileged_control` | | Account Service | `GetSubscriptionTenantHighLevel` | `billing_safe_tenant` | `tenantAdmin` (tenant-scoped); live `current_operator_roles` and caller-bound membership checks under [Subscription Management](./microservices/account-service/subscription-management.md) | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 6be3066e64..b2164e7299 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -3,6 +3,7 @@ import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.number; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.quota; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -81,7 +82,7 @@ public AccountTenantCapacityOwner( public Result commit(Request request, String authenticatedCaller) { requireCaller(request, authenticatedCaller); - request.requireCommittable(); + request.requireStructurallyValid(); return inTransaction( () -> { lockPlayerAccount(request); @@ -91,6 +92,7 @@ public Result commit(Request request, String authenticatedCaller) { if (request.capacityRearmFence() != 1) throw conflict(); current(request); requireSupportedShape(request); + if (!request.evidence().permitsCreation()) throw quota(); return capacity.create(request, request.evidence().expiresAt()); }); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index dbbee5739e..77a04d0b95 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -2,9 +2,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.protobuf.ByteString; import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.StatusProto; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -13,6 +17,10 @@ import java.time.Duration; import java.util.Arrays; import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.v1.AuthenticateRequest; @@ -32,6 +40,8 @@ import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -41,6 +51,7 @@ import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture; +import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -334,6 +345,46 @@ void missingActualInitialBarrierRefusesWithoutRecreatingOpenOrAdmittingCandidate } } + @Test + void freshRetainedNonCreatingEvaluationIsPolicyDeniedWithoutOwnerMutation() throws Exception { + try (Session session = session()) { + var denied = session.retainControlledNonCreatingEvaluation(); + assertThat(denied.evidence().permitsCreation()).isFalse(); + String before = session.capacityImage() + session.durableImage(); + for (int attempt = 0; attempt < 2; attempt++) { + StatusRuntimeException failure = + assertThrows(StatusRuntimeException.class, () -> session.capacityClient.commit(denied)); + assertCapacityFailure(failure, Status.Code.RESOURCE_EXHAUSTED, "TENANT_BILLING_BLOCKED"); + assertThat(session.capacityImage() + session.durableImage()).isEqualTo(before); + assertThat(session.gs.physicalSession()).isNull(); + } + } + } + + @Test + void retainedOriginalReplaysBeforeChangedNonCreatingEvidenceCanBecomeADenial() throws Exception { + try (Session session = session()) { + var first = session.capacityClient.commit(session.capacityRequest); + var changed = session.retainControlledNonCreatingEvaluation(); + String before = session.capacityImage() + session.durableImage(); + StatusRuntimeException failure = + assertThrows(StatusRuntimeException.class, () -> session.capacityClient.commit(changed)); + assertCapacityFailure(failure, Status.Code.ALREADY_EXISTS, "IDEMPOTENCY_CONFLICT"); + assertThat(session.capacityClient.commit(session.capacityRequest)).isEqualTo(first); + assertThat(session.capacityImage() + session.durableImage()).isEqualTo(before); + assertThat(session.gs.physicalSession()).isNull(); + } + } + + private static void assertCapacityFailure( + StatusRuntimeException failure, Status.Code expectedStatus, String expectedCode) + throws Exception { + assertThat(failure.getStatus().getCode()).isEqualTo(expectedStatus); + var status = Objects.requireNonNull(StatusProto.fromThrowable(failure)); + assertThat(status.getDetailsCount()).isOne(); + assertThat(status.getDetails(0).unpack(ErrorDetail.class).getCode()).isEqualTo(expectedCode); + } + private Session session() throws Exception { accountFixtures.temporaryDirectory = temporaryDirectory; return new Session(); @@ -632,6 +683,79 @@ private Genesis genesis() { .readByLease(UUID.fromString((String) lease.carrier().get("leaseId")))); } + /** Controlled entitlement facts, real current caller/scope and actual immutable retention. */ + @SuppressWarnings("unchecked") + private TenantCapacityAdmission.Request retainControlledNonCreatingEvaluation() { + var original = capacityRequest; + var parsed = + RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( + original.evidence().canonicalBytes()); + var fields = parsed.fields(); + Map facts = new LinkedHashMap<>(); + for (String name : + List.of( + "sourceKind", + "subscriptionStatus", + "provisioningStatus", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "entitlementVersion", + "tenantBillingSequence", + "tenantAuthorityGeneration")) { + facts.put(name, fields.get(name)); + } + facts.put("allowNewGameplayBindings", false); + var denied = + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + original.identity().requestId(), + original.evidence().callerWorkload(), + (String) fields.get("verifiedConnectScopeId"), + parsed.membershipSource(), + (Map) fields.get("target"), + facts, + (Map) fields.get("sourceReferences"), + CLOCK.instant()); + serializable.executeWithoutResult( + ignored -> new AccountTenantCapacityRepository(dsl).retainPlayerEvaluation(denied)); + return new TenantCapacityAdmission.Request( + original.identity(), + original.admissionAttemptId(), + original.capacityRearmFence(), + original.targetNamespace(), + original.context(), + original.operation(), + original.priorShape(), + original.requestedShape(), + TenantCapacityAdmission.Evidence.player(denied), + original.capacityDelta(), + null) + .withDigest(); + } + + private String capacityImage() { + StringBuilder image = new StringBuilder(); + for (String table : + List.of( + "account_tenant_capacity_evaluations", + "account_tenant_capacity_usage", + "account_tenant_capacity_reservations", + "account_tenant_capacity_attempt_history", + "account_tenant_capacity_recovery_evidence")) { + image + .append(table) + .append( + dsl.fetch( + "SELECT (to_jsonb(t) || jsonb_build_object('_original_xmin', t.xmin::text))::text AS image FROM " + + table + + " t ORDER BY 1") + .getValues("image", String.class)); + } + return image.toString(); + } + private String durableImage() { return gsReceiptImage() + dsl.fetch( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 3d2e8e3961..29b633a7ed 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -65,6 +65,7 @@ void changedAttemptOrPayloadOrFenceConflictsBeforeAnyCurrentSourceOrUsageMutatio var f = new Fixture(false); for (Request changed : java.util.List.of( + CapacityAdmissionTestFixture.playerRequest(false), new Request( f.request.identity(), UUID.randomUUID(), @@ -147,6 +148,63 @@ void wrongPeerOrAbsentDeltaNeverStartsAccountWork() throws Exception { verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); } + @Test + void unretainedNonCreatingEvidenceRemainsUnavailableWithoutAnyUsageWrite() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.playerRequest(false)); + f.existing = false; + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void staleNonCreatingEvidenceStaysInvalidInsteadOfBecomingPolicyDenial() throws Exception { + var f = new Fixture(true, CapacityAdmissionTestFixture.playerRequest(false)); + f.existing = false; + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void nonCreatingEvidenceCannotStartRecoveryOrRearmWork() throws Exception { + var f = new Fixture(false); + var source = + mock( + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .ExecutionReadClient.class); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, f.dsl, source, Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC)); + var denied = CapacityAdmissionTestFixture.playerRequest(false); + var next = + new Request( + denied.identity(), + UUID.randomUUID(), + 2, + denied.targetNamespace(), + denied.context(), + denied.operation(), + denied.priorShape(), + denied.requestedShape(), + denied.evidence(), + denied.capacityDelta(), + null) + .withDigest(); + assertThatThrownBy(() -> recovery.rearm(f.request, next)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + recovery.reconcile( + denied, + net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.NoCommitAction.RETAIN_FOR_REARM)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes, source); + } + private static final class Fixture { private final DSLContext dsl = mock(DSLContext.class); private final AccountRepository accounts = mock(AccountRepository.class); @@ -155,12 +213,17 @@ private static final class Fixture { private final AccountGameplayDelegationIssuanceRepository issuances = mock(AccountGameplayDelegationIssuanceRepository.class); private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); - private final Request request = CapacityAdmissionTestFixture.playerRequest(); + private final Request request; private final UUID reservation = UUID.randomUUID(); private final AccountTenantCapacityOwner owner; private boolean existing = true; private Fixture(boolean expired) throws Exception { + this(expired, CapacityAdmissionTestFixture.playerRequest()); + } + + private Fixture(boolean expired, Request request) throws Exception { + this.request = request; when(accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) .thenReturn(Optional.of(new Account())); Connection connection = mock(Connection.class); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java index bfc478c83f..5da6d9b77a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java @@ -292,7 +292,14 @@ public Request withDigest() { CapacityAdmissionDigest.digest(this)); } + /** Strong guard for rearm and selected-owner execution; content alone grants no authority. */ public void requireCommittable() { + requireStructurallyValid(); + if (operation == Operation.CAPACITY_CREATING && !evidence.permitsCreation()) throw invalid(); + } + + /** Account resolves exact replay/conflict and current policy after this content check. */ + public void requireStructurallyValid() { if (capacityDelta == null || mutationDigest == null || !mutationDigest.equals(CapacityAdmissionDigest.digest(this)) @@ -302,8 +309,7 @@ public void requireCommittable() { Math.subtractExact( requestedShape.units(context.owner()), priorShape.units(context.owner())); if (operation == Operation.CAPACITY_CREATING) { - if (capacityDelta <= 0 || net <= 0 || capacityDelta > net || !evidence.permitsCreation()) - throw invalid(); + if (capacityDelta <= 0 || net <= 0 || capacityDelta > net) throw invalid(); // A scalar commitment cannot hide expansion in another resource dimension. if (context.owner() == Owner.GAME_SESSION ? requestedShape.concurrentGameInstances() > priorShape.concurrentGameInstances() diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index d7cc00ea89..928f4e53f5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -72,6 +72,69 @@ void sharedCorpusFixesCompleteEvidenceAndAbsentZeroPositiveBoundaryPreimages() t .isNotEqualTo(CapacityAdmissionTestFixture.worldRequest(0L).mutationDigest()); } + @Test + void nonCreatingEvidenceIsValidContentButCannotAuthorizeExecution() { + Request denied = CapacityAdmissionTestFixture.playerRequest(false); + denied.requireStructurallyValid(); + assertThat(denied.evidence().permitsCreation()).isFalse(); + assertThat(CapacityAdmissionTestFixture.playerRequest().evidence().permitsCreation()).isTrue(); + assertThat(denied.mutationDigest()) + .isNotEqualTo(CapacityAdmissionTestFixture.playerRequest().mutationDigest()); + assertThatThrownBy(denied::requireCommittable).isInstanceOf(IllegalArgumentException.class); + var reservation = + new TenantCapacityAdmission.Result( + denied.identity(), + denied.admissionAttemptId(), + denied.capacityRearmFence(), + denied.mutationDigest(), + java.util.UUID.randomUUID(), + 1, + denied.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + denied.evidence().snapshotIdentity(), + denied.evidence().evaluationIdentity()); + assertThatThrownBy( + () -> + new OriginalNewCapacityExecution( + denied, + reservation, + denied.identity().admissionId(), + "sha256:" + "a".repeat(64), + "owner-1", + 1)) + .isInstanceOf(IllegalArgumentException.class); + + for (Request invalid : + List.of( + playerMutation(denied, null, denied.requestedShape(), null).withDigest(), + playerMutation(denied, 1L, denied.requestedShape(), null), + playerMutation(denied, 1L, denied.requestedShape(), "b".repeat(64)), + playerMutation(denied, 0L, denied.requestedShape(), null).withDigest(), + playerMutation(denied, 2L, denied.requestedShape(), null).withDigest(), + playerMutation(denied, 1L, denied.priorShape(), null).withDigest(), + playerMutation(denied, 1L, new Shape(1, 1, 0), null).withDigest(), + playerMutation(denied, 1L, new Shape(1, 0, 1), null).withDigest())) { + assertThatThrownBy(invalid::requireStructurallyValid) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(invalid::requireCommittable).isInstanceOf(IllegalArgumentException.class); + } + } + + private static Request playerMutation(Request base, Long delta, Shape requested, String digest) { + return new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + base.operation(), + base.priorShape(), + requested, + base.evidence(), + delta, + digest); + } + @Test void decimalWireGrammarRejectsNegativesOverflowAndMalformedSpellingsBeforeHash() { for (String value : diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java index 2f2fd5d42e..d64aed95f9 100644 --- a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java @@ -39,6 +39,14 @@ public static RuntimePlayerAdmissionEntitlementEvidence playerEvidence() { } public static TenantCapacityAdmission.Request playerRequest() { + return playerRequest(true); + } + + /** Controlled policy content, never proof of current Account entitlement custody. */ + public static TenantCapacityAdmission.Request playerRequest(boolean permitsCreation) { + Map policyFacts = facts(); + policyFacts.put("allowNewGameplayBindings", permitsCreation); + var evidence = capture(target(), policyFacts, sources(), NOW); return new TenantCapacityAdmission.Request( new TenantCapacityAdmission.Identity(TENANT, REQUEST, ADMISSION), ATTEMPT, @@ -49,7 +57,7 @@ public static TenantCapacityAdmission.Request playerRequest() { TenantCapacityAdmission.Operation.CAPACITY_CREATING, new TenantCapacityAdmission.Shape(0, 0, 0), new TenantCapacityAdmission.Shape(1, 0, 0), - TenantCapacityAdmission.Evidence.player(playerEvidence()), + TenantCapacityAdmission.Evidence.player(evidence), 1L, null) .withDigest(); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index 53232eeda6..8cee9f1a85 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -32,7 +32,7 @@ public final class TenantCapacityAdmissionGrpcCodec { private TenantCapacityAdmissionGrpcCodec() {} public static CommitTenantCapacityAdmissionRequest toRequest(Request value) { - value.requireCommittable(); + value.requireStructurallyValid(); var attempt = TenantCapacityAdmissionAttempt.newBuilder() .addTenantId(value.identity().tenantId().toString()) @@ -85,7 +85,7 @@ else if (attempt.getWorldContextCount() == 1 && attempt.getPlayerContextCount() one(attempt.getCanonicalAccountEvidenceList()).toByteArray(), context.owner()), wire.getCapacityDelta(), one(attempt.getMutationDigestList())); - request.requireCommittable(); + request.requireStructurallyValid(); return request; } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index 59f209338b..5af0f67dcc 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -29,6 +29,23 @@ void exactBothAlternativesRoundTripWithCompleteBundleAndReservationBinding() { } } + @Test + void nonCreatingEvidenceRoundTripsWithoutChangingAnyCanonicalBytes() { + Request request = CapacityAdmissionTestFixture.playerRequest(false); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + var parsed = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + assertThat(wire.getAttempt(0).getCanonicalAccountEvidence(0).toByteArray()) + .containsExactly(request.evidence().canonicalBytes()); + assertThat(parsed).isEqualTo(request); + assertThat(parsed.evidence().canonicalBytes()) + .containsExactly(request.evidence().canonicalBytes()); + assertThat(parsed.evidence().permitsCreation()).isFalse(); + assertThat(TenantCapacityAdmissionGrpcCodec.toRequest(parsed).toByteArray()) + .containsExactly(wire.toByteArray()); + parsed.requireStructurallyValid(); + assertThatThrownBy(parsed::requireCommittable).isInstanceOf(IllegalArgumentException.class); + } + @Test void absentNegativeDuplicateUnknownAndMixedCallerContextFailBeforeCommit() { Request request = CapacityAdmissionTestFixture.playerRequest(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index 94e43379f5..0af7aa0f78 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -55,7 +55,7 @@ public void init() throws IOException { */ public Result commit(Request request) { requireNoAmbientSql("Capacity commitment requires no ambient SQL"); - request.requireCommittable(); + request.requireStructurallyValid(); if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION || !namespace.equals(request.targetNamespace())) throw new IllegalArgumentException("Exact Game Session context required"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index b2f458f359..db8e1682fb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -3,18 +3,22 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.Any; import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import java.net.InetSocketAddress; import java.nio.file.Path; import java.time.Clock; import java.time.ZoneOffset; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -28,6 +32,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -70,6 +75,35 @@ void exactAccountPeerReceivesCompleteRequestAndExactRetryKeepsReservation() thro } } + @Test + void nonCreatingEvidenceReachesControlledAccountAndReturnsStructuredPolicyDenial() + throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("account", calls, false); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(false); + assertThatThrownBy(() -> client.commit(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED); + var status = Objects.requireNonNull(StatusProto.fromThrowable(failure)); + assertThat(status.getDetailsList()) + .containsExactly( + Any.pack( + ErrorDetail.newBuilder() + .setCode("TENANT_BILLING_BLOCKED") + .setMessage("Tenant capacity commitment did not complete") + .build())); + }); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + @Test void wrongAccountPeerIsRejectedBeforeRequestBodyRelease() throws Exception { AtomicInteger calls = new AtomicInteger(); @@ -121,6 +155,23 @@ public void commitTenantCapacityAdmission( assertThat(GrpcPeerIdentity.current().uri()) .isEqualTo("spiffe://firemud/ns/prod/sa/game-session-service"); var request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + if (!request.evidence().permitsCreation()) { + assertThat(request).isEqualTo(CapacityAdmissionTestFixture.playerRequest(false)); + // Controlled transport response only; the real Account owner proves policy authority. + observer.onError( + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(Status.Code.RESOURCE_EXHAUSTED.value()) + .setMessage("Tenant capacity commitment did not complete") + .addDetails( + Any.pack( + ErrorDetail.newBuilder() + .setCode("TENANT_BILLING_BLOCKED") + .setMessage("Tenant capacity commitment did not complete") + .build())) + .build())); + return; + } var result = new TenantCapacityAdmission.Result( request.identity(), From c8dab91d050082d7c989900b4b2d44d7a812f275 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 02:30:50 +1300 Subject: [PATCH 13/52] Preserve provisional state in denial proof and record the held retention prerequisite --- .../player-access-and-session.md | 2 ++ ...alAdmissionCompositionIntegrationTest.java | 21 +++++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 6e3a6a7999..d58d6f1e2b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,6 +32,8 @@ The [shared capacity-admission/v1 schema](../../../services/common-platform-core [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 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. Focused local validation on base `2e23db82384efa3221a53633dd43b45c62cd6ecc` passes 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. Physical PostgreSQL migration, fresh-bootstrap, retention/rollback, reservation finalization/release and bounded recovery/quarantine definitions remain unrun; their controlled entitlement and execution readback do not qualify genuine World lifecycle or final admission CAS. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 77a04d0b95..d592335910 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -350,13 +350,15 @@ void freshRetainedNonCreatingEvaluationIsPolicyDeniedWithoutOwnerMutation() thro try (Session session = session()) { var denied = session.retainControlledNonCreatingEvaluation(); assertThat(denied.evidence().permitsCreation()).isFalse(); + byte[] candidate = session.gs.physicalSession(); + assertThat(candidate).isNotNull(); String before = session.capacityImage() + session.durableImage(); for (int attempt = 0; attempt < 2; attempt++) { StatusRuntimeException failure = assertThrows(StatusRuntimeException.class, () -> session.capacityClient.commit(denied)); assertCapacityFailure(failure, Status.Code.RESOURCE_EXHAUSTED, "TENANT_BILLING_BLOCKED"); assertThat(session.capacityImage() + session.durableImage()).isEqualTo(before); - assertThat(session.gs.physicalSession()).isNull(); + assertProvisionalUnchanged(session, candidate); } } } @@ -366,16 +368,31 @@ void retainedOriginalReplaysBeforeChangedNonCreatingEvidenceCanBecomeADenial() t try (Session session = session()) { var first = session.capacityClient.commit(session.capacityRequest); var changed = session.retainControlledNonCreatingEvaluation(); + byte[] candidate = session.gs.physicalSession(); + assertThat(candidate).isNotNull(); String before = session.capacityImage() + session.durableImage(); StatusRuntimeException failure = assertThrows(StatusRuntimeException.class, () -> session.capacityClient.commit(changed)); assertCapacityFailure(failure, Status.Code.ALREADY_EXISTS, "IDEMPOTENCY_CONFLICT"); assertThat(session.capacityClient.commit(session.capacityRequest)).isEqualTo(first); assertThat(session.capacityImage() + session.durableImage()).isEqualTo(before); - assertThat(session.gs.physicalSession()).isNull(); + assertProvisionalUnchanged(session, candidate); } } + private static void assertProvisionalUnchanged(Session session, byte[] candidate) { + assertThat(session.gs.physicalSession()).containsExactly(candidate); + assertThat( + session + .gs + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition WHERE transition_id = ?", + session.gs.decisionId()) + .get(0, String.class)) + .isEqualTo("PROVISIONAL"); + } + private static void assertCapacityFailure( StatusRuntimeException failure, Status.Code expectedStatus, String expectedCode) throws Exception { From 84a6915106ed210ff0046b79a1ab516512066a69 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 12:43:48 +1300 Subject: [PATCH 14/52] Prove default Account runtime entitlement refuses without capacity creation --- .../player-access-and-session.md | 2 + ...timeEntitlementNoWriteIntegrationTest.java | 332 ++++++++++++++++++ 2 files changed, 334 insertions(+) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index d58d6f1e2b..57e536bcf9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -52,6 +52,8 @@ Remaining qualification includes these exact-source checks, complete Account rea The prepared recovery policy `capacity-recovery/1` retains an immutable observation per current fenced claim, with twelve bounded read attempts and the original reconciliation deadline. Unavailable, invalid, late and ambiguous reads never release the hold. Exhaustion durably quarantines the original reservation, fence, exact payload and full held quota; replay performs no further source call. No operator release, automatic expiry, replacement reservation or unaudited quarantine-resolution API is supplied. The physical fixture includes controlled-source exhaustion/quarantine proof definitions; these remain unrun. Genuine audited Account remediation from independent owner evidence remains an activation prerequisite. +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 The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java new file mode 100644 index 0000000000..e56214c74e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java @@ -0,0 +1,332 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mockingDetails; + +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.stub.MetadataUtils; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker; +import net.firedevops.firemud.accountservice.service.impl.AccountGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.impl.AccountTenantCapacityGrpcService; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.test.TlsTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.context.ApplicationContext; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Full default Account application, real database/Redis and ordinary REQUIRE-mTLS listener. Empty + * capacity cohorts prove no durable creation only. Populated-family preservation, + * retention/erasure, production PKI, admission and owner activation are not qualified here. + */ +@Testcontainers +@SpringBootTest( + classes = AccountServiceApplication.class, + webEnvironment = WebEnvironment.RANDOM_PORT, + properties = { + "spring.config.import=classpath:account-main-application.yml", + "spring.grpc.server.port=0", + "spring.grpc.server.ssl.enabled=true", + "spring.grpc.server.ssl.bundle=firemud-grpc", + "spring.grpc.server.ssl.client-auth=REQUIRE", + "firemud.grpc.workload-namespace=test", + "firemud.mail.verification-url=https://account.test/verify-email?token=%s" + }) +class AccountRuntimeEntitlementNoWriteIntegrationTest { + private static final String METHOD = "account.v1.AccountService/GetTenantEntitlementsForRuntime"; + private static final List CAPACITY_TABLES = + List.of( + "account_tenant_capacity_evaluations", + "account_tenant_capacity_usage", + "account_tenant_capacity_reservations", + "account_tenant_capacity_attempt_history", + "account_tenant_capacity_recovery_evidence"); + private static final GetTenantEntitlementsForRuntimeRequest REQUEST = + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("default-runtime-entitlement-no-write") + .build(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private static Path tlsDirectory; + private static LoopbackMtlsTestPki.Pki pki; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) throws Exception { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + tlsDirectory = Files.createTempDirectory("account-runtime-no-write-mtls-"); + pki = + LoopbackMtlsTestPki.create( + tlsDirectory, + "Account default runtime no-write CA", + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", true), + new IdentitySpec( + "game-session", "spiffe://firemud/ns/test/sa/game-session-service", false), + new IdentitySpec( + "world", "spiffe://firemud/ns/test/sa/world-management-service", false), + new IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/entity-management-service", false), + new IdentitySpec( + "cross-namespace", "spiffe://firemud/ns/other/sa/game-session-service", false)); + var server = pki.clientProperties(tlsDirectory, pki.identity("account")); + registry.add("FIREMUD_GRPC_CERT_CHAIN_PATH", server::getCertChain); + registry.add("FIREMUD_GRPC_PRIVATE_KEY_PATH", server::getPrivateKey); + registry.add("FIREMUD_GRPC_CA_CERT_PATH", server::getCaCert); + } + + @Autowired private ApplicationContext context; + @Autowired private DataSource dataSource; + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private AccountServiceImpl accountFacade; + @Autowired private AccountGrpcService accountGrpcService; + @Autowired private GrpcServerLifecycle listener; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @BeforeEach + void assertActualDefaultRegistration() { + assertThat(listener.isRunning()).isTrue(); + assertThat(listener.getPort()).isPositive(); + assertThat(listener.getFactory()).isSameAs(context.getBean(GrpcServerFactory.class)); + assertThat(listener.getFactory()).isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(accountService).isSameAs(accountFacade); + for (Object actual : + List.of( + accountService, + accountGrpcService, + dataSource, + dsl, + context.getBean(GrpcPeerIdentityInterceptor.class))) { + assertThat(mockingDetails(actual).isMock()).isFalse(); + } + assertThat(context.getBeansOfType(GrpcPeerIdentityInterceptor.class)).hasSize(1); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(METHOD) + .doesNotContain("account.v1.AccountService/*"); + assertThat(context.getBeansOfType(AccountPlayerAdmissionEntitlementOwner.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountPlayerAdmissionEntitlementGrpcService.class)) + .isEmpty(); + assertThat(context.getBeansOfType(AccountPlayerAdmissionEntitlementWorkloadGuard.class)) + .isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityRepository.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityOwner.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityGrpcService.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityRecoveryWorker.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityWorkloadGuard.class)).isEmpty(); + assertThat(dsl.fetchValue("SELECT current_schema()", String.class)) + .isEqualTo("account_service"); + } + + @ParameterizedTest + @ValueSource(strings = {"game-session", "world"}) + void authorizedNumericRefusalAndExactRetryCreateNoCapacityRows(String identity) throws Exception { + Map before = emptyCapacityImages(); + ManagedChannel channel = channel(identity); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + for (int attempt = 0; attempt < 2; attempt++) { + assertRefusal( + stub.withDeadlineAfter(5, TimeUnit.SECONDS).getTenantEntitlementsForRuntime(REQUEST), + "ENTITLEMENT_UNAVAILABLE"); + assertThat(capacityImages()).isEqualTo(before); + } + } finally { + close(channel); + } + } + + @ParameterizedTest + @ValueSource(strings = {"wrong-service", "cross-namespace"}) + void deniedCertificateAndSpoofedMetadataCreateNoCapacityRows(String identity) throws Exception { + Map before = emptyCapacityImages(); + ManagedChannel channel = channel(identity); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + assertRefusal( + stub.withDeadlineAfter(5, TimeUnit.SECONDS).getTenantEntitlementsForRuntime(REQUEST), + "PERMISSION_DENIED"); + assertThat(capacityImages()).isEqualTo(before); + assertRefusal( + stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(fakePeer())) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getTenantEntitlementsForRuntime(REQUEST), + "PERMISSION_DENIED"); + assertThat(capacityImages()).isEqualTo(before); + } finally { + close(channel); + } + } + + @Test + void missingClientCertificateIsRefusedByTlsWithoutCapacityCreation() throws Exception { + Map before = emptyCapacityImages(); + ManagedChannel channel = channel(null); + try { + assertThatThrownBy( + () -> + AccountServiceGrpc.newBlockingStub(channel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(fakePeer())) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getTenantEntitlementsForRuntime(REQUEST)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + assertThat(capacityImages()).isEqualTo(before); + } finally { + close(channel); + } + } + + private static void assertRefusal(GetTenantEntitlementsForRuntimeResponse response, String code) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo(code); + assertThat(response.toBuilder().clearError().build()) + .isEqualTo(GetTenantEntitlementsForRuntimeResponse.getDefaultInstance()); + } + + private static Metadata fakePeer() { + Metadata headers = new Metadata(); + String claim = "spiffe://firemud/ns/test/sa/game-session-service"; + for (String name : + List.of("x-firemud-peer-identity", "x-spiffe-id", "x-forwarded-client-cert")) { + headers.put(Metadata.Key.of(name, Metadata.ASCII_STRING_MARSHALLER), claim); + } + return headers; + } + + private ManagedChannel channel(String identity) throws Exception { + var tls = GrpcSslContexts.forClient().trustManager(pki.trustManagerFactory()); + if (identity != null) tls.keyManager(pki.keyManagerFactory(pki.identity(identity))); + return NettyChannelBuilder.forAddress("localhost", listener.getPort()) + .sslContext(tls.build()) + .build(); + } + + private static void close(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private Map emptyCapacityImages() throws Exception { + Map images = capacityImages(); + assertThat(images).hasSize(5); + images.forEach( + (table, image) -> { + assertThat(image.count()).as(table).isZero(); + assertThat(image.rows()).as(table).isEmpty(); + }); + return images; + } + + private Map capacityImages() throws Exception { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + Map images = new LinkedHashMap<>(); + // Fresh autocommit connections observe committed postimages, never a shared test rollback. + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.getAutoCommit()).isTrue(); + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_READ_COMMITTED); + assertThat(connection.getMetaData().getDatabaseProductName()).isEqualTo("PostgreSQL"); + assertThat(connection.getCatalog()).isEqualTo(postgres.getDatabaseName()); + assertThat(connection.getSchema()).isEqualTo("account_service"); + for (String table : CAPACITY_TABLES) { + long count; + try (var statement = connection.createStatement(); + var result = statement.executeQuery("SELECT COUNT(*) FROM account_service." + table)) { + assertThat(result.next()).isTrue(); + count = result.getLong(1); + } + List rows = new ArrayList<>(); + try (var statement = connection.createStatement(); + var result = + statement.executeQuery( + "SELECT to_jsonb(t)::text, t.xmin::text FROM account_service." + + table + + " t ORDER BY 1, 2")) { + while (result.next()) rows.add(new RowImage(result.getString(1), result.getString(2))); + } + assertThat(rows).hasSize(Math.toIntExact(count)); + images.put(table, new TableImage(count, List.copyOf(rows))); + } + } + return Map.copyOf(images); + } + + @AfterAll + static void removeOwnedTlsFixture() throws Exception { + if (tlsDirectory != null) { + try (var files = Files.walk(tlsDirectory)) { + for (Path file : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(file); + } + } + } + + private record RowImage(String json, String xmin) {} + + private record TableImage(long count, List rows) {} +} From e5c814f1501774c85b041d6d0af60d0d754037d2 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 15:29:11 +1300 Subject: [PATCH 15/52] Distinguish Account capacity admission refusals --- .../account-service/api-contracts.md | 2 +- ...ystem-architecture-authz-route-matrix.yaml | 2 +- .../system-architecture-versioning-runtime.md | 2 +- .../AccountTenantCapacityRepository.java | 21 +++--- .../service/AccountTenantCapacityOwner.java | 56 +++++++++++----- .../AccountTenantCapacityGrpcService.java | 45 ++++--------- ...alAdmissionCompositionIntegrationTest.java | 63 +++++++++++++++--- ...CurrentSourcesPostgresIntegrationTest.java | 12 +--- .../AccountTenantCapacityOwnerTest.java | 66 ++++++++++++++++++- .../TenantCapacityAdmissionGrpcCodec.java | 65 ++++++++++++++++++ .../TenantCapacityAdmissionGrpcCodecTest.java | 24 +++++++ .../client/AccountTenantCapacityClient.java | 17 ++--- 12 files changed, 280 insertions(+), 95 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index e7e2ec4327..5fef7aa9d5 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -233,7 +233,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh non-creating evidence receives the existing `TENANT_BILLING_BLOCKED`/`RESOURCE_EXHAUSTED` policy denial before usage writes; malformed identity, stale evidence, unavailable authority, conflicting retries, and unsupported shapes retain their fail-closed refusals. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns `TENANT_BILLING_BLOCKED` with `RESOURCE_EXHAUSTED`. Fresh creation-eligible evidence with checked insufficient capacity returns `CAPACITY_QUOTA_EXCEEDED` with the same gRPC status. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 1ede0d0bce..511a7754b0 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -3177,7 +3177,7 @@ routes: changed_attempt_without_rearm_ordering: rejected_before_any_mutation mutation_contract: account_owned_fenced_capacity_reservation_create_or_replay canonical_errors: - any_of: [CAPACITY_ADMISSION_STALE, CAPACITY_QUOTA_EXCEEDED, FENCE_REJECTED, IDEMPOTENCY_CONFLICT, AUTH_UNAVAILABLE] + any_of: [CAPACITY_ADMISSION_STALE, CAPACITY_QUOTA_EXCEEDED, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, FENCE_REJECTED, IDEMPOTENCY_CONFLICT, AUTH_UNAVAILABLE, PERMISSION_DENIED, INVALID_ARGUMENT] fence_rejection_requirements: no_accept_no_runtime_mutation_proof - service: game-session-service route: ReadOriginalNewCapacityExecution diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index 95f565ad03..eb6cb274f1 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -486,7 +486,7 @@ For the capacity action-family schema, `capacityDelta` is a declared member of t The absent encoding exists only to produce a deterministic rejected digest vector; an absent request can never commit. -The capacity vector fixture is normative proof work for Account, Game Session, and World Management. It fixes every non-`capacityDelta` field in the published `capacity-admission/v1` schema, including the complete capacity shape used for non-expanding comparison, and publishes canonical preimage bytes plus the expected lowercase SHA-256 digest for `absent`, `present(0)`, a representative valid positive value such as `17`, and the boundary `present(9223372036854775807)`. It also publishes request candidates for `9223372036854775808`, signed negatives, malformed decimal spellings, signed-`int64`/JSON overflow, changed capacity-shape fields, and checked usage/quota addition overflow, with the expected rejection before commitment and no accepted mutation digest. Every implementation in Account and both callers must consume the same vectors and produce the same accepted/rejected result. The [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records the existing shared schema/vector fixtures and scoped proof; complete cross-language consumption, physical owner proof and runtime qualification remain required before capacity admission is enabled. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the focused proof and record fixture execution results in PR/CI or implementation-tracking evidence; it supplements these owner-local requirements and does not create an execution ledger. +The capacity vector fixture is normative proof work for Account, Game Session, and World Management. It fixes every non-`capacityDelta` field in the published `capacity-admission/v1` schema, including the complete capacity shape used for non-expanding comparison, and publishes canonical preimage bytes plus the expected lowercase SHA-256 digest for `absent`, `present(0)`, a representative valid positive value such as `17`, and the boundary `present(9223372036854775807)`. It also publishes request candidates for `9223372036854775808`, signed negatives, malformed decimal spellings, signed-`int64`/JSON overflow, changed capacity-shape fields, and checked usage/quota addition overflow, with the expected rejection before commitment and no accepted mutation digest. Every implementation in Account and both callers must consume the same vectors and produce the same accepted/rejected result. The [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the existing shared schema/vector fixtures and scoped proof; complete cross-language consumption, physical owner proof and runtime qualification remain required before capacity admission is enabled. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the focused proof and record fixture execution results in PR/CI or implementation-tracking evidence; it supplements these owner-local requirements and does not create an execution ledger. The changed-capacity-shape candidates in this fixture represent expanding or unvalidated changes and therefore must reject before commitment. A changed shape with Account-authenticated proof of a non-expanding effective resource delta is covered by the eligible replacement rule and is not an unconditional rejection case. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java index 9ab7e4ac68..6c67a69c23 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -133,8 +134,8 @@ public Result create(Request request, Instant expiresAt) { Record usage = usage(request); long delta = Objects.requireNonNull(request.capacityDelta()); long occupied = Math.addExact(number(usage, "held_units"), number(usage, "used_units")); - long after = Math.addExact(occupied, delta); - if (after > request.evidence().quota()) throw quota(); + if (delta > request.evidence().quota() - occupied) + throw new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED); long held = Math.addExact(number(usage, "held_units"), delta); updateUsage(request, usage, held, number(usage, "used_units")); int created = @@ -221,26 +222,22 @@ public static void transaction() { } public static CapacityException conflict() { - return new CapacityException("IDEMPOTENCY_CONFLICT"); + return new CapacityException(Failure.IDEMPOTENCY_CONFLICT); } public static CapacityException unavailable() { - return new CapacityException("ENTITLEMENT_UNAVAILABLE"); - } - - public static CapacityException quota() { - return new CapacityException("TENANT_BILLING_BLOCKED"); + return new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE); } public static final class CapacityException extends IllegalStateException { - private final String code; + private final Failure code; - public CapacityException(String code) { - super(code); + public CapacityException(Failure code) { + super(code.name()); this.code = code; } - public String code() { + public Failure code() { return code; } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index b2164e7299..a73f66c33f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -3,13 +3,13 @@ import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.number; -import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.quota; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.sql.Connection; import java.time.Clock; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Map; import java.util.Objects; import java.util.UUID; @@ -20,12 +20,14 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; 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.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.jooq.DSLContext; import org.jooq.Record; @@ -92,7 +94,8 @@ public Result commit(Request request, String authenticatedCaller) { if (request.capacityRearmFence() != 1) throw conflict(); current(request); requireSupportedShape(request); - if (!request.evidence().permitsCreation()) throw quota(); + if (!request.evidence().permitsCreation()) + throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); return capacity.create(request, request.evidence().expiresAt()); }); } @@ -169,28 +172,41 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { } private void current(Request request) { + var evidence = request.evidence(); + capacity.requireRetained(evidence); Instant now = clock.instant(); - request.evidence().requireCurrent(now); // PostgreSQL stores microseconds. Floor the bound, never round an expiry forward. - if (!now.isBefore( - request.evidence().expiresAt().truncatedTo(java.time.temporal.ChronoUnit.MICROS))) - throw unavailable(); - capacity.requireRetained(request.evidence()); + if (now.isBefore(evidence.evaluatedAt()) + || !now.isBefore(evidence.expiresAt().truncatedTo(ChronoUnit.MICROS))) + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); if (!(request.context() instanceof PlayerContext player)) throw unavailable(); var parsed = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( request.evidence().canonicalBytes()); - var current = memberships.readCurrent(player.accountId(), request.identity().tenantId()); - if (!current.equals(parsed.membershipSource()) - || !current.membershipExists() + var current = + qualifiedSource(() -> memberships.readCurrent(player.accountId(), player.tenantId())); + if (!current.membershipExists() || !current.gameplayAdmissionAllowed() || !"ACTIVE".equals(current.membershipLifecycleState())) throw unavailable(); - var fields = request.evidence().fields(); + var fields = evidence.fields(); + if (!current.equals(parsed.membershipSource())) { + var billing = + current + .authorityTuple() + .tenantBillingCutoff() + .map(cutoffs -> cutoffs.get(current.tenantId())) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + if (Long.parseLong(billing.tenantBillingSequence()) + > Long.parseLong((String) fields.get("tenantBillingSequence"))) + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + throw unavailable(); + } if (!(fields.get("sourceReferences") instanceof Map source)) throw unavailable(); var issuance = - issuances - .readCurrentCommittedCandidateByJti( - UUID.fromString((String) source.get("callerTokenJti"))) + qualifiedSource( + () -> + issuances.readCurrentCommittedCandidateByJti( + UUID.fromString((String) source.get("callerTokenJti")))) .orElseThrow(AccountTenantCapacityRepository::unavailable); if (!issuance.identity().accountId().equals(player.accountId()) || !issuance.identity().callerWorkload().equals(request.evidence().callerWorkload()) @@ -205,8 +221,8 @@ private void current(Request request) { || now.getEpochSecond() >= issuance.identity().expiresAtEpochSecond()) throw unavailable(); String connect = (String) fields.get("verifiedConnectScopeId"); var scope = - scopes - .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(connect)) + qualifiedSource( + () -> scopes.findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(connect))) .orElseThrow(AccountTenantCapacityRepository::unavailable); if (!scope.accountUuid().equals(player.accountId()) || !scope.tenantUuid().equals(player.tenantId()) @@ -218,6 +234,14 @@ private void current(Request request) { || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) throw unavailable(); } + private static T qualifiedSource(Supplier read) { + try { + return read.get(); + } catch (IllegalArgumentException | IllegalStateException unqualifiedSource) { + throw unavailable(); + } + } + private static void requireSupportedShape(Request request) { if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION || request.operation() != TenantCapacityAdmission.Operation.CAPACITY_CREATING diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index 0c3784b27b..31b90aa3e9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -1,12 +1,10 @@ package net.firedevops.firemud.accountservice.service.impl; -import com.google.protobuf.Any; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.TlsServerCredentials; -import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.Objects; @@ -19,9 +17,9 @@ import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; -import net.firedevops.firemud.shared.v1.ErrorDetail; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Explicit private composition only. Other Account RPCs remain UNIMPLEMENTED on this server. */ @@ -59,70 +57,49 @@ public void commitTenantCapacityAdmission( try { peer = guard.requireAuthenticatedCaller(); } catch (StatusRuntimeException denied) { - fail(observer, denied.getStatus(), "AUTH_UNAVAILABLE"); + observer.onError(Failure.AUTH_UNAVAILABLE.toStatusException()); return; } if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { - fail(observer, Status.FAILED_PRECONDITION, "ENTITLEMENT_UNAVAILABLE"); + observer.onError( + Failure.ENTITLEMENT_UNAVAILABLE.toStatusException(Status.Code.FAILED_PRECONDITION)); return; } final net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request; try { request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); } catch (IllegalArgumentException | ArithmeticException invalid) { - fail(observer, Status.INVALID_ARGUMENT, "INVALID_ARGUMENT"); + observer.onError(Failure.INVALID_ARGUMENT.toStatusException()); return; } if (!request.evidence().callerWorkload().equals(peer)) { - fail(observer, Status.PERMISSION_DENIED, "AUTH_UNAVAILABLE"); + observer.onError(Failure.PERMISSION_DENIED.toStatusException()); return; } final CommitTenantCapacityAdmissionResponse result; try { result = TenantCapacityAdmissionGrpcCodec.toResponse(request, owner.commit(request, peer)); } catch (CapacityException denied) { - fail( - observer, - "IDEMPOTENCY_CONFLICT".equals(denied.code()) - ? Status.ALREADY_EXISTS - : "TENANT_BILLING_BLOCKED".equals(denied.code()) - ? Status.RESOURCE_EXHAUSTED - : Status.UNAVAILABLE, - denied.code()); + observer.onError(denied.code().toStatusException()); return; } catch (org.jooq.exception.DataAccessException | org.springframework.dao.DataAccessException | org.springframework.transaction.TransactionException unavailable) { - fail(observer, Status.UNAVAILABLE, "ENTITLEMENT_UNAVAILABLE"); + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); return; } catch (IllegalArgumentException | ArithmeticException invalid) { - fail(observer, Status.INVALID_ARGUMENT, "INVALID_ARGUMENT"); + observer.onError(Failure.INVALID_ARGUMENT.toStatusException()); return; } catch (RuntimeException internal) { - fail(observer, Status.INTERNAL, "ENTITLEMENT_UNAVAILABLE"); + observer.onError(Status.INTERNAL.asRuntimeException()); return; } try { observer.onNext(result); observer.onCompleted(); } catch (RuntimeException callback) { - fail(observer, Status.INTERNAL, "ENTITLEMENT_UNAVAILABLE"); + observer.onError(Status.INTERNAL.asRuntimeException()); } } - - private static void fail(StreamObserver observer, Status status, String code) { - observer.onError( - StatusProto.toStatusRuntimeException( - com.google.rpc.Status.newBuilder() - .setCode(status.getCode().value()) - .setMessage("Tenant capacity commitment did not complete") - .addDetails( - Any.pack( - ErrorDetail.newBuilder() - .setCode(code) - .setMessage("Tenant capacity commitment did not complete") - .build())) - .build())); - } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index d592335910..48638e2c2d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -348,7 +348,7 @@ void missingActualInitialBarrierRefusesWithoutRecreatingOpenOrAdmittingCandidate @Test void freshRetainedNonCreatingEvaluationIsPolicyDeniedWithoutOwnerMutation() throws Exception { try (Session session = session()) { - var denied = session.retainControlledNonCreatingEvaluation(); + var denied = session.retainControlledEvaluation(false, null); assertThat(denied.evidence().permitsCreation()).isFalse(); byte[] candidate = session.gs.physicalSession(); assertThat(candidate).isNotNull(); @@ -363,11 +363,44 @@ void freshRetainedNonCreatingEvaluationIsPolicyDeniedWithoutOwnerMutation() thro } } + @Test + void freshCreationEligibleEvidenceWithZeroQuotaIsDeniedWithoutOwnerMutation() throws Exception { + try (Session session = session()) { + var request = session.retainControlledEvaluation(true, "0"); + assertThat(request.evidence().permitsCreation()).isTrue(); + assertThat(request.evidence().quota()).isZero(); + assertCapacityRefusalWithoutMutation( + session, request, Status.Code.RESOURCE_EXHAUSTED, "CAPACITY_QUOTA_EXCEEDED"); + } + } + + @Test + void exactRetainedEvaluationOutsideOwnerWindowIsStaleWithoutOwnerMutation() throws Exception { + try (Session session = session(Clock.offset(CLOCK, Duration.ofSeconds(60)))) { + assertCapacityRefusalWithoutMutation( + session, session.capacityRequest, Status.Code.UNAVAILABLE, "CAPACITY_ADMISSION_STALE"); + } + } + + private static void assertCapacityRefusalWithoutMutation( + Session session, TenantCapacityAdmission.Request request, Status.Code status, String code) + throws Exception { + byte[] candidate = session.gs.physicalSession(); + assertThat(candidate).isNotNull(); + String before = session.capacityImage() + session.durableImage(); + assertCapacityFailure( + assertThrows(StatusRuntimeException.class, () -> session.capacityClient.commit(request)), + status, + code); + assertThat(session.capacityImage() + session.durableImage()).isEqualTo(before); + assertProvisionalUnchanged(session, candidate); + } + @Test void retainedOriginalReplaysBeforeChangedNonCreatingEvidenceCanBecomeADenial() throws Exception { try (Session session = session()) { var first = session.capacityClient.commit(session.capacityRequest); - var changed = session.retainControlledNonCreatingEvaluation(); + var changed = session.retainControlledEvaluation(false, null); byte[] candidate = session.gs.physicalSession(); assertThat(candidate).isNotNull(); String before = session.capacityImage() + session.durableImage(); @@ -403,8 +436,12 @@ private static void assertCapacityFailure( } private Session session() throws Exception { + return session(CLOCK); + } + + private Session session(Clock capacityClock) throws Exception { accountFixtures.temporaryDirectory = temporaryDirectory; - return new Session(); + return new Session(capacityClock); } private final class Session implements AutoCloseable { @@ -437,7 +474,7 @@ private final class Session implements AutoCloseable { private AccountGameplayAdmissionLeaseEvidence lease; private CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector targetSelector; - private Session() throws Exception { + private Session(Clock capacityClock) throws Exception { try { account = accountFixtures.newCapacityPlayerEntitlementFixture(redis.client()); dsl = @@ -597,7 +634,7 @@ private Session() throws Exception { 1L, null) .withDigest(); - capacityOwner = account.capacityOwner(); + capacityOwner = account.capacityOwner(capacityClock); capacityServer = new net.firedevops.firemud.accountservice.service.impl.AccountTenantCapacityGrpcService( capacityOwner, "test") @@ -702,7 +739,8 @@ private Genesis genesis() { /** Controlled entitlement facts, real current caller/scope and actual immutable retention. */ @SuppressWarnings("unchecked") - private TenantCapacityAdmission.Request retainControlledNonCreatingEvaluation() { + private TenantCapacityAdmission.Request retainControlledEvaluation( + boolean creationAllowed, @org.jspecify.annotations.Nullable String quota) { var original = capacityRequest; var parsed = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( @@ -724,8 +762,13 @@ private TenantCapacityAdmission.Request retainControlledNonCreatingEvaluation() "tenantAuthorityGeneration")) { facts.put(name, fields.get(name)); } - facts.put("allowNewGameplayBindings", false); - var denied = + facts.put("allowNewGameplayBindings", creationAllowed); + if (quota != null) { + var quotas = new LinkedHashMap<>((Map) facts.get("quotas")); + quotas.put(original.context().owner().quota(), quota); + facts.put("quotas", quotas); + } + var evaluation = RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( original.identity().requestId(), original.evidence().callerWorkload(), @@ -736,7 +779,7 @@ private TenantCapacityAdmission.Request retainControlledNonCreatingEvaluation() (Map) fields.get("sourceReferences"), CLOCK.instant()); serializable.executeWithoutResult( - ignored -> new AccountTenantCapacityRepository(dsl).retainPlayerEvaluation(denied)); + ignored -> new AccountTenantCapacityRepository(dsl).retainPlayerEvaluation(evaluation)); return new TenantCapacityAdmission.Request( original.identity(), original.admissionAttemptId(), @@ -746,7 +789,7 @@ private TenantCapacityAdmission.Request retainControlledNonCreatingEvaluation() original.operation(), original.priorShape(), original.requestedShape(), - TenantCapacityAdmission.Evidence.player(denied), + TenantCapacityAdmission.Evidence.player(evaluation), original.capacityDelta(), null) .withDigest(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java index c8540dcce0..2dc00bd716 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -2304,7 +2304,8 @@ private void bootstrapFreshCapacityBaseline() { bootstrap.bootstrap(creatorEvidence); } - net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner capacityOwner() { + net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner capacityOwner( + Clock clock) { var snapshots = new AccountCanonicalRuntimeMembershipSnapshotRepository( accounts, @@ -2317,14 +2318,7 @@ net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner capacit membershipRoles, authorityOutbox); return new net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner( - dsl, - accounts, - snapshots, - issuance, - connectScopes, - manager, - Clock.systemUTC(), - TEST_NAMESPACE); + dsl, accounts, snapshots, issuance, connectScopes, manager, clock, TEST_NAMESPACE); } net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2 capacityScope( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 29b633a7ed..f85064e8f8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -14,6 +14,7 @@ import java.sql.Connection; import java.time.Clock; import java.time.ZoneOffset; +import java.util.Map; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; @@ -23,6 +24,9 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; @@ -159,15 +163,60 @@ void unretainedNonCreatingEvidenceRemainsUnavailableWithoutAnyUsageWrite() throw } @Test - void staleNonCreatingEvidenceStaysInvalidInsteadOfBecomingPolicyDenial() throws Exception { + void exactRetainedNonCreatingEvidenceOutsideWindowIsStale() throws Exception { var f = new Fixture(true, CapacityAdmissionTestFixture.playerRequest(false)); f.existing = false; + f.retained = true; assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) - .isInstanceOf(IllegalArgumentException.class); + .hasMessage("CAPACITY_ADMISSION_STALE"); verifyNoInteractions(f.memberships, f.issuances, f.scopes); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void qualifiedNewerBillingCutoffMakesExactRetainedEvaluationStale() throws Exception { + var f = new Fixture(false); + f.existing = false; + f.retained = true; + var current = mock(Snapshot.class); + var tuple = mock(AuthorityTuple.class); + var tenant = f.request.identity().tenantId().toString(); + var sequence = + Long.parseLong((String) f.request.evidence().fields().get("tenantBillingSequence")); + when(current.membershipExists()).thenReturn(true); + when(current.membershipLifecycleState()).thenReturn("ACTIVE"); + when(current.gameplayAdmissionAllowed()).thenReturn(true); + when(current.tenantId()).thenReturn(tenant); + when(current.authorityTuple()).thenReturn(tuple); + when(tuple.tenantBillingCutoff()) + .thenReturn( + Optional.of( + Map.of( + tenant, + new TenantBillingCutoff("1", Long.toString(sequence + 1), "billing", "2")))); + when(f.memberships.readCurrent( + CapacityAdmissionTestFixture.ACCOUNT, f.request.identity().tenantId())) + .thenReturn(current); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("CAPACITY_ADMISSION_STALE"); + verifyNoInteractions(f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void currentOwnerReadWithoutQualifiedEvidenceIsUnavailable() throws Exception { + var f = new Fixture(false); + f.existing = false; + f.retained = true; + when(f.memberships.readCurrent( + CapacityAdmissionTestFixture.ACCOUNT, f.request.identity().tenantId())) + .thenThrow(new IllegalStateException("Missing committed source")); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + @Test void nonCreatingEvidenceCannotStartRecoveryOrRearmWork() throws Exception { var f = new Fixture(false); @@ -217,6 +266,7 @@ private static final class Fixture { private final UUID reservation = UUID.randomUUID(); private final AccountTenantCapacityOwner owner; private boolean existing = true; + private boolean retained; private Fixture(boolean expired) throws Exception { this(expired, CapacityAdmissionTestFixture.playerRequest()); @@ -256,6 +306,16 @@ private Fixture(boolean expired, Request request) throws Exception { Record evaluation = mock(Record.class); when(evaluation.get("snapshot_identity", String.class)) .thenReturn(request.evidence().snapshotIdentity()); + var evidence = request.evidence(); + when(evaluation.get("tenant_uuid", UUID.class)).thenReturn(evidence.tenantId()); + when(evaluation.get("caller_workload", String.class)).thenReturn(evidence.callerWorkload()); + when(evaluation.get("owner_service", String.class)).thenReturn(evidence.owner().service()); + when(evaluation.get("canonical_evidence", byte[].class)) + .thenReturn(evidence.canonicalBytes()); + when(evaluation.get("evaluated_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(evidence.evaluatedAt())); + when(evaluation.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(evidence.expiresAt())); when(dsl.fetchOne(anyString(), any(Object[].class))) .thenAnswer( invocation -> { @@ -266,7 +326,7 @@ private Fixture(boolean expired, Request request) throws Exception { "SELECT snapshot_identity FROM account_tenant_capacity_evaluations ")) return evaluation; if (sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) - return null; + return retained ? evaluation : null; throw new AssertionError(sql); }); owner = diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index 8cee9f1a85..4eb6166481 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -1,7 +1,12 @@ package net.firedevops.firemud.common.account.capacity; +import com.google.protobuf.Any; import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.StatusProto; import java.time.Instant; import java.util.List; import java.util.UUID; @@ -22,6 +27,7 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Shape; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext; +import net.firedevops.firemud.shared.v1.ErrorDetail; /** Strict bounded content mapping. TLS identity and source authority are never codec inputs. */ public final class TenantCapacityAdmissionGrpcCodec { @@ -29,8 +35,67 @@ public final class TenantCapacityAdmissionGrpcCodec { public static final int MAX_RESPONSE_WIRE_BYTES = 4096; public static final long CALL_DEADLINE_SECONDS = 5; + private static final String FAILURE_MESSAGE = "Tenant capacity commitment did not complete"; + private TenantCapacityAdmissionGrpcCodec() {} + public enum Failure { + INVALID_ARGUMENT(Status.Code.INVALID_ARGUMENT), + AUTH_UNAVAILABLE(Status.Code.UNAUTHENTICATED), + PERMISSION_DENIED(Status.Code.PERMISSION_DENIED), + IDEMPOTENCY_CONFLICT(Status.Code.ALREADY_EXISTS), + CAPACITY_ADMISSION_STALE(Status.Code.UNAVAILABLE), + ENTITLEMENT_UNAVAILABLE(Status.Code.UNAVAILABLE), + TENANT_BILLING_BLOCKED(Status.Code.RESOURCE_EXHAUSTED), + CAPACITY_QUOTA_EXCEEDED(Status.Code.RESOURCE_EXHAUSTED); + + private final Status.Code code; + + Failure(Status.Code code) { + this.code = code; + } + + public StatusRuntimeException toStatusException() { + return toStatusException(code); + } + + public StatusRuntimeException toStatusException(Status.Code status) { + if (!matches(status)) throw invalid(); + return StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.value()) + .setMessage(FAILURE_MESSAGE) + .addDetails(Any.pack(detail())) + .build()); + } + + private ErrorDetail detail() { + return ErrorDetail.newBuilder().setCode(name()).setMessage(FAILURE_MESSAGE).build(); + } + + private boolean matches(Status.Code status) { + return status == code + || (this == ENTITLEMENT_UNAVAILABLE && status == Status.Code.FAILED_PRECONDITION); + } + } + + /** Preserve the transport outcome. Accept semantic details only in the closed owner format. */ + public static StatusRuntimeException validateFailure(StatusRuntimeException failure) { + try { + var status = StatusProto.fromThrowable(failure); + if (status == null || status.getDetailsCount() == 0) return failure; + if (status.getDetailsCount() == 1 && status.getSerializedSize() <= MAX_RESPONSE_WIRE_BYTES) { + var detail = status.getDetails(0).unpack(ErrorDetail.class); + var error = Failure.valueOf(detail.getCode()); + if (error.matches(failure.getStatus().getCode()) && error.detail().equals(detail)) + return failure; + } + } catch (InvalidProtocolBufferException | IllegalArgumentException invalidDetail) { + // A malformed detail supplies no owner decision or execution proof. + } + return failure.getStatus().asRuntimeException(); + } + public static CommitTenantCapacityAdmissionRequest toRequest(Request value) { value.requireStructurallyValid(); var attempt = diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index 5af0f67dcc..933cffc97d 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -3,15 +3,39 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.Any; import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; import java.util.List; import java.util.UUID; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; class TenantCapacityAdmissionGrpcCodecTest { + @Test + void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { + for (var failure : Failure.values()) { + var canonical = failure.toStatusException(); + assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(canonical)).isSameAs(canonical); + } + var deadline = Status.DEADLINE_EXCEEDED.asRuntimeException(); + assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(deadline)).isSameAs(deadline); + var claimedFence = + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(Status.Code.UNAVAILABLE.value()) + .addDetails(Any.pack(ErrorDetail.newBuilder().setCode("FENCE_REJECTED").build())) + .build()); + var verified = TenantCapacityAdmissionGrpcCodec.validateFailure(claimedFence); + assertThat(verified.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(StatusProto.fromThrowable(verified).getDetailsList()).isEmpty(); + } + @Test void exactBothAlternativesRoundTripWithCompleteBundleAndReservationBinding() { for (Request request : diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index 0af7aa0f78..f89bd69d1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.client; import io.grpc.ManagedChannel; +import io.grpc.StatusRuntimeException; import java.io.IOException; import java.time.Clock; import java.util.Objects; @@ -65,14 +66,14 @@ public Result commit(Request request) { TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .withMaxOutboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES) .withMaxInboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_RESPONSE_WIRE_BYTES); - Result result = - TenantCapacityAdmissionGrpcCodec.requireResponse( - request, - stub.commitTenantCapacityAdmission( - TenantCapacityAdmissionGrpcCodec.toRequest(request))); - // Exact retry may replay an expired/terminal reservation. Returning it grants no activation; - // the selected owner's final CAS must compare its current reservation fence and expiry. - return result; + try { + // Exact retry may replay an expired/terminal reservation. The final owner still checks it. + return TenantCapacityAdmissionGrpcCodec.requireResponse( + request, + stub.commitTenantCapacityAdmission(TenantCapacityAdmissionGrpcCodec.toRequest(request))); + } catch (StatusRuntimeException failure) { + throw TenantCapacityAdmissionGrpcCodec.validateFailure(failure); + } } @Override From 3fe1372822ebb35ee3e088f5fe543c21e6381b2f Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 16:00:07 +1300 Subject: [PATCH 16/52] Validate original capacity binding before Account commitment --- ...alAdmissionCompositionIntegrationTest.java | 83 ++++++++++++++ ...playOriginalNewCapacityExecutionOwner.java | 49 ++++++-- ...yOriginalNewFinalAdmissionCoordinator.java | 19 ++-- ...ayOriginalNewFinalAdmissionRedisOwner.java | 10 -- ...alNewFinalAdmissionCompositionFixture.java | 62 ++++++++++ ...NewFinalAdmissionOwnerIntegrationTest.java | 106 +++++++++++++++--- 6 files changed, 280 insertions(+), 49 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 48638e2c2d..413649446f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -270,6 +270,89 @@ void missingCapacityInputRefusesBeforeAnyFinalSessionOrReservationMutation() thr } } + @Test + void mismatchedCapacityRequestRefusesBeforeAccountCommit() throws Exception { + try (Session session = session()) { + var original = session.capacityRequest; + var mismatched = + new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity( + original.identity().tenantId(), + original.identity().requestId(), + UUID.randomUUID()), + original.admissionAttemptId(), + original.capacityRearmFence(), + original.targetNamespace(), + original.context(), + original.operation(), + original.priorShape(), + original.requestedShape(), + original.evidence(), + original.capacityDelta(), + null) + .withDigest(); + mismatched.requireStructurallyValid(); + String capacityBefore = session.capacityImage(); + var gsBefore = session.gs.capacityStateImage(); + for (int attempt = 0; attempt < 2; attempt++) { + assertThatThrownBy( + () -> + session.gs.complete( + session.client, + session.jwks, + session.jwt, + System.currentTimeMillis() + 10_000L, + session.capacityClient, + mismatched)) + .isInstanceOf(IllegalStateException.class); + assertThat(session.capacityImage()).isEqualTo(capacityBefore); + assertThat(session.gs.capacityStateImage()).isEqualTo(gsBefore); + assertThat(session.gs.finalReadCalls()).isZero(); + } + + // A structurally valid non-creating observation reaches the real Account policy owner. + var denied = session.retainControlledEvaluation(false, null); + denied.requireStructurallyValid(); + String beforeDenial = session.capacityImage(); + byte[] candidate = session.gs.physicalSession(); + assertThatThrownBy( + () -> + session.gs.complete( + session.client, + session.jwks, + session.jwt, + System.currentTimeMillis() + 10_000L, + session.capacityClient, + denied)) + .isInstanceOf(IllegalStateException.class) + .hasCauseInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertCapacityFailure( + (StatusRuntimeException) failure.getCause(), + Status.Code.RESOURCE_EXHAUSTED, + "TENANT_BILLING_BLOCKED")); + assertThat(session.capacityImage()).isEqualTo(beforeDenial); + assertProvisionalUnchanged(session, candidate); + } + try (Session session = session()) { + var request = session.capacityRequest; + byte[] candidate = session.gs.physicalSession(); + var fault = + session.gs.commitThenMoveSelectedOwnerForFault( + session.capacityClient, request, System.currentTimeMillis() + 10_000L); + fault.reservation().requireBinding(request); + assertThat(fault.reservation().state()).isEqualTo(TenantCapacityAdmission.State.RESERVED); + String committedCapacity = session.capacityImage(); + var movedGs = session.gs.capacityStateImage(); + assertThatThrownBy(fault.bindOriginal()::run).isInstanceOf(IllegalStateException.class); + assertThat(session.capacityImage()).isEqualTo(committedCapacity); + assertThat(session.gs.capacityStateImage()).isEqualTo(movedGs); + assertThat(session.gs.physicalSession()).containsExactly(candidate); + assertThat(session.gs.finalReadCalls()).isZero(); + } + } + @Test void actualPostActiveSqlConfirmationLossRecoversThroughFreshProtectedFinalRead() throws Exception { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 38a9fc00d4..a0d53d56bc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -87,11 +87,44 @@ OriginalNewCapacityExecution bind( Request request, Result result, long deadline) { + return bind(source, request, result, deadline, null); + } + + OriginalNewCapacityExecution bind( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + Request request, + Result result, + long deadline, + CurrentOwner expectedOwner) { if (budget == null) - return within(deadline, owner -> owner.bind(source, request, result, deadline)); + return within( + deadline, owner -> owner.bind(source, request, result, deadline, expectedOwner)); budget.check(); request.requireCommittable(); result.requireBinding(request); + CurrentOwner selected = requireRequestBinding(source, request, deadline); + if (expectedOwner != null && !expectedOwner.equals(selected)) throw unavailable(); + var candidate = source.candidate(); + return new OriginalNewCapacityExecution( + request, + result, + candidate.bindingDecisionId(), + source.candidateDigest(), + selected.instanceId(), + selected.fence()); + } + + /** Qualifies deterministic candidate binding before Account commits a reservation. */ + CurrentOwner requireRequestBinding( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + Request request, + long deadline) { + noSql(); + if (budget == null) + return within(deadline, owner -> owner.requireRequestBinding(source, request, deadline)); + budget.check(); + // Account owns fresh policy denial; coherent non-creating evidence must reach that owner. + request.requireStructurallyValid(); var candidate = source.candidate(); var binding = candidate.bindingIdentity(); var target = candidate.targetEvidence(); @@ -114,16 +147,10 @@ OriginalNewCapacityExecution bind( || !Objects.equals( request.evidence().fields().get("authorityTuple"), candidate.leaseEvidence().carrier().get("authorityTuple"))) throw unavailable(); - var region = source.regionAcknowledgement(); CurrentOwner selected = currentOwner(candidate); - if (selected.fence() != region.executorFence().longValueExact()) throw unavailable(); - return new OriginalNewCapacityExecution( - request, - result, - candidate.bindingDecisionId(), - source.candidateDigest(), - selected.instanceId(), - region.executorFence().longValueExact()); + if (selected.fence() != source.regionAcknowledgement().executorFence().longValueExact()) + throw unavailable(); + return selected; } /** Returns only after independently reading the already-installed exact execution record. */ @@ -491,7 +518,7 @@ private CurrentOwner currentOwner(CanonicalGameplayOriginalNewCandidate candidat return new CurrentOwner(instance, fence); } - private record CurrentOwner(String instanceId, long fence) {} + record CurrentOwner(String instanceId, long fence) {} private String candidateDigest(Record row) { Record transition = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index a5c0896168..80c0888016 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -94,15 +94,6 @@ final class CanonicalGameplayOriginalNewFinalAdmissionCoordinator { * Completes one already-installed original NEW candidate and returns only a redacted internal * receipt. Uncertainty preserves the owners' retryable evidence and never invents cleanup. */ - FinalAdmissionResult completeOriginalNew( - CanonicalGameplayAdmissionDecision originalDecision, - String originalLoginJwt, - CanonicalGameplayRegionLeaseOwner.Installation privateRegionInstallation, - long canonicalSessionDurationMillis, - long absoluteDeadlineMillis) { - throw unavailable(); - } - FinalAdmissionResult completeOriginalNew( CanonicalGameplayAdmissionDecision originalDecision, String originalLoginJwt, @@ -113,7 +104,7 @@ FinalAdmissionResult completeOriginalNew( requireNoAmbientSql(); if (capacityClient == null || capacityExecution == null) throw unavailable(); if (capacityRequest == null) throw unavailable(); - capacityRequest.requireCommittable(); + capacityRequest.requireStructurallyValid(); Objects.requireNonNull(originalDecision, "Original Account decision is required"); Objects.requireNonNull( privateRegionInstallation, "This owner's private region grant is required"); @@ -139,6 +130,8 @@ FinalAdmissionResult completeOriginalNew( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source = inventory.readOriginalNewFinalAdmissionSource(originalDecision); requireOriginalSource(source, originalDecision); + var selectedOwner = + capacityExecution.requireRequestBinding(source, capacityRequest, absoluteDeadlineMillis); Currentness beforeEffects = currentness(source, privateRegionInstallation); CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource currentSource = readSameSource(source, originalDecision, false); @@ -178,9 +171,13 @@ FinalAdmissionResult completeOriginalNew( // This is the actual final owner boundary, after all original player evidence and // credential/currentness checks. The Account commitment is never a quota preflight. + if (!selectedOwner.equals( + capacityExecution.requireRequestBinding( + source, capacityRequest, absoluteDeadlineMillis))) throw unavailable(); var reservation = capacityClient.commit(capacityRequest); var execution = - capacityExecution.bind(source, capacityRequest, reservation, absoluteDeadlineMillis); + capacityExecution.bind( + source, capacityRequest, reservation, absoluteDeadlineMillis, selectedOwner); try (var boundTemplate = template.bindCapacityExecution(execution)) { capacityExecution.authorize( source, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index c91abe99b1..36b9be49ba 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -158,16 +158,6 @@ final class CanonicalGameplayOriginalNewFinalAdmissionRedisOwner { * read-only physical inspection. Only independently verified postimages produce a private * readback capability. */ - /** Unqualified historical compositions have no capacity authority and cannot admit. */ - Readback finalizeOriginalNewOnce( - CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, - CanonicalGameplayOriginalNewAuthenticatedSession.Template template, - CanonicalGameplayAccountInitialOpenProof.CurrentOpen accountOpen, - CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback issuerOpen, - long absoluteDeadlineMillis) { - throw unavailable(); - } - Readback finalizeOriginalNewOnce( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, CanonicalGameplayOriginalNewAuthenticatedSession.Template template, 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 49d397f58b..beacb02552 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 @@ -691,6 +691,68 @@ public byte[] physicalSession() { return administration.sync().get(ascii(candidateInstallation.sessionKey())); } + /** Actual Account commit followed by a controlled selected-owner movement before GS binding. */ + public OwnerMovementFault commitThenMoveSelectedOwnerForFault( + net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient client, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, + long deadline) { + var source = + new CanonicalGameplayBindingInventoryRepository(binding.dsl()) + .readOriginalNewFinalAdmissionSource(decision); + var executionOwner = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + binding.dsl(), coordination, scripts, CLOCK, tags); + var selected = executionOwner.requireRequestBinding(source, request, deadline); + var result = client.commit(request); + var identity = source.candidate().bindingIdentity(); + if (binding + .dsl() + .execute( + "UPDATE game_session_region_runtime_status SET executor_fence = executor_fence + 1 WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + identity.tenantId(), + identity.gameInstanceId(), + identity.regionId()) + != 1) + throw new IllegalStateException("Controlled owner movement did not affect the selected row"); + return new OwnerMovementFault( + result, () -> executionOwner.bind(source, request, result, deadline, selected)); + } + + public record OwnerMovementFault( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result reservation, + Runnable bindOriginal) {} + + /** Read-only images of the isolated fixture's actual admission SQL and Redis state. */ + public java.util.Map capacityStateImage() { + var result = new java.util.TreeMap(); + for (String table : + java.util.List.of( + "game_session_canonical_binding_transition", + "game_session_original_new_capacity_execution")) { + String rows = + binding + .dsl() + .fetch( + "SELECT (to_jsonb(t) || jsonb_build_object('_xmin', t.xmin::text))::text AS image FROM " + + table + + " t ORDER BY 1") + .getValues("image", String.class) + .toString(); + result.put( + "sql:" + table, + net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution.sha256( + rows.getBytes(StandardCharsets.UTF_8))); + } + var commands = administration.sync(); + for (byte[] key : commands.keys("*")) { + result.put( + "redis:" + new String(key, StandardCharsets.UTF_8), + net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution.sha256( + commands.dump(key))); + } + return java.util.Map.copyOf(result); + } + /** Controlled post-retention serving loss only, not proof of actual runtime teardown ordering. */ public void removeServingIndexesAfterCapacityRetentionForFault() { String state = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 86b2520caf..e573819877 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -162,6 +162,30 @@ void tearDown() throws Exception { } } + @Test + void missingCapacityExecutionRefusesTheCanonicalFinalPathWithoutMutation() throws Exception { + repairAccountMember(); + bridge(false); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var account = controlledAccountOpen(); + var issuer = issuerOpen(); + String rows = sqlImage(); + var physical = physicalImage(); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template()) { + assertThatThrownBy( + () -> + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + ownerClient, catalog, CLOCK, tags) + .finalizeOriginalNewOnce(source, template, account, issuer, null, deadline())) + .isExactlyInstanceOf(NullPointerException.class) + .hasMessage("Exact Account capacity execution is required"); + } + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + } + @Test void missingExecutionCannotBeReinstalledFromTheRetainedSqlDispatchOrUsedAsNoCommit() throws Exception { @@ -283,7 +307,12 @@ void recreatedCapacityOwnerClosesExactAttemptAndRejectsDelayedFinalCas() throws () -> finalOwner() .finalizeOriginalNewOnce( - source, template, controlledAccountOpen(), issuerOpen(), deadline())) + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) .isInstanceOf(IllegalStateException.class); } var assignment = tags.assignmentForTransition(fixture.transitionId()); @@ -329,7 +358,8 @@ void retainedClosedProofSurvivesControlledServingRemovalAndStillRejectsDelayedFi assertThatThrownBy( () -> finalOwner() - .finalizeOriginalNewOnce(source, template, account, issuer, deadline())) + .finalizeOriginalNewOnce( + source, template, account, issuer, controlledCapacity, deadline())) .isInstanceOf(IllegalStateException.class); } assertThat(admin.hget(ascii(capacityKey(assignment)), ascii("state"))) @@ -525,7 +555,8 @@ void committedReceiptSurvivesDeleteRefusalAndClockUnavailabilityUntilCatchup() t var template = credential.template(); var actual = finalOwner() - .finalizeOriginalNewOnce(source, template, accountOpen, issuerOpen, deadline())) { + .finalizeOriginalNewOnce( + source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { inventory.commitOriginalNewFinalAdmission(actual); String retainedReceiptQuery = "SELECT xmin::text || '/' || to_jsonb(transition)::text" @@ -644,7 +675,8 @@ private void assertSameNativeCandidateFinalizesCommitsReadsAndRecoversExactTimes var template = credential.template(); var actual = finalOwner() - .finalizeOriginalNewOnce(source, template, accountOpen, issuerOpen, deadline())) { + .finalizeOriginalNewOnce( + source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { assertThat(credential.boundJti().toString()).isNotEqualTo(credential.initialLoginJti()); assertThat(new String(template.finalCasTemplateBytes(), StandardCharsets.UTF_8)) .doesNotContain(credential.jwt()) @@ -658,6 +690,7 @@ private void assertSameNativeCandidateFinalizesCommitsReadsAndRecoversExactTimes template, accountOpen, issuerOpen, + controlledCapacity, deadline())) { assertThat(provisionalReplay.exactCanonicalBytes()) .containsExactly(actual.exactCanonicalBytes()); @@ -1025,7 +1058,12 @@ private void assertSameNativeCandidateFinalizesCommitsReadsAndRecoversExactTimes try (var replay = finalOwner() .finalizeOriginalNewOnce( - recoveredSource, template, accountOpen, issuerOpen, deadline())) { + recoveredSource, + template, + accountOpen, + issuerOpen, + controlledCapacity, + deadline())) { assertThat(replay.exactCanonicalBytes()).containsExactly(actual.exactCanonicalBytes()); assertThat(recoveredInventory.commitOriginalNewFinalAdmission(replay).status()) .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED); @@ -1070,7 +1108,8 @@ void missingOrChangedIndexesAndBarriersNeverRecreateCommittedPostimagesOrExtendT var template = credential.template(); var actual = finalOwner() - .finalizeOriginalNewOnce(source, template, accountOpen, issuerOpen, deadline())) { + .finalizeOriginalNewOnce( + source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { inventory.commitOriginalNewFinalAdmission(actual); var committed = inventory.readOriginalNewFinalAdmissionSource(decision); byte[] finalBytes = actual.exactCanonicalBytes(); @@ -1088,7 +1127,12 @@ void missingOrChangedIndexesAndBarriersNeverRecreateCommittedPostimagesOrExtendT () -> finalOwner() .finalizeOriginalNewOnce( - committed, template, accountOpen, issuerOpen, deadline())) + committed, + template, + accountOpen, + issuerOpen, + controlledCapacity, + deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThat(admin.exists(ascii(key))).isZero(); @@ -1101,7 +1145,12 @@ committed, template, accountOpen, issuerOpen, deadline())) () -> finalOwner() .finalizeOriginalNewOnce( - committed, template, accountOpen, issuerOpen, deadline())) + committed, + template, + accountOpen, + issuerOpen, + controlledCapacity, + deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThat(admin.hget(ascii(accountOpen.key()), ascii("state"))) @@ -1113,7 +1162,12 @@ committed, template, accountOpen, issuerOpen, deadline())) () -> finalOwner() .finalizeOriginalNewOnce( - committed, template, accountOpen, issuerOpen, deadline())) + committed, + template, + accountOpen, + issuerOpen, + controlledCapacity, + deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThatThrownBy( @@ -1151,7 +1205,12 @@ void provisionalFinalCasRefusesMissingIndexesAndChangedBarriersWithoutAdmission( () -> finalOwner() .finalizeOriginalNewOnce( - source, template, accountOpen, issuerOpen, deadline())) + source, + template, + accountOpen, + issuerOpen, + controlledCapacity, + deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThat(admin.exists(ascii(key))).isZero(); @@ -1164,7 +1223,12 @@ source, template, accountOpen, issuerOpen, deadline())) () -> finalOwner() .finalizeOriginalNewOnce( - source, template, accountOpen, issuerOpen, deadline())) + source, + template, + accountOpen, + issuerOpen, + controlledCapacity, + deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThat(admin.hget(ascii(issuerKey(issuerOpen)), ascii("state"))) @@ -1195,7 +1259,8 @@ void retainedRevisionAdvanceAcrossPhysicalReadIsUnavailableAndRetryCanRead() thr var template = credential.template(); var actual = finalOwner() - .finalizeOriginalNewOnce(source, template, accountOpen, issuerOpen, deadline())) { + .finalizeOriginalNewOnce( + source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { inventory.commitOriginalNewFinalAdmission(actual); var assignment = tags.assignmentForTransition(fixture.transitionId()); CanonicalGameplayTenantGameplayTagRepository racingTags = mock(); @@ -1264,7 +1329,8 @@ void changedPersistedSessionCannotRecoverAgainstTheActualCommittedReceipt() thro var template = credential.template(); var actual = finalOwner() - .finalizeOriginalNewOnce(source, template, accountOpen, issuerOpen, deadline())) { + .finalizeOriginalNewOnce( + source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { inventory.commitOriginalNewFinalAdmission(actual); var committed = new CanonicalGameplayBindingInventoryRepository(fixture.dsl()) @@ -1285,7 +1351,12 @@ void changedPersistedSessionCannotRecoverAgainstTheActualCommittedReceipt() thro () -> finalOwner() .finalizeOriginalNewOnce( - committed, template, accountOpen, issuerOpen, deadline())) + committed, + template, + accountOpen, + issuerOpen, + controlledCapacity, + deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThatThrownBy( @@ -1520,14 +1591,15 @@ CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback finalizeOriginalNe CanonicalGameplayOriginalNewAuthenticatedSession.Template template, CanonicalGameplayAccountInitialOpenProof.CurrentOpen account, CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback issuer, + net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution execution, long deadline) { - if (controlledCapacity == null) + if (execution == null) throw new IllegalStateException( "Controlled capacity must be prepared by the native bridge fixture"); - try (var bound = template.bindCapacityExecution(controlledCapacity)) { + try (var bound = template.bindCapacityExecution(execution)) { return new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( ownerClient, catalog, CLOCK, tags) - .finalizeOriginalNewOnce(source, bound, account, issuer, controlledCapacity, deadline); + .finalizeOriginalNewOnce(source, bound, account, issuer, execution, deadline); } } } From 36fa21b138f5cd3b3ff738955645d48a2c42930a Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Wed, 11 Nov 2026 23:28:44 +1300 Subject: [PATCH 17/52] Honor capacity admission deadlines and candidate binding --- .../game-session-service/runtime-and-data.md | 2 +- .../system-architecture-authz-route-matrix.md | 2 +- ...ystem-architecture-authz-route-matrix.yaml | 2 +- ...alAdmissionCompositionIntegrationTest.java | 70 ++++++++-- .../AccountTenantCapacityOwnerTest.java | 36 ++++++ .../capacity/CapacityAdmissionDigestTest.java | 51 ++++++++ .../capacity-admission-v1-vectors.json | 57 ++++---- .../test_capacity_admission_vectors.py | 18 ++- .../client/AccountTenantCapacityClient.java | 23 +++- ...layOriginalNewCapacityExecutionBudget.java | 26 +++- ...playOriginalNewCapacityExecutionOwner.java | 2 + ...yOriginalNewFinalAdmissionCoordinator.java | 2 +- ...alNewFinalAdmissionCompositionFixture.java | 2 +- .../AccountTenantCapacityClientMtlsTest.java | 122 +++++++++++++++++- ...riginalNewCapacityExecutionBudgetTest.java | 85 +++++++++++- 15 files changed, 441 insertions(+), 59 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 8b21d111a2..27d83d891f 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -8,7 +8,7 @@ The seven-key tenant-slot final script atomically serializes `FINAL` against per Positive SQL terminal retention follows actual persistent session/index/atomic-outcome and final-receipt verification. That retained result survives later serving-index retirement. Retained negative replay requires the already-verified immutable SQL CLOSED proof, full original identity, exact persistent Redis CLOSED tombstone, absence of contradictory final SQL receipt/state and a fresh actual current-owner observation. Serving-index absence is never negative evidence. Missing tombstones and closure before SQL proof retention remain indeterminate. Retention-before-cleanup ordering across the earlier crash window is not yet enforced. The existing never-admitted cleanup owner accepts only untouched PREPARED dispatches; cleanup of this already-acknowledged PROVISIONAL final-admission boundary and finalized-usage retirement on real runtime teardown remain separate unfinished Account/owner work. No default owner, receiver, recovery scheduler or source custody is registered by this slice. -The capacity execution owner uses one absolute budget for each complete operation: the earlier incoming gRPC or explicit coordinator deadline, capped at five seconds. Its local SQL connection provider and transaction provider derive from the existing configuration without changing shared datasource settings. Four resource operations are admitted without a waiting queue. Acquisition, SQL and cleanup stay in the admitted worker; cancellation requests the active JDBC statement's cancellation, while a late acquisition cannot execute SQL. Statement close and pool return detach the statement under the same monitor as cancellation. A blocked driver cancellation or acquisition retains its admission slot until it exits. A throwing pool return preserves uncertain connection ownership and retains the slot rather than blindly retrying or claiming disposal. JDBC query timeouts back up cancellation; neither cancellation nor deadline return proves driver termination or an owner outcome. The separate four-slot Redis connector, scoped capacity INSTALL/CLOSE writes and all successive Redis commands consume the same remaining operation budget. INSTALL and the first CLOSE mutation carry that operation's frozen absolute deadline, enforced by Redis time; completed CLOSE replay remains read-only. Other final-admission callers retain their existing connection and command policy. +The capacity execution owner uses one absolute budget for each complete operation: the earlier incoming gRPC or explicit coordinator deadline, capped at five seconds. Its local SQL connection provider and transaction provider derive from the existing configuration without changing shared datasource settings. Four resource operations are admitted without a waiting queue. Acquisition, SQL and cleanup stay in the admitted worker; cancellation requests the active JDBC statement's cancellation, while a late acquisition cannot execute SQL. Statement close and pool return detach the statement under the same monitor as cancellation. A blocked driver cancellation or acquisition retains its admission slot until it exits. A throwing pool return preserves uncertain connection ownership and retains the slot rather than blindly retrying or claiming disposal. The JVM-wide Micrometer gauge `original_new_capacity_sql_release_failure_retained_operations`, exposed through the existing Prometheus actuator path, counts retained operation slots once per affected operation, even if several connections fail to return. A nonzero value identifies lost local admission capacity; four retained slots exhaust this SQL boundary. Investigate the provider failure before a controlled process restart. Restart recovers local admission slots only and supplies no reservation or selected-owner outcome proof. JDBC query timeouts back up cancellation; neither cancellation nor deadline return proves driver termination or an owner outcome. The separate four-slot Redis connector, scoped capacity INSTALL/CLOSE writes and all successive Redis commands consume the same remaining operation budget. INSTALL and the first CLOSE mutation carry that operation's frozen absolute deadline, enforced by Redis time; completed CLOSE replay remains read-only. Other final-admission callers retain their existing connection and command policy. ## Runtime Model diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index be7c5a85d6..3dff3dc935 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -265,7 +265,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus validated typed player context; no circular end-user token prerequisite. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `GetTenantEntitlementsForRuntime` | `internal_workload` | Exactly one complete caller-policy alternative: Game Session mTLS plus current private delegation and typed player context for player admission, or World Management mTLS plus tenant/operation-bound instance-lifecycle context without a player delegation. Constraints within the selected alternative are conjunctive; no `control-ui` or Logging and Admin caller; not edge exposed. The read assesses eligibility only and never commits capacity. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `CommitTenantCapacityAdmission` | `internal_workload` | **Target; not currently routable.** Exactly one complete caller-policy alternative is required: Game Session presents its own exact Game Session caller workload mTLS identity to Account with typed `PlayerExecutionContext` and the live player-binding checks, or World Management presents its own exact World Management caller workload mTLS identity to Account with tenant/operation-bound instance-lifecycle context and the live lifecycle checks. Account remains the receiving authority; only those alternatives may call its exact receiving mTLS boundary. The request binds `tenantId`, stable `requestId`/`admissionId`, fresh `admissionAttemptId`, current `capacityRearmFence`, the complete Account evidence bundle including its applicable `authorityTuple`, `expected_billing_evidence`, and all `outboxCheckpoints[]`, plus a bounded `capacityDelta` whose protobuf field is `optional int64` encoded as a varint and whose canonical JSON/proto-JSON spelling is `capacityDelta` encoded as a base-10 decimal string. The machine contract explicitly distinguishes omitted (`absent`) from present zero (`present_zero`), rejects JSON `null` and boolean zero, and publishes both transport-specific golden vectors. The caller-supplied `capacity_rearm_fence` is the attempt-bound fence, while Account compares the live `capacity_admission_fence` at final commit alongside the applicable generation guards. It also carries versioned `mutationDigest` over the attempt identity, fence, and complete payload. The first attempt binds those fields without a rearm; an exact retry replays, while a changed field requires the Account-owned committed rearm CAS that advances the fence and binds the fresh attempt. Any change without that CAS is an idempotency conflict before reservation, usage, activation, or routing mutation. Account performs the final fenced reservation commit and returns the committed evidence or a canonical stale/quota/unavailable outcome; until this route is implemented, capacity-changing operations fail closed. | -| Game Session Service | `ReadOriginalNewCapacityExecution` | `internal_workload` | **Unregistered; not currently routable.** Exact same-namespace Account mTLS workload, with no user token or ambient delegated context. Bounded read-only original attempt and reservation selector. Returns complete exact binding and immutable proven final-session/SQL receipt evidence or an irreversibly closed original attempt, together with a fresh owner-fence observation distinct from the captured original fence. Missing, interrupted, ambiguous, or contradictory execution evidence is `INDETERMINATE`; `UNAVAILABLE` means the read cannot produce an observation. Neither outcome proves non-execution. See [Game Session API Contracts](./microservices/game-session-service/api-contracts.md#original-new-capacity-execution-read). | +| Game Session Service | `ReadOriginalNewCapacityExecution` | `internal_workload` | **Unregistered; not currently routable.** Exact same-namespace Account mTLS workload, with no user token or ambient delegated context. Bounded read-only original attempt and reservation selector. Returns complete exact binding and immutable proven final-session/SQL receipt evidence or an irreversibly closed original attempt, together with a fresh owner-fence observation distinct from the captured original fence. Missing, interrupted, ambiguous, or contradictory execution evidence returns RPC `UNAVAILABLE`; Account recovery records that failed read as `INDETERMINATE` and preserves the hold. Absence or expiry never proves non-execution. See [Game Session API Contracts](./microservices/game-session-service/api-contracts.md#original-new-capacity-execution-read). | | Account Service | `GetTenantEntitlementsTenant` | `billing_safe_tenant` | `tenantAdmin` (tenant-scoped); live `current_operator_roles` and caller-bound membership checks | | Account Service | `GetTenantEntitlementsCrossTenantSupportSafe` | `cross_tenant_support_safe` | `support` without `privileged_control`; `platformAdmin` requires `privileged_control` | | Account Service | `GetSubscriptionTenantHighLevel` | `billing_safe_tenant` | `tenantAdmin` (tenant-scoped); live `current_operator_roles` and caller-bound membership checks under [Subscription Management](./microservices/account-service/subscription-management.md) | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 511a7754b0..aea234cfae 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -3205,7 +3205,7 @@ routes: implementation_status: known_drift: - unregistered_bounded_Account_only_read_and_client_prepared; deployed_PKI_source_custody_and_registration_unqualified - - missing_interrupted_or_ambiguous_evidence_is_INDETERMINATE; absence_or_expiry_never_proves_no_execution + - missing_interrupted_or_ambiguous_evidence_returns_RPC_UNAVAILABLE_and_Account_recovery_records_INDETERMINATE; absence_or_expiry_never_proves_no_execution - service: account-service route: GetTenantEntitlementsTenant scope: tenant diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 413649446f..c30d5971b3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -180,7 +180,8 @@ void retainedActualCasEvidenceStillFinalizesCapacityAfterControlledServingRetire throws Exception { try (Session session = session()) { var admitted = session.complete(); - var reservation = session.capacityClient.commit(session.capacityRequest); + var reservation = + session.capacityClient.commit(session.capacityRequest, CLOCK.millis() + 5_000L); var before = session.capacityRead.readExact( session.capacityRequest, reservation, CLOCK.instant().plusSeconds(5)); @@ -270,6 +271,43 @@ void missingCapacityInputRefusesBeforeAnyFinalSessionOrReservationMutation() thr } } + @Test + void changedCatalogRevisionRefusesBeforeAccountCapacityCommitment() throws Exception { + try (Session session = session()) { + var original = session.capacityRequest; + var target = (Map) original.evidence().fields().get("target"); + long revision = Long.parseLong((String) target.get("catalogRevision")); + var changed = session.retainControlledEvaluation(true, null, revision + 1L); + changed.requireStructurallyValid(); + assertThat(changed.context()).isEqualTo(original.context()); + assertThat(changed.evidence().fields().get("authorityTuple")) + .isEqualTo(original.evidence().fields().get("authorityTuple")); + String capacityBefore = session.capacityImage(); + var gsBefore = session.gs.capacityStateImage(); + byte[] candidate = session.gs.physicalSession(); + assertThatThrownBy( + () -> + session.gs.complete( + session.client, + session.jwks, + session.jwt, + System.currentTimeMillis() + 10_000L, + session.capacityClient, + changed)) + .isInstanceOf(IllegalStateException.class) + .hasCauseInstanceOf(IllegalStateException.class) + .hasRootCauseMessage("Original NEW capacity execution is indeterminate"); + assertThat(session.capacityImage()).isEqualTo(capacityBefore); + assertThat(session.gs.capacityStateImage()).isEqualTo(gsBefore); + assertThat(session.gs.physicalSession()).containsExactly(candidate); + assertThat(session.gs.finalReadCalls()).isZero(); + assertThat( + session.dsl.fetchCount( + org.jooq.impl.DSL.table("account_tenant_capacity_reservations"))) + .isZero(); + } + } + @Test void mismatchedCapacityRequestRefusesBeforeAccountCommit() throws Exception { try (Session session = session()) { @@ -438,7 +476,9 @@ void freshRetainedNonCreatingEvaluationIsPolicyDeniedWithoutOwnerMutation() thro String before = session.capacityImage() + session.durableImage(); for (int attempt = 0; attempt < 2; attempt++) { StatusRuntimeException failure = - assertThrows(StatusRuntimeException.class, () -> session.capacityClient.commit(denied)); + assertThrows( + StatusRuntimeException.class, + () -> session.capacityClient.commit(denied, CLOCK.millis() + 5_000L)); assertCapacityFailure(failure, Status.Code.RESOURCE_EXHAUSTED, "TENANT_BILLING_BLOCKED"); assertThat(session.capacityImage() + session.durableImage()).isEqualTo(before); assertProvisionalUnchanged(session, candidate); @@ -472,7 +512,9 @@ private static void assertCapacityRefusalWithoutMutation( assertThat(candidate).isNotNull(); String before = session.capacityImage() + session.durableImage(); assertCapacityFailure( - assertThrows(StatusRuntimeException.class, () -> session.capacityClient.commit(request)), + assertThrows( + StatusRuntimeException.class, + () -> session.capacityClient.commit(request, CLOCK.millis() + 5_000L)), status, code); assertThat(session.capacityImage() + session.durableImage()).isEqualTo(before); @@ -482,15 +524,18 @@ private static void assertCapacityRefusalWithoutMutation( @Test void retainedOriginalReplaysBeforeChangedNonCreatingEvidenceCanBecomeADenial() throws Exception { try (Session session = session()) { - var first = session.capacityClient.commit(session.capacityRequest); + var first = session.capacityClient.commit(session.capacityRequest, CLOCK.millis() + 5_000L); var changed = session.retainControlledEvaluation(false, null); byte[] candidate = session.gs.physicalSession(); assertThat(candidate).isNotNull(); String before = session.capacityImage() + session.durableImage(); StatusRuntimeException failure = - assertThrows(StatusRuntimeException.class, () -> session.capacityClient.commit(changed)); + assertThrows( + StatusRuntimeException.class, + () -> session.capacityClient.commit(changed, CLOCK.millis() + 5_000L)); assertCapacityFailure(failure, Status.Code.ALREADY_EXISTS, "IDEMPOTENCY_CONFLICT"); - assertThat(session.capacityClient.commit(session.capacityRequest)).isEqualTo(first); + assertThat(session.capacityClient.commit(session.capacityRequest, CLOCK.millis() + 5_000L)) + .isEqualTo(first); assertThat(session.capacityImage() + session.durableImage()).isEqualTo(before); assertProvisionalUnchanged(session, candidate); } @@ -821,9 +866,16 @@ private Genesis genesis() { } /** Controlled entitlement facts, real current caller/scope and actual immutable retention. */ - @SuppressWarnings("unchecked") private TenantCapacityAdmission.Request retainControlledEvaluation( boolean creationAllowed, @org.jspecify.annotations.Nullable String quota) { + return retainControlledEvaluation(creationAllowed, quota, null); + } + + @SuppressWarnings("unchecked") + private TenantCapacityAdmission.Request retainControlledEvaluation( + boolean creationAllowed, + @org.jspecify.annotations.Nullable String quota, + @org.jspecify.annotations.Nullable Long catalogRevision) { var original = capacityRequest; var parsed = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( @@ -851,13 +903,15 @@ private TenantCapacityAdmission.Request retainControlledEvaluation( quotas.put(original.context().owner().quota(), quota); facts.put("quotas", quotas); } + var target = new LinkedHashMap<>((Map) fields.get("target")); + if (catalogRevision != null) target.put("catalogRevision", Long.toString(catalogRevision)); var evaluation = RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( original.identity().requestId(), original.evidence().callerWorkload(), (String) fields.get("verifiedConnectScopeId"), parsed.membershipSource(), - (Map) fields.get("target"), + target, facts, (Map) fields.get("sourceReferences"), CLOCK.instant()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index f85064e8f8..baa3b9fd7b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -29,6 +29,7 @@ import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import org.jooq.ConnectionRunnable; import org.jooq.DSLContext; @@ -40,6 +41,7 @@ import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.SimpleTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; /** * Controlled ordering/denial only. Physical transaction and positive current-source proof are @@ -52,6 +54,40 @@ void clear() { TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); } + @Test + void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + for (var vector : corpus.path("rejectedUsage")) { + DSLContext dsl = mock(DSLContext.class); + Record usage = mock(Record.class); + when(usage.get("held_units", Long.class)) + .thenReturn(TenantCapacityAdmission.decimal(vector.path("held").asText())); + when(usage.get("used_units", Long.class)) + .thenReturn(TenantCapacityAdmission.decimal(vector.path("usage").asText())); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(usage); + var request = + CapacityAdmissionTestFixture.worldRequest( + TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText())); + request.requireCommittable(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + new AccountTenantCapacityRepository(dsl) + .create(request, request.evidence().expiresAt())) + .as(vector.path("name").asText()) + .hasMessage(vector.path("expected").asText()); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + } + } + @Test void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index 928f4e53f5..79c87dba01 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -72,6 +72,57 @@ void sharedCorpusFixesCompleteEvidenceAndAbsentZeroPositiveBoundaryPreimages() t .isNotEqualTo(CapacityAdmissionTestFixture.worldRequest(0L).mutationDigest()); } + @Test + void sharedRejectedEvidenceAndRequestsReachCanonicalValidators() throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + for (var vector : corpus.path("rejectedEvidence")) { + byte[] bytes = + Base64.getDecoder().decode(vector.path("canonicalAccountEvidenceBase64").asText()); + assertThatThrownBy(() -> Evidence.parse(bytes, Owner.WORLD_MANAGEMENT)) + .as(vector.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + for (var vector : corpus.path("rejectedRequests")) { + Request base = CapacityAdmissionTestFixture.worldRequest(17L); + Shape requested = base.requestedShape(); + if (vector.has("requestedShape")) { + var shape = vector.path("requestedShape"); + requested = + new Shape( + TenantCapacityAdmission.decimal(shape.get(0).asText()), + TenantCapacityAdmission.decimal(shape.get(1).asText()), + TenantCapacityAdmission.decimal(shape.get(2).asText())); + } + Long delta = + vector.has("capacityDelta") + ? (vector.path("capacityDelta").isNull() + ? null + : TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText())) + : base.capacityDelta(); + Request rejected = + new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + base.operation(), + base.priorShape(), + requested, + base.evidence(), + delta, + null) + .withDigest(); + assertThatThrownBy(rejected::requireStructurallyValid) + .as(vector.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + @Test void nonCreatingEvidenceIsValidContentButCannotAuthorizeExecution() { Request denied = CapacityAdmissionTestFixture.playerRequest(false); diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json index 7e1632b65d..6d63b4d240 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json +++ b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json @@ -1,6 +1,6 @@ { "schema": "capacity-admission/1", - "validation": "UNRUN: artifact authoring only; not source or runtime proof", + "validation": "Encoding vectors and separate native request/Account usage rejection fixtures; not source or runtime authority", "request": { "tenantId": "22222222-2222-4222-8222-222222222222", "requestId": "33333333-3333-4333-8333-333333333333", @@ -138,26 +138,32 @@ "capacityDelta": 0.0, "expected": "REJECT_BEFORE_COMMIT", "acceptedDigest": null - }, + } + ], + "rejectedEvidence": [ { - "name": "delta-10", - "capacityDelta": null, + "name": "changed-cutoff-without-checkpoint", "expected": "REJECT_BEFORE_COMMIT", - "acceptedDigest": null + "acceptedDigest": null, + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5VHVwbGUiOnsidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiI1In0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiNCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiI1IiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMTEifX19LCJidW5kbGVWZXJzaW9uIjoiMSIsImNhbGxlcldvcmtsb2FkIjoic3BpZmZlOi8vZmlyZW11ZC9ucy9wcm9kL3NhL3dvcmxkLW1hbmFnZW1lbnQtc2VydmljZSIsImVudGl0bGVtZW50VmVyc2lvbiI6IjciLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDJUMDA6MDA6MDBaIiwiZXZhbHVhdGlvbklkZW50aXR5Ijoic2hhMjU2OmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLCJnYW1lcGxheUF2YWlsYWJsZSI6dHJ1ZSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMyIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInNvdXJjZUV2ZW50RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzb3VyY2VFdmVudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIn1dLCJwcm92aXNpb25pbmdTdGF0dXMiOm51bGwsInF1b3RhcyI6eyJtYXhBY3RpdmVTZXNzaW9ucyI6IjEwMCIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiOTIyMzM3MjAzNjg1NDc3NTgwNyIsIm1heFN0b3JhZ2VCeXRlcyI6IjEwNDg1NzYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwic2NoZW1hIjoiYWNjb3VudC1hdXRoLWV2aWRlbmNlLWJ1bmRsZS92MSIsInNuYXBzaG90SWRlbnRpdHkiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInNvdXJjZUtpbmQiOiJQQUlEX0hPU1RJTkciLCJzdWJzY3JpcHRpb25TdGF0dXMiOiJhY3RpdmUiLCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjoiNSIsInRlbmFudEJpbGxpbmdTZXF1ZW5jZSI6IjExIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YXJpYW50IjoiVEVOQU5UX09QRVJBVElPTiJ9" }, { - "name": "usage-addition-overflow", - "usage": "9223372036854775807", - "held": "0", - "capacityDelta": "1", + "name": "noncanonical-evidence-whitespace", "expected": "REJECT_BEFORE_COMMIT", - "acceptedDigest": null + "acceptedDigest": null, + "canonicalAccountEvidenceBase64": "IHsiYWxsb3dOZXdHYW1lcGxheUJpbmRpbmdzIjp0cnVlLCJhbGxvd05ld0luc3RhbmNlU3RhcnRzIjp0cnVlLCJhbGxvd1B1YmxpY0pvaW4iOnRydWUsImF1dGhvcml0eUF2YWlsYWJpbGl0eSI6IkFWQUlMQUJMRSIsImF1dGhvcml0eVR1cGxlIjp7InRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjoiNSJ9LCJ0ZW5hbnRCaWxsaW5nQ3V0b2ZmIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6eyJvdXRib3hTZXF1ZW5jZSI6IjMiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjoiNSIsInRlbmFudEJpbGxpbmdTZXF1ZW5jZSI6IjExIn19fSwiYnVuZGxlVmVyc2lvbiI6IjEiLCJjYWxsZXJXb3JrbG9hZCI6InNwaWZmZTovL2ZpcmVtdWQvbnMvcHJvZC9zYS93b3JsZC1tYW5hZ2VtZW50LXNlcnZpY2UiLCJlbnRpdGxlbWVudFZlcnNpb24iOiI3IiwiZXZhbHVhdGVkQXQiOiIyMDI2LTExLTAyVDAwOjAwOjAwWiIsImV2YWx1YXRpb25JZGVudGl0eSI6InNoYTI1NjpiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwiZ2FtZXBsYXlBdmFpbGFibGUiOnRydWUsIm91dGJveENoZWNrcG9pbnRzIjpbeyJvdXRib3hTZXF1ZW5jZSI6IjMiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJzb3VyY2VFdmVudERpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwic291cmNlRXZlbnRJZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTExMTExMTExMTExMSJ9XSwicHJvdmlzaW9uaW5nU3RhdHVzIjpudWxsLCJxdW90YXMiOnsibWF4QWN0aXZlU2Vzc2lvbnMiOiIxMDAiLCJtYXhDb25jdXJyZW50R2FtZUluc3RhbmNlcyI6IjkyMjMzNzIwMzY4NTQ3NzU4MDciLCJtYXhTdG9yYWdlQnl0ZXMiOiIxMDQ4NTc2In0sInJlcXVlc3RJZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsInNjaGVtYSI6ImFjY291bnQtYXV0aC1ldmlkZW5jZS1idW5kbGUvdjEiLCJzbmFwc2hvdElkZW50aXR5Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzb3VyY2VLaW5kIjoiUEFJRF9IT1NUSU5HIiwic3Vic2NyaXB0aW9uU3RhdHVzIjoiYWN0aXZlIiwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjUiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxMSIsInRlbmFudElkIjoiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwidmFyaWFudCI6IlRFTkFOVF9PUEVSQVRJT04ifQ==" }, { - "name": "held-addition-overflow", - "usage": "0", - "held": "9223372036854775807", - "capacityDelta": "1", + "name": "duplicate-evidence-member", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null, + "canonicalAccountEvidenceBase64": "eyJidW5kbGVWZXJzaW9uIjoiMSIsImFsbG93TmV3R2FtZXBsYXlCaW5kaW5ncyI6dHJ1ZSwiYWxsb3dOZXdJbnN0YW5jZVN0YXJ0cyI6dHJ1ZSwiYWxsb3dQdWJsaWNKb2luIjp0cnVlLCJhdXRob3JpdHlBdmFpbGFiaWxpdHkiOiJBVkFJTEFCTEUiLCJhdXRob3JpdHlUdXBsZSI6eyJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6IjUifSwidGVuYW50QmlsbGluZ0N1dG9mZiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOnsib3V0Ym94U2VxdWVuY2UiOiIzIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjUiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxMSJ9fX0sImJ1bmRsZVZlcnNpb24iOiIxIiwiY2FsbGVyV29ya2xvYWQiOiJzcGlmZmU6Ly9maXJlbXVkL25zL3Byb2Qvc2Evd29ybGQtbWFuYWdlbWVudC1zZXJ2aWNlIiwiZW50aXRsZW1lbnRWZXJzaW9uIjoiNyIsImV2YWx1YXRlZEF0IjoiMjAyNi0xMS0wMlQwMDowMDowMFoiLCJldmFsdWF0aW9uSWRlbnRpdHkiOiJzaGEyNTY6YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsImdhbWVwbGF5QXZhaWxhYmxlIjp0cnVlLCJvdXRib3hDaGVja3BvaW50cyI6W3sib3V0Ym94U2VxdWVuY2UiOiIzIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwic291cmNlRXZlbnREaWdlc3QiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInNvdXJjZUV2ZW50SWQiOiIxMTExMTExMS0xMTExLTQxMTEtODExMS0xMTExMTExMTExMTEifV0sInByb3Zpc2lvbmluZ1N0YXR1cyI6bnVsbCwicXVvdGFzIjp7Im1heEFjdGl2ZVNlc3Npb25zIjoiMTAwIiwibWF4Q29uY3VycmVudEdhbWVJbnN0YW5jZXMiOiI5MjIzMzcyMDM2ODU0Nzc1ODA3IiwibWF4U3RvcmFnZUJ5dGVzIjoiMTA0ODU3NiJ9LCJyZXF1ZXN0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJzY2hlbWEiOiJhY2NvdW50LWF1dGgtZXZpZGVuY2UtYnVuZGxlL3YxIiwic25hcHNob3RJZGVudGl0eSI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwic291cmNlS2luZCI6IlBBSURfSE9TVElORyIsInN1YnNjcmlwdGlvblN0YXR1cyI6ImFjdGl2ZSIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiI1IiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMTEiLCJ0ZW5hbnRJZCI6IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInZhcmlhbnQiOiJURU5BTlRfT1BFUkFUSU9OIn0=" + } + ], + "rejectedRequests": [ + { + "name": "delta-10", + "capacityDelta": null, "expected": "REJECT_BEFORE_COMMIT", "acceptedDigest": null }, @@ -170,20 +176,23 @@ ], "expected": "REJECT_BEFORE_COMMIT", "acceptedDigest": null - }, - { - "name": "changed-cutoff-without-checkpoint", - "expected": "REJECT_BEFORE_COMMIT", - "acceptedDigest": null - }, + } + ], + "rejectedUsage": [ { - "name": "noncanonical-evidence-whitespace", - "expected": "REJECT_BEFORE_COMMIT", + "name": "usage-addition-overflow", + "usage": "9223372036854775807", + "held": "0", + "capacityDelta": "1", + "expected": "CAPACITY_QUOTA_EXCEEDED", "acceptedDigest": null }, { - "name": "duplicate-evidence-member", - "expected": "REJECT_BEFORE_COMMIT", + "name": "held-addition-overflow", + "usage": "0", + "held": "9223372036854775807", + "capacityDelta": "1", + "expected": "CAPACITY_QUOTA_EXCEEDED", "acceptedDigest": null } ] diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py index 52e6bcf179..b777da33ee 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -114,15 +114,19 @@ def test_shared_golden_preimages_and_digests(self): digests.append(digest) self.assertNotEqual(digests[0], digests[1]) - def test_rejected_delta_candidates_and_checked_addition(self): + def test_rejected_decimal_candidates(self): corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) for candidate in corpus["rejected"]: - if candidate["name"].startswith("delta-"): - with self.subTest(candidate["name"]), self.assertRaises(ValueError): - decimal(candidate["capacityDelta"]) - if "usage" in candidate: - occupied = decimal(candidate["usage"]) + decimal(candidate["held"]) + decimal(candidate["capacityDelta"]) - self.assertGreater(occupied, MAX) + with self.subTest(candidate["name"]), self.assertRaises(ValueError): + decimal(candidate["capacityDelta"]) + + def test_rejected_evidence_candidates(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + for candidate in corpus["rejectedEvidence"]: + with self.subTest(candidate["name"]), self.assertRaises(ValueError): + evidence(candidate["canonicalAccountEvidenceBase64"]) + # Shape/absence and usage expectations are separate from this encoding corpus: + # CapacityAdmissionDigestTest and AccountTenantCapacityOwnerTest invoke their real owners. if __name__ == "__main__": diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index f89bd69d1e..fd219bb4ec 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamesession.client; +import io.grpc.Context; +import io.grpc.Deadline; import io.grpc.ManagedChannel; import io.grpc.StatusRuntimeException; import java.io.IOException; @@ -25,6 +27,7 @@ public final class AccountTenantCapacityClient extends AbstractReloadingBlockingGrpcClient { private final String namespace; + private final Clock clock; private final String expectedPeer; public AccountTenantCapacityClient( @@ -42,7 +45,7 @@ public AccountTenantCapacityClient( throw new IllegalArgumentException("Namespace required"); this.namespace = namespace; this.expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; - Objects.requireNonNull(clock); + this.clock = Objects.requireNonNull(clock); } public void init() throws IOException { @@ -52,18 +55,28 @@ public void init() throws IOException { /** * The caller must obtain its typed context from current owned player state, not text/metadata. - * Retries retain this exact request. A timeout is indeterminate and never allocates another ID. + * Retries retain this exact request. The Account call consumes the remaining absolute admission + * budget, capped at five seconds and the incoming deadline. A timeout is indeterminate and never + * allocates another ID. */ - public Result commit(Request request) { + public Result commit(Request request, long absoluteDeadlineMillis) { requireNoAmbientSql("Capacity commitment requires no ambient SQL"); request.requireStructurallyValid(); if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION || !namespace.equals(request.targetNamespace())) throw new IllegalArgumentException("Exact Game Session context required"); + long remainingMillis = Math.subtractExact(absoluteDeadlineMillis, clock.millis()); + Deadline deadline = + Deadline.after( + Math.min( + TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS), + remainingMillis), + TimeUnit.MILLISECONDS); + Deadline incoming = Context.current().getDeadline(); + if (incoming != null) deadline = deadline.minimum(incoming); var stub = requireInitializedStub("Account capacity unavailable") - .withDeadlineAfter( - TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withDeadline(deadline) .withMaxOutboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES) .withMaxInboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_RESPONSE_WIRE_BYTES); try { 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 30ba2a2ecd..641725ccd5 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 @@ -2,6 +2,8 @@ import io.grpc.Context; import io.grpc.Deadline; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.Metrics; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -32,7 +34,19 @@ final class CanonicalGameplayOriginalNewCapacityExecutionBudget { static final int MAX_IN_FLIGHT_OPERATIONS = 4; private static final Semaphore OPERATIONS = new Semaphore(MAX_IN_FLIGHT_OPERATIONS); + private static final AtomicInteger RELEASE_FAILURE_RETAINED_OPERATIONS = new AtomicInteger(); + + static { + Gauge.builder( + "original_new_capacity_sql_release_failure_retained_operations", + RELEASE_FAILURE_RETAINED_OPERATIONS, + AtomicInteger::get) + .description("Capacity SQL operation permits retained after an uncertain provider release") + .register(Metrics.globalRegistry); + } + private final ThreadFactory cancellationThreads; + private final AtomicBoolean releaseFailureRecorded = new AtomicBoolean(); private final AtomicInteger outstandingConnections = new AtomicInteger(); private final Context caller; private final Clock clock; @@ -122,7 +136,7 @@ static T run( budget.releaseOutstandingConnections(); } catch (RuntimeException | Error cleanupFailure) { if (failure == null) failure = cleanupFailure; - else failure.addSuppressed(cleanupFailure); + else if (failure != cleanupFailure) failure.addSuppressed(cleanupFailure); } budget.caller.detach(previous); synchronized (budget.lifecycle) { @@ -289,7 +303,7 @@ private void releaseOutstandingConnections() { connection.release(); } catch (RuntimeException cleanupFailure) { if (failure == null) failure = cleanupFailure; - else failure.addSuppressed(cleanupFailure); + else if (failure != cleanupFailure) failure.addSuppressed(cleanupFailure); } } if (failure != null) throw failure; @@ -398,7 +412,13 @@ void release() { } // A throwing provider release has uncertain ownership. Do not retry it blindly or free // the resource permit as though that connection were known to have returned to its pool. - provider.release(raw); + try { + provider.release(raw); + } catch (RuntimeException | Error uncertainReturn) { + if (releaseFailureRecorded.compareAndSet(false, true)) + RELEASE_FAILURE_RETAINED_OPERATIONS.incrementAndGet(); + throw uncertainReturn; + } returned = true; if (connections.remove(proxy) != null) outstandingConnections.decrementAndGet(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index a0d53d56bc..fb560a41de 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -139,6 +139,8 @@ CurrentOwner requireRequestBinding( || !binding.characterId().equals(player.characterId()) || !binding.sessionId().equals(player.sessionId().toString()) || !target.realmId().equals(player.realmId()) + || !(request.evidence().fields().get("target") instanceof Map evidenceTarget) + || !Long.toString(target.catalogRevision()).equals(evidenceTarget.get("catalogRevision")) || !player .requestId() .toString() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index 80c0888016..e8041f4288 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -174,7 +174,7 @@ FinalAdmissionResult completeOriginalNew( if (!selectedOwner.equals( capacityExecution.requireRequestBinding( source, capacityRequest, absoluteDeadlineMillis))) throw unavailable(); - var reservation = capacityClient.commit(capacityRequest); + var reservation = capacityClient.commit(capacityRequest, absoluteDeadlineMillis); var execution = capacityExecution.bind( source, capacityRequest, reservation, absoluteDeadlineMillis, selectedOwner); 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 beacb02552..0c2ba1b9d9 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 @@ -703,7 +703,7 @@ public OwnerMovementFault commitThenMoveSelectedOwnerForFault( new CanonicalGameplayOriginalNewCapacityExecutionOwner( binding.dsl(), coordination, scripts, CLOCK, tags); var selected = executionOwner.requireRequestBinding(source, request, deadline); - var result = client.commit(request); + var result = client.commit(request, deadline); var identity = source.candidate().bindingIdentity(); if (binding .dsl() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index db8e1682fb..d13d56873b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.Any; +import io.grpc.Context; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; @@ -20,8 +21,11 @@ import java.time.ZoneOffset; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; @@ -66,8 +70,8 @@ void exactAccountPeerReceivesCompleteRequestAndExactRetryKeepsReservation() thro try (var client = client(server)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(); - var first = client.commit(request); - assertThat(client.commit(request)).isEqualTo(first); + var first = client.commit(request, deadline()); + assertThat(client.commit(request, deadline())).isEqualTo(first); assertThat(first.identity()).isEqualTo(request.identity()); assertThat(calls).hasValue(2); } finally { @@ -83,7 +87,7 @@ void nonCreatingEvidenceReachesControlledAccountAndReturnsStructuredPolicyDenial try (var client = client(server)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(false); - assertThatThrownBy(() -> client.commit(request)) + assertThatThrownBy(() -> client.commit(request, deadline())) .isInstanceOf(StatusRuntimeException.class) .satisfies( failure -> { @@ -110,7 +114,8 @@ void wrongAccountPeerIsRejectedBeforeRequestBodyRelease() throws Exception { Server server = server("wrong", calls, false); try (var client = client(server)) { client.init(); - assertThatThrownBy(() -> client.commit(CapacityAdmissionTestFixture.playerRequest())) + assertThatThrownBy( + () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) .isInstanceOf(StatusRuntimeException.class); assertThat(calls).hasValue(0); } finally { @@ -124,13 +129,106 @@ void changedResponseFenceCannotSubstituteForOriginalCommitment() throws Exceptio Server server = server("account", calls, true); try (var client = client(server)) { client.init(); - assertThatThrownBy(() -> client.commit(CapacityAdmissionTestFixture.playerRequest())) + assertThatThrownBy( + () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) .isInstanceOf(IllegalArgumentException.class); } finally { stop(server); } } + @Test + void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() + throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicLong observedNanos = new AtomicLong(); + AtomicBoolean respond = new AtomicBoolean(true); + Server server = server("account", calls, false, observedNanos, respond); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var first = client.commit(request, deadline()); + respond.set(false); + long started = System.nanoTime(); + assertThatThrownBy( + () -> client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 200L)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); + assertThat(observedNanos.get()) + .isPositive() + .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(200)); + respond.set(true); + assertThat(client.commit(request, deadline())).isEqualTo(first); + assertThat(calls).hasValue(3); + } finally { + stop(server); + } + } + + @Test + void incomingDeadlineAndFiveSecondMaximumAlsoCapTheAccountCall() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicLong observedNanos = new AtomicLong(); + AtomicBoolean respond = new AtomicBoolean(true); + Server server = server("account", calls, false, observedNanos, respond); + var scheduler = Executors.newSingleThreadScheduledExecutor(); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 60_000L); + assertThat(observedNanos.get()).isPositive().isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(5)); + respond.set(false); + long started = System.nanoTime(); + assertThatThrownBy( + () -> + Context.current() + .withDeadlineAfter(200, TimeUnit.MILLISECONDS, scheduler) + .call(() -> client.commit(request, deadline()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); + assertThat(observedNanos.get()) + .isPositive() + .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(200)); + } finally { + scheduler.shutdownNow(); + stop(server); + } + } + + @Test + void expiredExplicitBudgetSendsNoAccountRequest() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("account", calls, false); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> + client.commit( + CapacityAdmissionTestFixture.playerRequest(), + CapacityAdmissionTestFixture.NOW.toEpochMilli() - 1L)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + + private static long deadline() { + return CapacityAdmissionTestFixture.NOW.toEpochMilli() + 5_000L; + } + private static AccountTenantCapacityClient client(Server server) throws Exception { var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + server.getPort()); @@ -144,6 +242,16 @@ private static AccountTenantCapacityClient client(Server server) throws Exceptio private static Server server(String identity, AtomicInteger calls, boolean wrongFence) throws Exception { + return server(identity, calls, wrongFence, new AtomicLong(), new AtomicBoolean(true)); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond) + throws Exception { UUID reservationId = UUID.randomUUID(); var service = new AccountServiceGrpc.AccountServiceImplBase() { @@ -152,6 +260,10 @@ public void commitTenantCapacityAdmission( CommitTenantCapacityAdmissionRequest wire, StreamObserver observer) { calls.incrementAndGet(); + observedNanos.set( + Objects.requireNonNull(Context.current().getDeadline()) + .timeRemaining(TimeUnit.NANOSECONDS)); + if (!respond.get()) return; assertThat(GrpcPeerIdentity.current().uri()) .isEqualTo("spiffe://firemud/ns/prod/sa/game-session-service"); var request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); 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 648b279407..703cb54f9f 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 @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; @@ -13,6 +14,8 @@ import io.grpc.Context; import io.lettuce.core.RedisClient; +import io.micrometer.core.instrument.Metrics; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.sql.Connection; import java.sql.PreparedStatement; import java.time.Clock; @@ -22,6 +25,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -108,7 +112,9 @@ void activeStatementCancellationFinishesBeforePoolReturn() throws Exception { when(provider.acquire()).thenReturn(connection); CountDownLatch executing = new CountDownLatch(1), finishExecution = new CountDownLatch(1); CountDownLatch cancelling = new CountDownLatch(1), finishCancellation = new CountDownLatch(1); + CountDownLatch cancelled = new CountDownLatch(1), released = new CountDownLatch(1); AtomicBoolean returned = new AtomicBoolean(); + AtomicBoolean orderingViolation = new AtomicBoolean(); when(statement.execute()) .thenAnswer( invocation -> { @@ -118,10 +124,11 @@ void activeStatementCancellationFinishesBeforePoolReturn() throws Exception { }); doAnswer( invocation -> { - assertThat(returned).isFalse(); + if (returned.get()) orderingViolation.set(true); cancelling.countDown(); awaitUninterruptibly(finishCancellation); - assertThat(returned).isFalse(); + if (returned.get()) orderingViolation.set(true); + cancelled.countDown(); return null; }) .when(statement) @@ -129,6 +136,8 @@ void activeStatementCancellationFinishesBeforePoolReturn() throws Exception { doAnswer( invocation -> { returned.set(true); + if (cancelled.getCount() != 0) orderingViolation.set(true); + released.countDown(); return null; }) .when(provider) @@ -148,6 +157,9 @@ void activeStatementCancellationFinishesBeforePoolReturn() throws Exception { finishExecution.countDown(); verify(provider, never()).release(connection); finishCancellation.countDown(); + assertThat(cancelled.await(2, TimeUnit.SECONDS)).isTrue(); + assertThat(released.await(2, TimeUnit.SECONDS)).isTrue(); + assertThat(orderingViolation).isFalse(); verify(provider, timeout(2000)).release(connection); verify(statement).cancel(); verify(statement).setQueryTimeout(anyInt()); @@ -157,6 +169,75 @@ void activeStatementCancellationFinishesBeforePoolReturn() throws Exception { } } + @Test + void uncertainProviderReleaseRetainsOnePermitAndExposesItThroughMicrometer() { + ConnectionProvider provider = mock(); + Connection first = mock(), second = mock(); + when(provider.acquire()).thenReturn(first, second); + doThrow(new IllegalStateException("Controlled uncertain pool return")) + .when(provider) + .release(org.mockito.ArgumentMatchers.any(Connection.class)); + AtomicReference captured = + new AtomicReference<>(); + var registry = new SimpleMeterRegistry(); + try { + Metrics.addRegistry(registry); + AtomicInteger retained = + (AtomicInteger) + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, + "RELEASE_FAILURE_RETAINED_OPERATIONS"); + Semaphore permits = + (Semaphore) + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, "OPERATIONS"); + assertThat(retained).isNotNull(); + assertThat(permits).isNotNull(); + int before = retained.get(); + int available = permits.availablePermits(); + try { + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + CLOCK, + Long.MAX_VALUE, + budget -> { + captured.set(budget); + var scoped = + budget.sql(source(provider)).configuration().connectionProvider(); + scoped.acquire(); + scoped.acquire(); + return true; + })) + .isInstanceOf(IllegalStateException.class); + assertThat( + registry + .get("original_new_capacity_sql_release_failure_retained_operations") + .gauge() + .value()) + .isEqualTo(before + 1); + assertThat(permits.availablePermits()).isEqualTo(available - 1); + assertThat(ReflectionTestUtils.getField(captured.get(), "released")).isEqualTo(false); + assertThat( + (AtomicInteger) + ReflectionTestUtils.getField(captured.get(), "outstandingConnections")) + .hasValue(2); + verify(provider).release(first); + verify(provider).release(second); + } finally { + // Only mocked resources exist here. Restore JVM-wide fixture state after proving that + // production code neither retries an uncertain return nor releases its retained permit. + if (retained.get() == before + 1) { + retained.decrementAndGet(); + } + if (permits.availablePermits() == available - 1) permits.release(); + } + } finally { + Metrics.removeRegistry(registry); + registry.close(); + } + } + @Test void cancellationAfterPoolReturnCannotCancelAReusedConnectionStatement() throws Exception { ConnectionProvider provider = mock(); From c86fae5627edae298e4bbe081091a6bfb3a515ef Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 00:41:15 +1300 Subject: [PATCH 18/52] fix(gameplay): retain committed execution and fence owner movement Address caller statuses, retained-permit alerting, mandatory capacity dependencies, precise recovery docs and deterministic cleanup tests. Add credential-free positive continuation and durable region-owner exclusion with five physical regression definitions. Local focused tests, integration-source compilation, affected static/style and docs pass. Physical new crash/movement cases require exact-head CI; default runtime registration remains held. --- .../game-session-service/operations.md | 10 + .../game-session-service/runtime-and-data.md | 4 +- .../system-architecture-authz-route-matrix.md | 2 +- ...ystem-architecture-authz-route-matrix.yaml | 2 +- .../player-access-and-session.md | 4 +- k8s/monitoring/prometheus-rules-firemud.yaml | 15 ++ .../service/AccountTenantCapacityOwner.java | 9 +- .../AccountTenantCapacityOwnerTest.java | 48 +++- ...playOriginalNewCapacityExecutionOwner.java | 90 +++++++ ...yOriginalNewFinalAdmissionCoordinator.java | 37 +-- ...ayOriginalNewFinalAdmissionRedisOwner.java | 163 ++++++++---- ...GameplayRegionRuntimeStatusRepository.java | 19 ++ ...NewFinalAdmissionOwnerIntegrationTest.java | 244 +++++++++++++++++- ...riginalNewCapacityExecutionBudgetTest.java | 17 ++ 14 files changed, 569 insertions(+), 95 deletions(-) diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index bb5dac47eb..bb0db3e3c9 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -47,6 +47,16 @@ Before deploying the new Game Session admission validation, Automation must alre - Prometheus scrapes metrics from `/actuator/prometheus`. - Target state: logs, traces, and control-plane reads expose the active exact `{scriptPatchVersion, scriptPinEpoch}` execution fence so operators can identify the hotfix revision and selection epoch during incident triage without adding either raw value as ordinary high-cardinality metric labels. Current coverage is summarized in [Implementation Status](#implementation-status). +### Original NEW capacity SQL release failure + +`original_new_capacity_sql_release_failure_retained_operations` is a process-local, monotonic gauge of original-NEW capacity operations whose SQL provider release threw with uncertain connection custody. It counts each affected operation once, even if multiple connections fail release. The shared [Prometheus rules](../../../../k8s/monitoring/prometheus-rules-firemud.yaml) raise the gameplay-owned P1 `OriginalNewCapacitySqlReleaseFailureRetainedOperations` alert whenever the value is greater than zero. Each retained operation consumes one of the process's four zero-waiting operation permits; four retained operations refuse all further original-NEW capacity work on that process. This manually composed component remains unregistered, so installing the rule does not establish a deployed producer or qualify admission. The [API contract](./api-contracts.md#original-new-capacity-execution-read) owns the deadline and evidence boundary. + +1. Identify the emitting process/pod and preserve its alert value, observation time, immutable image/source identity, release exception and available connection-pool/PostgreSQL session diagnostics in the incident record before replacement removes process-local diagnostics. Retain the exact affected original attempt, reservation, dispatch and execution selectors through the existing protected owner records, not metric labels. A throwing release does not prove either that the connection was returned or that a transaction did not commit. +2. Isolate new original-NEW capacity operations from the affected process using the deployment's authorized admission/drain controls. Do not clear the gauge, replenish the semaphore, blindly retry provider release, disable guards, delete SQL/Redis evidence, or release/rearm Account reservations. A deadline, an absent response or a disappearing alert grants no cleanup or no-execution authority. If isolation or the affected operation inventory cannot be established, keep admission held and escalate to the Game Session owner with infrastructure support. +3. Investigate the datasource/provider failure and reconcile the original operations against the retained immutable final receipt or exact permanent CLOSED proof. Account alone may consume qualified readback and transition its reservations under its current claim/fence. The existing recovery/read components are unregistered and do not provide a manual SQL/Redis repair procedure; unresolved or contradictory evidence remains held for owner-scoped reconciliation. +4. If process replacement is necessary to recover local execution capacity, first retain the diagnostics above and preserve all durable attempt/effect evidence and affected admission fences. Use the normal authorized deployment lifecycle, positively verify that the old process and its resource/cancellation workers have ended, and verify through the datasource/PostgreSQL owner that no old connection or transaction remains live or in uncertain custody before admitting replacement capacity work. If any of those checks is unavailable, keep the affected scope closed. Never reuse an uncertain connection or treat replacement as evidence of rollback, reservation release, or non-execution. +5. Verify the replacement's producer and scrape are present, the retained-operation gauge stays zero, and datasource acquisition/release works within the existing deadline/concurrency bound. Reopen only scopes whose normal owner authority and reconciliation gates are satisfied. A new process starts with a zero gauge and fresh permits, so alert resolution alone proves neither old-resource disposal nor admission safety. Preserve unresolved reservations and evidence until their existing owner-authorized resolution completes. + ### Visible public-production pointer cardinality preflight Before applying the existing V1053 cardinality migration, run this read-only query against the deployed Game Session schema: 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 27d83d891f..3339a36c33 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -6,7 +6,9 @@ V1063 adds retained exact original capacity execution evidence and the final tra The seven-key tenant-slot final script atomically serializes `FINAL` against permanent same-attempt `CLOSE`, retaining the complete attempt envelope, reservation fence/expiry, original owner and actual committed session hash/times. New execution requires the exact persistent `AUTHORIZED` record and an unexpired reservation at Redis `TIME`. Account transition restrictions, coupled to the irreversible closure, exclude a delayed final CAS after release or rearm without relying on a one-time remote current-fence read. Original evidence is immutable and retained without TTL, deletion or truncation. V1063 separately classifies the evidence family and seals the next runtime-family catalog epoch without changing retained predecessor epochs or migration histories. -Positive SQL terminal retention follows actual persistent session/index/atomic-outcome and final-receipt verification. That retained result survives later serving-index retirement. Retained negative replay requires the already-verified immutable SQL CLOSED proof, full original identity, exact persistent Redis CLOSED tombstone, absence of contradictory final SQL receipt/state and a fresh actual current-owner observation. Serving-index absence is never negative evidence. Missing tombstones and closure before SQL proof retention remain indeterminate. Retention-before-cleanup ordering across the earlier crash window is not yet enforced. The existing never-admitted cleanup owner accepts only untouched PREPARED dispatches; cleanup of this already-acknowledged PROVISIONAL final-admission boundary and finalized-usage retirement on real runtime teardown remain separate unfinished Account/owner work. No default owner, receiver, recovery scheduler or source custody is registered by this slice. +The finalized schema-2 reader requires `capacityExecutionDigest`; predecessor finalized values without it are unsupported by this unregistered preproduction cutover. Before activation or reuse of predecessor-populated storage, establish and resolve retained-data and active original-confirmation or recovery obligations while preserving immutable historical evidence. The [owning tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records this cutover limitation and the unknown inventory of earlier manually persisted data. + +Positive SQL terminal retention follows actual persistent session/index/atomic-outcome and final-receipt verification. That retained result survives later serving-index retirement. Retained negative replay requires the already-verified immutable SQL CLOSED proof, full original identity, exact persistent Redis CLOSED tombstone, absence of contradictory final SQL receipt/state and a fresh actual current-owner observation. Serving-index absence is never negative evidence. Missing tombstones and closure before SQL proof retention remain indeterminate. The credential-free owner-local continuation independently verifies an already-committed tenant-slot effect and persists any missing final SQL receipt before retaining terminal evidence. The existing original-attempt closure entry point invokes that positive reconciliation before refusing negative closure; it does not need the original LOGIN, credential, live grant or fresh OPEN barriers, and it never dispatches a new final effect. Serving retirement must wait for retained positive evidence or independently retained exact closure. Capacity authorization locks and checks the durable region owner before creating dispatch custody; owner-generation replacement takes the same region-row lock and refuses unresolved installation or authorization records. The coordinator revalidates its grant immediately before final dispatch and preserves verified positive receipt/retention before a later currentness failure can withhold success. The existing never-admitted cleanup owner accepts only untouched PREPARED dispatches; cleanup of this already-acknowledged PROVISIONAL final-admission boundary and finalized-usage retirement on real runtime teardown remain separate unfinished Account/owner work. No default owner, receiver, recovery scheduler or source custody is registered by this slice. The capacity execution owner uses one absolute budget for each complete operation: the earlier incoming gRPC or explicit coordinator deadline, capped at five seconds. Its local SQL connection provider and transaction provider derive from the existing configuration without changing shared datasource settings. Four resource operations are admitted without a waiting queue. Acquisition, SQL and cleanup stay in the admitted worker; cancellation requests the active JDBC statement's cancellation, while a late acquisition cannot execute SQL. Statement close and pool return detach the statement under the same monitor as cancellation. A blocked driver cancellation or acquisition retains its admission slot until it exits. A throwing pool return preserves uncertain connection ownership and retains the slot rather than blindly retrying or claiming disposal. The JVM-wide Micrometer gauge `original_new_capacity_sql_release_failure_retained_operations`, exposed through the existing Prometheus actuator path, counts retained operation slots once per affected operation, even if several connections fail to return. A nonzero value identifies lost local admission capacity; four retained slots exhaust this SQL boundary. Investigate the provider failure before a controlled process restart. Restart recovers local admission slots only and supplies no reservation or selected-owner outcome proof. JDBC query timeouts back up cancellation; neither cancellation nor deadline return proves driver termination or an owner outcome. The separate four-slot Redis connector, scoped capacity INSTALL/CLOSE writes and all successive Redis commands consume the same remaining operation budget. INSTALL and the first CLOSE mutation carry that operation's frozen absolute deadline, enforced by Redis time; completed CLOSE replay remains read-only. Other final-admission callers retain their existing connection and command policy. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 3dff3dc935..7a182c6a76 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -265,7 +265,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus validated typed player context; no circular end-user token prerequisite. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `GetTenantEntitlementsForRuntime` | `internal_workload` | Exactly one complete caller-policy alternative: Game Session mTLS plus current private delegation and typed player context for player admission, or World Management mTLS plus tenant/operation-bound instance-lifecycle context without a player delegation. Constraints within the selected alternative are conjunctive; no `control-ui` or Logging and Admin caller; not edge exposed. The read assesses eligibility only and never commits capacity. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `CommitTenantCapacityAdmission` | `internal_workload` | **Target; not currently routable.** Exactly one complete caller-policy alternative is required: Game Session presents its own exact Game Session caller workload mTLS identity to Account with typed `PlayerExecutionContext` and the live player-binding checks, or World Management presents its own exact World Management caller workload mTLS identity to Account with tenant/operation-bound instance-lifecycle context and the live lifecycle checks. Account remains the receiving authority; only those alternatives may call its exact receiving mTLS boundary. The request binds `tenantId`, stable `requestId`/`admissionId`, fresh `admissionAttemptId`, current `capacityRearmFence`, the complete Account evidence bundle including its applicable `authorityTuple`, `expected_billing_evidence`, and all `outboxCheckpoints[]`, plus a bounded `capacityDelta` whose protobuf field is `optional int64` encoded as a varint and whose canonical JSON/proto-JSON spelling is `capacityDelta` encoded as a base-10 decimal string. The machine contract explicitly distinguishes omitted (`absent`) from present zero (`present_zero`), rejects JSON `null` and boolean zero, and publishes both transport-specific golden vectors. The caller-supplied `capacity_rearm_fence` is the attempt-bound fence, while Account compares the live `capacity_admission_fence` at final commit alongside the applicable generation guards. It also carries versioned `mutationDigest` over the attempt identity, fence, and complete payload. The first attempt binds those fields without a rearm; an exact retry replays, while a changed field requires the Account-owned committed rearm CAS that advances the fence and binds the fresh attempt. Any change without that CAS is an idempotency conflict before reservation, usage, activation, or routing mutation. Account performs the final fenced reservation commit and returns the committed evidence or a canonical stale/quota/unavailable outcome; until this route is implemented, capacity-changing operations fail closed. | -| Game Session Service | `ReadOriginalNewCapacityExecution` | `internal_workload` | **Unregistered; not currently routable.** Exact same-namespace Account mTLS workload, with no user token or ambient delegated context. Bounded read-only original attempt and reservation selector. Returns complete exact binding and immutable proven final-session/SQL receipt evidence or an irreversibly closed original attempt, together with a fresh owner-fence observation distinct from the captured original fence. Missing, interrupted, ambiguous, or contradictory execution evidence returns RPC `UNAVAILABLE`; Account recovery records that failed read as `INDETERMINATE` and preserves the hold. Absence or expiry never proves non-execution. See [Game Session API Contracts](./microservices/game-session-service/api-contracts.md#original-new-capacity-execution-read). | +| Game Session Service | `ReadOriginalNewCapacityExecution` | `internal_workload` | **Unregistered; not currently routable.** Exact same-namespace Account mTLS workload, with no user token or ambient delegated context. Bounded read-only original attempt and reservation selector. Returns complete exact binding and immutable proven final-session/SQL receipt evidence or an irreversibly closed original attempt, together with a fresh owner-fence observation distinct from the captured original fence. Missing, interrupted, ambiguous, or contradictory execution evidence returns RPC `UNAVAILABLE`; Account recovery treats that failed read as indeterminate, records `SOURCE_UNAVAILABLE` before exhaustion or `QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION` on exhaustion, and preserves the hold. Absence or expiry never proves non-execution. See [Game Session API Contracts](./microservices/game-session-service/api-contracts.md#original-new-capacity-execution-read) and the [Account recovery reader](./microservices/account-service/api-contracts.md#account-reader-for-original-new-capacity-execution). | | Account Service | `GetTenantEntitlementsTenant` | `billing_safe_tenant` | `tenantAdmin` (tenant-scoped); live `current_operator_roles` and caller-bound membership checks | | Account Service | `GetTenantEntitlementsCrossTenantSupportSafe` | `cross_tenant_support_safe` | `support` without `privileged_control`; `platformAdmin` requires `privileged_control` | | Account Service | `GetSubscriptionTenantHighLevel` | `billing_safe_tenant` | `tenantAdmin` (tenant-scoped); live `current_operator_roles` and caller-bound membership checks under [Subscription Management](./microservices/account-service/subscription-management.md) | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index aea234cfae..cfed13f116 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -3205,7 +3205,7 @@ routes: implementation_status: known_drift: - unregistered_bounded_Account_only_read_and_client_prepared; deployed_PKI_source_custody_and_registration_unqualified - - missing_interrupted_or_ambiguous_evidence_returns_RPC_UNAVAILABLE_and_Account_recovery_records_INDETERMINATE; absence_or_expiry_never_proves_no_execution + - missing_interrupted_or_ambiguous_evidence_returns_RPC_UNAVAILABLE; Account_recovery_treats_failed_reads_as_indeterminate_and_records_SOURCE_UNAVAILABLE_before_exhaustion_or_QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION_on_exhaustion; absence_or_expiry_never_proves_no_execution - service: account-service route: GetTenantEntitlementsTenant scope: tenant 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 90be8f5188..f780e44654 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -42,13 +42,15 @@ Earlier attempts remain failed: R1 stopped on integration-fixture AssertJ infere 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 and is the sole negative source for Account's authorized transition. The guarded bounded Account-only read and exact Account recovery client are prepared without runtime registration. 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; existing cleanup does not yet enforce retention-before-serving-retirement in the pre-retention crash window. 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. +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. Durable unresolved execution custody excludes region-generation replacement until exact terminal reconciliation. Five new component regressions cover these crash windows, owner movement and missing-evidence refusal; physical execution of this new batch remains unverified. 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 prepared recovery policy `capacity-recovery/1` retains an immutable observation per current fenced claim, with twelve bounded read attempts and the original reconciliation deadline. Unavailable, invalid, late and ambiguous reads never release the hold. Exhaustion durably quarantines the original reservation, fence, exact payload and full held quota; replay performs no further source call. No operator release, automatic expiry, replacement reservation or unaudited quarantine-resolution API is supplied. The physical fixture includes controlled-source exhaustion/quarantine proof definitions; these remain unrun. Genuine audited Account remediation from independent owner evidence remains an activation prerequisite. diff --git a/k8s/monitoring/prometheus-rules-firemud.yaml b/k8s/monitoring/prometheus-rules-firemud.yaml index f42a5c9cfb..61c807af9a 100644 --- a/k8s/monitoring/prometheus-rules-firemud.yaml +++ b/k8s/monitoring/prometheus-rules-firemud.yaml @@ -272,6 +272,21 @@ spec: summary: World observed unresolved initial-admission holds beyond diagnostic age description: Repeated overdue observations require owner-proof and transport triage. This diagnostic alert does not authorize readiness, termination, or hold release; follow the exact owner-evidence procedure in the World initial-admission bind contract. + - name: firemud.alerts.game-session + rules: + - alert: OriginalNewCapacitySqlReleaseFailureRetainedOperations + expr: original_new_capacity_sql_release_failure_retained_operations > 0 + for: 0m + labels: + service: game-session-service + component: capacity + severity: P1 + owner: gameplay + runbook: design/architecture/microservices/game-session-service/operations.md#original-new-capacity-sql-release-failure + annotations: + summary: Original NEW capacity SQL permits remain in uncertain release custody + description: A provider release failed and the affected process retained an operation permit. Preserve original SQL and Redis execution evidence, isolate new capacity work and follow the owner reconciliation procedure; a restart or a zero gauge does not prove that an admission did not commit. + - name: firemud.recording.automation rules: - record: automation_retention_dead_letter_blocked_rows:max diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index a73f66c33f..99bb1e414d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -258,11 +258,12 @@ private void lockPlayerAccount(Request request) { } private void requireCaller(Request request, String caller) { - if (request == null - || !namespace.equals(request.targetNamespace()) - || !TenantCapacityAdmission.expectedWorkload(namespace, request.context().owner()) + if (request == null || !namespace.equals(request.targetNamespace())) + throw new CapacityException(Failure.INVALID_ARGUMENT); + if (!TenantCapacityAdmission.expectedWorkload(namespace, request.context().owner()) .equals(caller) - || !request.evidence().callerWorkload().equals(caller)) throw unavailable(); + || !request.evidence().callerWorkload().equals(caller)) + throw new CapacityException(Failure.PERMISSION_DENIED); } static void requireClaim(Record row, UUID owner, long fence, Instant now) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index baa3b9fd7b..8c196691af 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import org.jooq.ConnectionRunnable; import org.jooq.DSLContext; import org.jooq.Record; @@ -168,7 +169,13 @@ void wrongPeerOrAbsentDeltaNeverStartsAccountWork() throws Exception { var f = new Fixture(false); assertThatThrownBy( () -> f.owner.commit(f.request, "spiffe://firemud/ns/prod/sa/world-management-service")) - .hasMessage("ENTITLEMENT_UNAVAILABLE"); + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.PERMISSION_DENIED); + assertThat(failure.code().toStatusException().getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED); + }); var absent = new Request( f.request.identity(), @@ -188,6 +195,39 @@ void wrongPeerOrAbsentDeltaNeverStartsAccountWork() throws Exception { verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); } + @Test + void authenticatedGameSessionCannotSelectWorldOwnerBeforeAccountWork() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.worldRequest(1L)); + assertThatThrownBy(() -> f.owner.commit(f.request, CapacityAdmissionTestFixture.PEER)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.PERMISSION_DENIED)); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + + @Test + void wrongTargetNamespaceOrMissingRequestIsInvalidBeforeAccountWork() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.playerRequest(), "staging"); + for (String peer : + java.util.List.of( + CapacityAdmissionTestFixture.PEER, + "spiffe://firemud/ns/staging/sa/game-session-service")) { + assertThatThrownBy(() -> f.owner.commit(f.request, peer)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.INVALID_ARGUMENT); + assertThat(failure.code().toStatusException().getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.INVALID_ARGUMENT); + }); + } + assertThatThrownBy(() -> f.owner.commit(null, CapacityAdmissionTestFixture.PEER)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.INVALID_ARGUMENT)); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + @Test void unretainedNonCreatingEvidenceRemainsUnavailableWithoutAnyUsageWrite() throws Exception { var f = new Fixture(false, CapacityAdmissionTestFixture.playerRequest(false)); @@ -309,6 +349,10 @@ private Fixture(boolean expired) throws Exception { } private Fixture(boolean expired, Request request) throws Exception { + this(expired, request, "prod"); + } + + private Fixture(boolean expired, Request request, String namespace) throws Exception { this.request = request; when(accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) .thenReturn(Optional.of(new Account())); @@ -375,7 +419,7 @@ private Fixture(boolean expired, Request request) throws Exception { new ControlledTransactions(), Clock.fixed( CapacityAdmissionTestFixture.NOW.plusSeconds(expired ? 60 : 1), ZoneOffset.UTC), - "prod"); + namespace); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index fb560a41de..f3ad398a3e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -180,6 +180,9 @@ void authorize( .transactionResult( configuration -> { var tx = DSL.using(configuration); + // Serialize original effect custody with every durable region-owner replacement. + // This lock is released before any Redis command is submitted. + requireSelectedOwner(tx, source.candidate(), execution); Record row = find(tx, execution); if (row != null) { exact(row, execution); @@ -286,6 +289,11 @@ public void closeOriginalAttempt(Request request, Result reservation) { row.get("selected_owner_fence", Long.class)); exact(row, execution); Record transition = transition(execution); + if ("COMMITTED".equals(transition.get("status", String.class))) { + retainCommittedBeforeCleanup(request, reservation, budget.absoluteDeadlineMillis()); + // Successful positive reconciliation never authorizes the requested negative closure. + throw unavailable(); + } if (!"PROVISIONAL".equals(transition.get("status", String.class)) || transition.get("original_new_final_session_sha256") != null) throw unavailable(); var candidate = @@ -298,6 +306,10 @@ public void closeOriginalAttempt(Request request, Result reservation) { scopedFinalOwner() .closeCapacityExecutionOnce( execution, candidate, assignment, budget.absoluteDeadlineMillis()); + if (result == 2) { + retainCommittedBeforeCleanup(request, reservation, budget.absoluteDeadlineMillis()); + throw unavailable(); + } if (result != 4) throw unavailable(); Map physical = readExecution(execution, assignment.tenantGameplayTag()); exactPhysicalBinding(physical, execution, "CLOSED"); @@ -310,6 +322,62 @@ public void closeOriginalAttempt(Request request, Result reservation) { retainTerminal(execution, "CLOSED", proof); } + /** + * Owner-local continuation after a lost final reply or process stop. It never dispatches FINAL, + * issues a credential, or interprets absence as a negative outcome. Serving cleanup must wait for + * this retained positive evidence (or the independently verified original CLOSE path). + */ + public Snapshot retainCommittedBeforeCleanup(Request request, Result reservation) { + return retainCommittedBeforeCleanup(request, reservation, Long.MAX_VALUE); + } + + public Snapshot retainCommittedBeforeCleanup(Request request, Result reservation, long deadline) { + noSql(); + if (budget == null) + return within( + deadline, owner -> owner.retainCommittedBeforeCleanup(request, reservation, deadline)); + budget.check(); + Record row = + sql() + .fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE tenant_id = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ?", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.admissionAttemptId()); + if (row == null) throw unavailable(); + var execution = + new OriginalNewCapacityExecution( + request, + reservation, + row.get("transition_id", UUID.class), + candidateDigest(row), + row.get("selected_owner_id", String.class), + row.get("selected_owner_fence", Long.class)); + exact(row, execution); + Record transition = transition(execution); + if ("PROVISIONAL".equals(transition.get("status", String.class))) { + // Redis may already contain the irreversible positive effect even when its SQL receipt + // was not reached. Recover that exact result without the original LOGIN or private grant. + var candidate = + CanonicalGameplayOriginalNewCandidate.parseCanonical( + transition.get("original_new_candidate_bytes", byte[].class)); + var inventory = new CanonicalGameplayBindingInventoryRepository(sql()); + var decision = + inventory.readAdmissionDecision(execution.transitionId(), candidate.leaseEvidence()); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + try (var actual = scopedFinalOwner().readCommittedForRetention(source, execution)) { + inventory.commitOriginalNewFinalAdmission(actual); + } + } + Snapshot snapshot = readExact(request, reservation, true); + if (!"COMMITTED".equals(snapshot.disposition())) throw unavailable(); + retainTerminal(execution, "COMMITTED", snapshot.canonicalReadback()); + return readExact(request, reservation, false); + } + void retainCommitted(CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback actual) { retainCommitted(actual, Long.MAX_VALUE); } @@ -499,6 +567,28 @@ private static void requireClosedTransition(Record transition) { || transition.get("original_new_session_duration_ms") != null) throw unavailable(); } + private static void requireSelectedOwner( + DSLContext tx, + CanonicalGameplayOriginalNewCandidate candidate, + OriginalNewCapacityExecution execution) { + var binding = candidate.bindingIdentity(); + Record current = + tx.fetchOne( + "SELECT owner_service, owner_instance_id, executor_fence, region_epoch, paused FROM game_session_region_runtime_status WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", + binding.tenantId(), + binding.gameInstanceId(), + binding.regionId()); + if (current == null + || !"game-session-service".equals(current.get("owner_service", String.class)) + || !execution.selectedOwnerId().equals(current.get("owner_instance_id", String.class)) + || !Long.valueOf(execution.selectedOwnerFence()) + .equals(current.get("executor_fence", Long.class)) + || !binding + .regionEpoch() + .equals(java.math.BigInteger.valueOf(current.get("region_epoch", Long.class))) + || !Boolean.FALSE.equals(current.get("paused", Boolean.class))) throw unavailable(); + } + private CurrentOwner currentOwner(CanonicalGameplayOriginalNewCandidate candidate) { var binding = candidate.bindingIdentity(); Record current = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index e8041f4288..4154e891af 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -38,30 +38,6 @@ final class CanonicalGameplayOriginalNewFinalAdmissionCoordinator { private final AccountTenantCapacityClient capacityClient; private final CanonicalGameplayOriginalNewCapacityExecutionOwner capacityExecution; - CanonicalGameplayOriginalNewFinalAdmissionCoordinator( - CanonicalGameplayBindingInventoryRepository inventory, - AccountGameplayAdmissionLeaseClient accountClient, - CanonicalGameplayAccountInitialBarrierRedisOwner accountBarrier, - CanonicalGameplayIssuerAdmissionBarrierRedisOwner issuerBarrier, - CanonicalGameplayRegionBindingBridgeOwner regionBridge, - CanonicalGameplayOriginalNewBoundCredentialVerifier credentialVerifier, - CanonicalGameplayOriginalNewFinalAdmissionRedisOwner finalRedis, - Clock clock) { - this.capacityClient = null; - this.capacityExecution = null; - this.inventory = Objects.requireNonNull(inventory, "Game Session inventory is required"); - this.accountClient = Objects.requireNonNull(accountClient, "Account lease client is required"); - this.accountBarrier = - Objects.requireNonNull(accountBarrier, "Account INITIAL owner is required"); - this.issuerBarrier = - Objects.requireNonNull(issuerBarrier, "Issuer admission owner is required"); - this.regionBridge = Objects.requireNonNull(regionBridge, "Region bridge owner is required"); - this.credentialVerifier = - Objects.requireNonNull(credentialVerifier, "Bound credential verifier is required"); - this.finalRedis = Objects.requireNonNull(finalRedis, "Final admission Redis owner is required"); - this.clock = Objects.requireNonNull(clock, "Clock is required"); - } - CanonicalGameplayOriginalNewFinalAdmissionCoordinator( CanonicalGameplayBindingInventoryRepository inventory, AccountGameplayAdmissionLeaseClient accountClient, @@ -102,7 +78,6 @@ FinalAdmissionResult completeOriginalNew( long absoluteDeadlineMillis, TenantCapacityAdmission.Request capacityRequest) { requireNoAmbientSql(); - if (capacityClient == null || capacityExecution == null) throw unavailable(); if (capacityRequest == null) throw unavailable(); capacityRequest.requireStructurallyValid(); Objects.requireNonNull(originalDecision, "Original Account decision is required"); @@ -186,6 +161,11 @@ FinalAdmissionResult completeOriginalNew( beforeFinalCas.issuerOpen, execution, absoluteDeadlineMillis); + // Account commitment and capacity installation may outlive the prior grant check. + // Revalidate immediately before dispatch; durable execution custody excludes owner + // replacement throughout the residual lease-loss race and result reconciliation. + Currentness atDispatch = currentness(source, privateRegionInstallation); + requireSameCurrentness(beforeFinalCas, atDispatch); requireDeadline(absoluteDeadlineMillis); try (CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback finalReadback = finalRedis.finalizeOriginalNewOnce( @@ -197,9 +177,8 @@ FinalAdmissionResult completeOriginalNew( absoluteDeadlineMillis)) { requireFinalReadback( source, finalReadback, credential, canonicalSessionDurationMillis); - Currentness afterFinalCas = currentness(source, privateRegionInstallation); - requireSameCurrentness(beforeFinalCas, afterFinalCas); - + // The verified positive effect must acquire its durable receipt and retained + // evidence before a subsequent liveness/currentness failure withholds success. boolean committedByThisAttempt = source.transitionStatus() == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL; @@ -223,7 +202,7 @@ FinalAdmissionResult completeOriginalNew( requireReadbackMatchesReceipt(finalReadback, finalReceipt); capacityExecution.retainCommitted(finalReadback, absoluteDeadlineMillis); Currentness beforeConfirmation = currentness(source, privateRegionInstallation); - requireSameCurrentness(afterFinalCas, beforeConfirmation, committedByThisAttempt); + requireSameCurrentness(atDispatch, beforeConfirmation, committedByThisAttempt); requireDeadline(absoluteDeadlineMillis); OriginalFinalAdmissionConfirmation confirmation = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index 36b9be49ba..ab12e70c43 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -295,6 +295,52 @@ Readback finalizeOriginalNewOnce( } } + /** + * Recovers only an already-applied original effect for durable SQL receipt/retention. Unlike + * admission, recovery requires no fresh OPEN barrier, credential, or live private region grant. + * It cannot submit Lua or make the recovered session newly admissible. + */ + Readback readCommittedForRetention( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + OriginalNewCapacityExecution execution) { + requireNoAmbientTransaction(); + var candidate = requireSource(source); + if (!candidate.transition().transitionId().equals(execution.transitionId()) + || !source.candidateDigest().equals(execution.candidateDigest()) + || execution.selectedOwnerFence() + != source.regionAcknowledgement().executorFence().longValueExact()) throw unavailable(); + var assignment = tenantTags.assignmentForTransition(execution.transitionId()); + requireAssignment(assignment, candidate); + String accountKey = + ACCOUNT_PREFIX + + "{" + + assignment.tenantGameplayTag() + + "}:" + + assignment.accountId() + + ":" + + assignment.playableStateNamespaceId(); + var keys = requireKeys(candidate, assignment, accountKey, execution); + byte[] bytes = + readExactPostimages(keys, candidate, null, null, characterProjection(candidate), execution); + CanonicalGameplayOriginalNewAuthenticatedSession.Finalized finalized = null; + try { + finalized = CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized(bytes, clock); + if (!candidate.equals(finalized.candidate()) + || !execution + .digest() + .equals(JSON.readTree(bytes).get("capacityExecutionDigest").textValue())) + throw unavailable(); + Readback readback = new Readback(source, finalized, execution); + finalized = null; + return readback; + } catch (RuntimeException failure) { + throw unavailable(); + } finally { + if (finalized != null) finalized.close(); + wipe(bytes); + } + } + long closeCapacityExecutionOnce( OriginalNewCapacityExecution execution, CanonicalGameplayOriginalNewCandidate candidate, @@ -776,51 +822,58 @@ private byte[] readExactPostimages( byte[] sessionBytes = null; Map issuerFields = null; Map accountFields = new HashMap<>(); - for (Map.Entry entry : accountOpen.exactFields().entrySet()) { - accountFields.put(entry.getKey(), ascii(entry.getValue())); - } + if ((accountOpen == null) != (issuerOpen == null)) throw unavailable(); + if (accountOpen != null) + for (Map.Entry entry : accountOpen.exactFields().entrySet()) { + accountFields.put(entry.getKey(), ascii(entry.getValue())); + } + StatefulRedisConnection connection = null; try { - issuerFields = CanonicalGameplayIssuerAdmissionBarrierRedisOwner.physicalFields(issuerOpen); - try (StatefulRedisConnection connection = - redisClient.connect(ByteArrayCodec.INSTANCE)) { - RedisAsyncCommands commands = requireCommands(connection); - requirePrincipal(await(commands.aclWhoami())); - if (!persistentString(commands, sessionKey) - || !persistentString(commands, characterKey) - || !Arrays.equals(expectedCharacter, await(commands.get(characterKey))) - || !persistentMember( - commands, accountTenantKey, ascii(candidate.bindingIdentity().sessionId())) - || !persistentMember( - commands, tenantKey, ascii(candidate.bindingIdentity().sessionId()))) { - throw unavailable(); - } - sessionBytes = await(commands.get(sessionKey)); - Map capacityFields = new LinkedHashMap<>(); - capacityFields.put("binding", execution.canonicalBytes()); - capacityFields.put("digest", ascii(execution.digest())); - capacityFields.put("state", ascii("COMMITTED")); - capacityFields.put("sessionSha1", ascii(digest("SHA-1", sessionBytes))); - try (var parsed = - CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized(sessionBytes, clock)) { - capacityFields.put("admissionAt", ascii(Long.toString(parsed.admissionAtMillis()))); - capacityFields.put( - "continuityExpiresAt", ascii(Long.toString(parsed.continuityExpiresAtMillis()))); - } - try { - requireExactHash(commands, ascii(keys.capacityExecution()), capacityFields); - } finally { - wipe(capacityFields); - } + if (issuerOpen != null) + issuerFields = CanonicalGameplayIssuerAdmissionBarrierRedisOwner.physicalFields(issuerOpen); + connection = + scopedConnection == null + ? redisClient.connect(ByteArrayCodec.INSTANCE) + : scopedConnection.get(); + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(awaitCommand(commands::aclWhoami)); + if (!persistentString(commands, sessionKey) + || !persistentString(commands, characterKey) + || !Arrays.equals(expectedCharacter, awaitCommand(() -> commands.get(characterKey))) + || !persistentMember( + commands, accountTenantKey, ascii(candidate.bindingIdentity().sessionId())) + || !persistentMember( + commands, tenantKey, ascii(candidate.bindingIdentity().sessionId()))) { + throw unavailable(); + } + sessionBytes = awaitCommand(() -> commands.get(sessionKey)); + Map capacityFields = new LinkedHashMap<>(); + capacityFields.put("binding", execution.canonicalBytes()); + capacityFields.put("digest", ascii(execution.digest())); + capacityFields.put("state", ascii("COMMITTED")); + capacityFields.put("sessionSha1", ascii(digest("SHA-1", sessionBytes))); + try (var parsed = + CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized(sessionBytes, clock)) { + capacityFields.put("admissionAt", ascii(Long.toString(parsed.admissionAtMillis()))); + capacityFields.put( + "continuityExpiresAt", ascii(Long.toString(parsed.continuityExpiresAtMillis()))); + } + try { + requireExactHash(commands, ascii(keys.capacityExecution()), capacityFields); + } finally { + wipe(capacityFields); + } + if (accountOpen != null) { requireExactHash(commands, accountBarrierKey, accountFields); requireExactHash(commands, issuerBarrierKey, issuerFields); - if (sessionBytes == null - || sessionBytes.length == 0 - || sessionBytes.length - > CanonicalGameplayOriginalNewAuthenticatedSession.MAX_SESSION_BYTES) { - throw unavailable(); - } - return sessionBytes.clone(); } + if (sessionBytes == null + || sessionBytes.length == 0 + || sessionBytes.length + > CanonicalGameplayOriginalNewAuthenticatedSession.MAX_SESSION_BYTES) { + throw unavailable(); + } + return sessionBytes.clone(); } catch (RuntimeException failure) { throw unavailable(); } finally { @@ -833,30 +886,34 @@ commands, tenantKey, ascii(candidate.bindingIdentity().sessionId()))) { wipe(tenantKey); wipe(accountBarrierKey); wipe(issuerBarrierKey); + if (connection != null) { + if (scopedConnection == null) connection.close(); + else connection.closeAsync(); + } } } - private static boolean persistentString(RedisAsyncCommands commands, byte[] key) { - return "string".equals(await(commands.type(key))) - && Long.valueOf(-1L).equals(await(commands.pttl(key))); + private boolean persistentString(RedisAsyncCommands commands, byte[] key) { + return "string".equals(awaitCommand(() -> commands.type(key))) + && Long.valueOf(-1L).equals(awaitCommand(() -> commands.pttl(key))); } - private static boolean persistentMember( + private boolean persistentMember( RedisAsyncCommands commands, byte[] key, byte[] member) { - return "set".equals(await(commands.type(key))) - && Long.valueOf(-1L).equals(await(commands.pttl(key))) - && Boolean.TRUE.equals(await(commands.sismember(key, member))); + return "set".equals(awaitCommand(() -> commands.type(key))) + && Long.valueOf(-1L).equals(awaitCommand(() -> commands.pttl(key))) + && Boolean.TRUE.equals(awaitCommand(() -> commands.sismember(key, member))); } - private static void requireExactHash( + private void requireExactHash( RedisAsyncCommands commands, byte[] key, Map expected) { - if (!"hash".equals(await(commands.type(key))) - || !Long.valueOf(-1L).equals(await(commands.pttl(key)))) { + if (!"hash".equals(awaitCommand(() -> commands.type(key))) + || !Long.valueOf(-1L).equals(awaitCommand(() -> commands.pttl(key)))) { throw unavailable(); } - Long length = await(commands.hlen(key)); + Long length = awaitCommand(() -> commands.hlen(key)); if (length == null || length != expected.size()) throw unavailable(); - Map raw = await(commands.hgetall(key)); + Map raw = awaitCommand(() -> commands.hgetall(key)); if (raw == null || raw.size() != expected.size()) throw unavailable(); Map actual = new HashMap<>(); try { 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 f6f8288d66..a39e13d8d0 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 @@ -727,6 +727,25 @@ CanonicalGameplayRegionRuntimeStatus installOwner( throw unavailable(); } if (prior == null || !current.equals(prior)) throw unavailable(); + // The old generation owns any dispatched original effect until exact COMMITTED + // retention or irreversible CLOSED proof. Lease expiry alone cannot release it. + // Capacity authorization takes this same row lock before creating that custody. + if (transaction.fetchExists( + DSL.selectOne() + .from( + DSL.table("game_session_original_new_capacity_execution").as("execution")) + .join( + DSL.table("game_session_canonical_binding_region_bridge_obligation") + .as("binding")) + .on( + DSL.field("binding.transition_id") + .eq(DSL.field("execution.transition_id"))) + .where(DSL.field("binding.tenant_id").eq(source.tenantId())) + .and(DSL.field("binding.game_instance_id").eq(source.gameInstanceId())) + .and(DSL.field("binding.region_id").eq(source.regionId())) + .and(DSL.field("execution.status").in("INSTALL_DISPATCHED", "AUTHORIZED")))) { + throw unavailable(); + } } else if (prior != null || expectedRegionEpoch != 1L) { throw unavailable(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index e573819877..59da77f2e8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -81,6 +81,7 @@ class CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest { private RedisScriptCatalog catalog; private net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution controlledCapacity; + private CanonicalGameplayRegionOwnerCompositionFixture.ExistingBinding regionBinding; @BeforeEach void setUp() throws Exception { @@ -489,6 +490,226 @@ void physicalClosureBeforeSqlProofRetentionRemainsIndeterminateEvenAfterServingR .isEqualTo("AUTHORIZED"); } + @Test + void recreatedCapacityOwnerRetainsCommittedSqlBeforeServingCleanup() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + String finalDigest; + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var actual = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + inventory.commitOriginalNewFinalAdmission(actual); + finalDigest = actual.finalSessionSha256(); + } + // Stop after final SQL commit, before the original coordinator retained terminal evidence. + String rows = sqlImage(); + var physical = physicalImage(); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + // The existing closure/lifecycle entry point must recover positive custody before refusing + // a negative outcome; no original coordinator or credential is available here. + assertThatThrownBy( + () -> + capacityOwner() + .closeOriginalAttempt( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + var retained = + capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); + assertThat(retained.disposition()).isEqualTo("COMMITTED"); + assertThat(retained.physicalDigest()).isEqualTo("sha256:" + finalDigest); + var assignment = tags.assignmentForTransition(fixture.transitionId()); + controlledRemoveServingKeys(source, assignment); + var replay = + capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); + assertThat(replay.canonicalReadback()).containsExactly(retained.canonicalReadback()); + assertThat( + capacityOwner() + .retainCommittedBeforeCleanup( + controlledCapacity.request(), controlledCapacity.reservation()) + .canonicalReadback()) + .containsExactly(retained.canonicalReadback()); + } + + @Test + void recreatedCapacityOwnerRecoversCommittedRedisWithoutOriginalCredentialOrGrant() + throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var account = controlledAccountOpen(); + var issuer = issuerOpen(); + String finalDigest; + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var actual = + finalOwner() + .finalizeOriginalNewOnce( + source, template, account, issuer, controlledCapacity, deadline())) { + finalDigest = actual.finalSessionSha256(); + } + // Stop before the final SQL receipt. The original private credential is disposed, the grant + // expires, and fresh OPEN barriers are unavailable. None may erase the actual positive effect. + var assignment = tags.assignmentForTransition(fixture.transitionId()); + admin.pexpire(ascii(regionBinding.installation().grant.key()), 0); + admin.del( + ascii(account.key()), + ascii( + CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + source.candidate().bindingIdentity().issuerId(), assignment))); + assertThatThrownBy(() -> replaceRegionOwner("successor-before-reconciliation")) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .closeOriginalAttempt( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + var retained = + capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); + assertThat(retained.disposition()).isEqualTo("COMMITTED"); + assertThat(retained.physicalDigest()).isEqualTo("sha256:" + finalDigest); + assertThat(inventory.readOriginalNewFinalAdmissionSource(decision).transitionStatus()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED); + var successor = replaceRegionOwner("successor-after-reconciliation"); + assertThat(successor.executorFence().longValueExact()) + .isGreaterThan(controlledCapacity.selectedOwnerFence()); + controlledRemoveServingKeys(source, assignment); + assertThat( + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation()) + .canonicalReadback()) + .containsExactly(retained.canonicalReadback()); + } + + @Test + void missingCommittedServingEvidenceCannotReleaseOriginalOwnerCustody() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var actual = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + inventory.commitOriginalNewFinalAdmission(actual); + } + admin.del(ascii(installation.sessionKey())); + String rows = sqlImage(); + var physical = physicalImage(); + assertThatThrownBy( + () -> + capacityOwner() + .closeOriginalAttempt( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .retainCommittedBeforeCleanup( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> replaceRegionOwner("successor-with-missing-committed-evidence")) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + } + + @Test + void ownerMovementBeforeCapacityAuthorizationRefusesOriginalDispatchWithoutMutation() + throws Exception { + repairAccountMember(); + bridge(false); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + replaceRegionOwner("successor-before-capacity-dispatch"); + var account = controlledAccountOpen(); + var issuer = issuerOpen(); + String rows = sqlImage(); + var physical = physicalImage(); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var raw = credential.template(); + var bound = raw.bindCapacityExecution(controlledCapacity)) { + assertThatThrownBy( + () -> + capacityOwner() + .authorize(source, bound, account, issuer, controlledCapacity, deadline())) + .isInstanceOf(IllegalStateException.class); + } + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + } + + @Test + void unresolvedOriginalExecutionBlocksOwnerMovementUntilExactClosure() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + admin.pexpire(ascii(regionBinding.installation().grant.key()), 0); + String rows = sqlImage(); + var physical = physicalImage(); + assertThatThrownBy( + () -> + regionBinding + .owner() + .revalidateOriginalNewFinalBinding(regionBinding.installation(), source)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> replaceRegionOwner("successor-before-closure")) + .isInstanceOf(IllegalStateException.class); + // The positive continuation cannot turn an unexecuted/missing final result into proof. + assertThatThrownBy( + () -> + capacityOwner() + .retainCommittedBeforeCleanup( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + capacityOwner() + .closeOriginalAttempt(controlledCapacity.request(), controlledCapacity.reservation()); + var successor = replaceRegionOwner("successor-after-closure"); + assertThat(successor.executorFence().longValueExact()) + .isGreaterThan(controlledCapacity.selectedOwnerFence()); + assertThat( + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation()) + .disposition()) + .isEqualTo("NOT_EXECUTED_AFTER_AUTHORIZATION"); + } + @Test void sameNativeCandidateFinalizesCommitsReadsAndRecoversExactTimesAndRows() throws Exception { repairAccountMember(); @@ -1420,7 +1641,7 @@ private void bridge() { } private void bridge(boolean authorizeCapacity) { - var region = + regionBinding = CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( fixture.dsl(), ownerClient, @@ -1428,8 +1649,8 @@ private void bridge(boolean authorizeCapacity) { sources.request, sources.resolver, sources.entity); - assertThat(region.owner().bridge(region.installation()).obligation()) - .isEqualTo(region.acknowledgement().obligation()); + assertThat(regionBinding.owner().bridge(regionBinding.installation()).obligation()) + .isEqualTo(regionBinding.acknowledgement().obligation()); // Explicit controlled Account content for this native owner component proof. The separate // Account composition traverses actual evaluation/commit and is the complete capacity path. if (controlledCapacity == null) { @@ -1553,6 +1774,23 @@ private CanonicalGameplayOriginalNewCandidateRedisOwner candidateOwner( ownerClient, catalog, repository, tags); } + private net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus + replaceRegionOwner(String successor) { + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()); + var current = repository.find(original.source).orElseThrow(); + // Exercise the actual serialized persistence boundary. The caller's replacement Redis grant + // is controlled here; this is not a proof of production handoff or external source custody. + return repository.installOwner( + original.source, + current.regionEpoch(), + current, + "a".repeat(64), + "game-session-service", + successor, + CLOCK.instant()); + } + private CanonicalGameplayOriginalNewCapacityExecutionOwner capacityOwner() { return new CanonicalGameplayOriginalNewCapacityExecutionOwner( fixture.dsl(), ownerClient, catalog, CLOCK, tags); 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 703cb54f9f..2743683041 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 @@ -40,6 +40,7 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.jooq.impl.DefaultConfiguration; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.test.util.ReflectionTestUtils; @@ -47,6 +48,22 @@ class CanonicalGameplayOriginalNewCapacityExecutionBudgetTest { private static final Clock CLOCK = Clock.systemUTC(); + @AfterEach + void awaitResourceAndCancellationWorkerCleanup() throws InterruptedException { + Semaphore permits = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, "OPERATIONS")); + int maximum = CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_IN_FLIGHT_OPERATIONS; + // A mocked provider release is observed before its caller drains connection custody and + // restores admission. Wait for the real worker/cancellation lifecycle, including on failure. + assertThat(permits.tryAcquire(maximum, 2, TimeUnit.SECONDS)) + .as("resource and cancellation workers restore all operation permits") + .isTrue(); + permits.release(maximum); + } + @Test void actualOwnerReadReturnsAtDeadlineAndLateAcquisitionNeverExecutes() throws Exception { ConnectionProvider provider = mock(); From 4a18e541cdb63f284048e006a85c901fb1668c7c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 01:49:41 +1300 Subject: [PATCH 19/52] fix(capacity): classify owner evidence and await connection cleanup Qualified focused handler and resource cleanup corrections. 21 focused cases, canonical formatting, Checkstyle and Account SpotBugs passed. Orphaned original execution recovery remains a separate accepted obligation. --- .../AccountTenantCapacityGrpcService.java | 4 +- .../AccountTenantCapacityGrpcServiceTest.java | 100 ++++++++++++++++++ ...nalNewCapacityExecutionConnectionTest.java | 34 ++++++ 3 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index 31b90aa3e9..7af0c6ad42 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -88,8 +88,8 @@ public void commitTenantCapacityAdmission( | org.springframework.transaction.TransactionException unavailable) { observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); return; - } catch (IllegalArgumentException | ArithmeticException invalid) { - observer.onError(Failure.INVALID_ARGUMENT.toStatusException()); + } catch (IllegalArgumentException | ArithmeticException ownerEvidence) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); return; } catch (RuntimeException internal) { observer.onError(Status.INTERNAL.asRuntimeException()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java new file mode 100644 index 0000000000..abf683a4b8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; +import io.grpc.stub.StreamObserver; +import java.util.stream.Stream; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedConstruction; + +/** Controlled handler classification only, not authenticated transport or owner-source proof. */ +class AccountTenantCapacityGrpcServiceTest { + @Test + void malformedWireAndStructurallyInvalidRequestsRefuseBeforeOwner() { + var valid = + TenantCapacityAdmissionGrpcCodec.toRequest(CapacityAdmissionTestFixture.playerRequest()); + for (var wire : + new CommitTenantCapacityAdmissionRequest[] { + null, + CommitTenantCapacityAdmissionRequest.getDefaultInstance(), + valid.toBuilder().setCapacityDelta(0).build() + }) { + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + StreamObserver observer = mock(); + + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission(wire, observer); + + assertFailure(observer, Failure.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + } + } + + @ParameterizedTest + @MethodSource("ownerEvidenceFailures") + void retainedOwnerParseEnumAndArithmeticFailuresAreEntitlementUnavailable( + RuntimeException cause) { + var request = CapacityAdmissionTestFixture.playerRequest(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)).thenThrow(cause); + StreamObserver observer = mock(); + + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + + assertFailure(observer, Failure.ENTITLEMENT_UNAVAILABLE); + verify(owner).commit(request, CapacityAdmissionTestFixture.PEER); + } + } + + private static Stream ownerEvidenceFailures() { + return Stream.of( + new NumberFormatException("Controlled retained billing parse failure"), + new IllegalArgumentException("Controlled retained enum or evidence parse failure"), + new ArithmeticException("Controlled retained arithmetic failure")); + } + + private static MockedConstruction authenticatedCaller() { + return mockConstruction( + AccountTenantCapacityWorkloadGuard.class, + (guard, context) -> + when(guard.requireAuthenticatedCaller()).thenReturn(CapacityAdmissionTestFixture.PEER)); + } + + private static void assertFailure( + StreamObserver observer, Failure expected) { + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + var expectedFailure = expected.toStatusException(); + assertThat(Status.fromThrowable(error.getValue()).getCode()) + .isEqualTo(expectedFailure.getStatus().getCode()); + assertThat(StatusProto.fromThrowable(error.getValue())) + .isEqualTo(StatusProto.fromThrowable(expectedFailure)); + assertThat(error.getValue().getCause()).isNull(); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java index 6f3fe40f04..f3a83c8b4c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java @@ -18,14 +18,48 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution; +import org.awaitility.Awaitility; import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; /** Controlled connect behavior only, never source or execution authority. */ class CanonicalGameplayOriginalNewCapacityExecutionConnectionTest { + @AfterEach + void awaitConnectorAndBudgetWorkerCleanup() throws InterruptedException { + Semaphore permits = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, "OPERATIONS")); + int maximum = CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_IN_FLIGHT_OPERATIONS; + assertThat(permits.tryAcquire(maximum, 2, TimeUnit.SECONDS)) + .as("resource and cancellation workers restore all operation permits") + .isTrue(); + permits.release(maximum); + + ThreadPoolExecutor connectors = + (ThreadPoolExecutor) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionOwner.class, "CONNECTS")); + // closeAsync() is observed before the connector task returns. Wait for executor task + // completion as well, including after failed assertions in either timeout test. + Awaitility.await() + .atMost(2, TimeUnit.SECONDS) + .untilAsserted( + () -> { + assertThat(connectors.getActiveCount()).isZero(); + assertThat(connectors.getCompletedTaskCount()).isEqualTo(connectors.getTaskCount()); + }); + } + @Test void expiredCallDoesNotWaitForConnectionAndDisposesTheLateConnection() throws Exception { RedisClient redis = mock(); From d0d2dfa22f91a679914f0b2d2efd5f19cd745fcb Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 02:40:53 +1300 Subject: [PATCH 20/52] Preserve unqualified normal owner-transfer recovery implementation Source custody checkpoint only. Includes transfer-purpose signed currentness, deny-only fencing, V1065 and physical regression definitions. Formatting, compilation and execution remain unrun; no ready, deployed, negative-capacity or complete-fix claim. Active stack and queued review remain unchanged. --- .../game-session-service/api-contracts.md | 2 + .../game-session-service/operations.md | 4 + .../game-session-service/runtime-and-data.md | 14 +- .../system-architecture-versioning-runtime.md | 2 + .../player-access-and-session.md | 10 +- ...alAdmissionCompositionIntegrationTest.java | 30 + ...ccountTenantCapacityWorkloadGuardTest.java | 25 +- ...playOriginalNewCapacityExecutionOwner.java | 70 +- ...ayOriginalNewFinalAdmissionRedisOwner.java | 25 + ...lGameplayProtectedIncarnationReceiver.java | 208 ++++- .../CanonicalGameplayRegionLeaseOwner.java | 24 +- ...ameplayRegionOwnerTransferCoordinator.java | 113 +++ ...yRegionOwnerTransferObservationSource.java | 96 +++ ...GameplayRegionOwnerTransferRepository.java | 451 ++++++++++ ...GameplayRegionRuntimeStatusRepository.java | 28 +- ...al_new_capacity_owner_transfer_fencing.sql | 219 +++++ ...e-session-original-new-final-admission.lua | 50 +- ...-session-original-new-final-admission.json | 9 +- ...olledRegionTransferObservationFixture.java | 148 ++++ ...alNewFinalAdmissionCompositionFixture.java | 37 + ...alNewFinalAdmissionLuaIntegrationTest.java | 314 ++++++- ...NewFinalAdmissionOwnerIntegrationTest.java | 339 +++++++- ...GameplayRegionOwnerCompositionFixture.java | 13 + ...untimeStatusRepositoryIntegrationTest.java | 776 +++++++++++++++++- ...eFamilyCatalogPostgresIntegrationTest.java | 54 +- ...nOwnerTransferObservationReceiverTest.java | 699 ++++++++++++++++ 26 files changed, 3703 insertions(+), 57 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065__original_new_capacity_owner_transfer_fencing.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index da47a1e87b..b64a9ad431 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -12,6 +12,8 @@ A positive result binds the actual final session digest, controller times, immut After independent actual-CAS readback and immutable positive outcome retention, recovery does not require the serving session or indexes to remain present. Before that retention transaction commits, a crash followed by serving-evidence cleanup can still prevent positive qualification. The current cleanup paths do not yet enforce the required retention-before-retirement ordering. A genuine cleanup owner for this acknowledged PROVISIONAL boundary is also missing; the existing never-admitted owner supports only untouched PREPARED dispatches. This is an unqualified lifecycle gap, not absence proof or complete crash recovery. Missing current region-owner evidence likewise remains indeterminate even when the original positive proof is retained. See [local capacity implementation status](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) and the [authorization classification](../../system-architecture-authz-route-matrix.md). +The separate manually composed region-owner handoff can consume current deny-only transfer evidence through the existing acquire/install/revalidate path. It is not an RPC on `OriginalNewCapacityExecutionReadService`: `FENCED_INDETERMINATE` remains unavailable to that terminal-only Account reader and grants no capacity transition or player admission. The [normal-handoff contract](./runtime-and-data.md#normal-handoff-future-execution-fencing) owns its storage currentness, complete inventory, positive-retention and failure requirements. No default receiver or scheduler is registered. + ## Steady-State Account Public-JWKS Provenance The separately disabled [current-publication consumer](./configuration.md#steady-state-account-public-jwks) authenticates the exact same-namespace Account workload before consuming the private [Account public-JWKS response](../account-service/api-contracts.md#private-current-public-jwks-read). Before interpreting either disposition, it validates the response's exact nine-field source identity against the existing pin. It compares a bounded `SNAPSHOT` with exact protected projected bytes before and after the read and pins the actual returned source identity for its lifetime. It accepts no alternate file, URL, or inline-key authority. After qualification, a different valid public snapshot from authenticated Account under the unchanged pinned identity is retryable while protected mount reads remain stable and exactly equal this instance's last accepted bytes. A publication transition between two intact protected reads is also retryable only when the first mounted bytes equal the last accepted snapshot and exactly match the first authenticated Account snapshot, the second mounted bytes exactly match the second authenticated Account snapshot under the same pinned identity, both public-key profiles are valid, and a custody recheck still matches the second mounted bytes. Neither case installs a snapshot or renews the cache age; a later stable exact comparison is required before installing the new keys. Startup mismatch, arbitrary local changes, outage with changed local bytes, unsafe or missing projection, source-identity or namespace replacement, authentication/schema/custody/profile failure, and an AtomicWriter change during a protected read still refuse the consumer until explicit requalification. Successful recovery requires the usual exact coherent Account and mounted-byte comparison; it never repins the source. diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index bb0db3e3c9..6ac384609e 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -57,6 +57,10 @@ Before deploying the new Game Session admission validation, Automation must alre 4. If process replacement is necessary to recover local execution capacity, first retain the diagnostics above and preserve all durable attempt/effect evidence and affected admission fences. Use the normal authorized deployment lifecycle, positively verify that the old process and its resource/cancellation workers have ended, and verify through the datasource/PostgreSQL owner that no old connection or transaction remains live or in uncertain custody before admitting replacement capacity work. If any of those checks is unavailable, keep the affected scope closed. Never reuse an uncertain connection or treat replacement as evidence of rollback, reservation release, or non-execution. 5. Verify the replacement's producer and scrape are present, the retained-operation gauge stays zero, and datasource acquisition/release works within the existing deadline/concurrency bound. Reopen only scopes whose normal owner authority and reconciliation gates are satisfied. A new process starts with a zero gauge and fresh permits, so alert resolution alone proves neither old-resource disposal nor admission safety. Preserve unresolved reservations and evidence until their existing owner-authorized resolution completes. +### Original NEW normal-handoff continuation + +The manually composed [normal-handoff owner](./runtime-and-data.md#normal-handoff-future-execution-fencing) can fence future execution without resolving an original capacity outcome. Resume only its retained intent through the actual owner path. An incomplete census, lost marker, unavailable or changed protected storage source, missing positive serving proof or failed lease/currentness check keeps the affected scope held. There is no manual SQL/Redis repair, reset adoption, Account release/rearm or cleanup permission. A sealed completion is read-only currentness evidence, not permission to replay installation. These source components remain unregistered and do not supply a deployed incident-remediation procedure. + ### Visible public-production pointer cardinality preflight Before applying the existing V1053 cardinality migration, run this read-only query against the deployed Game Session schema: 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 3339a36c33..d44bffd885 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -8,10 +8,22 @@ The seven-key tenant-slot final script atomically serializes `FINAL` against per The finalized schema-2 reader requires `capacityExecutionDigest`; predecessor finalized values without it are unsupported by this unregistered preproduction cutover. Before activation or reuse of predecessor-populated storage, establish and resolve retained-data and active original-confirmation or recovery obligations while preserving immutable historical evidence. The [owning tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records this cutover limitation and the unknown inventory of earlier manually persisted data. -Positive SQL terminal retention follows actual persistent session/index/atomic-outcome and final-receipt verification. That retained result survives later serving-index retirement. Retained negative replay requires the already-verified immutable SQL CLOSED proof, full original identity, exact persistent Redis CLOSED tombstone, absence of contradictory final SQL receipt/state and a fresh actual current-owner observation. Serving-index absence is never negative evidence. Missing tombstones and closure before SQL proof retention remain indeterminate. The credential-free owner-local continuation independently verifies an already-committed tenant-slot effect and persists any missing final SQL receipt before retaining terminal evidence. The existing original-attempt closure entry point invokes that positive reconciliation before refusing negative closure; it does not need the original LOGIN, credential, live grant or fresh OPEN barriers, and it never dispatches a new final effect. Serving retirement must wait for retained positive evidence or independently retained exact closure. Capacity authorization locks and checks the durable region owner before creating dispatch custody; owner-generation replacement takes the same region-row lock and refuses unresolved installation or authorization records. The coordinator revalidates its grant immediately before final dispatch and preserves verified positive receipt/retention before a later currentness failure can withhold success. The existing never-admitted cleanup owner accepts only untouched PREPARED dispatches; cleanup of this already-acknowledged PROVISIONAL final-admission boundary and finalized-usage retirement on real runtime teardown remain separate unfinished Account/owner work. No default owner, receiver, recovery scheduler or source custody is registered by this slice. +Positive SQL terminal retention follows actual persistent session/index/atomic-outcome and final-receipt verification. That retained result survives later serving-index retirement. Retained negative replay requires the already-verified immutable SQL CLOSED proof, full original identity, exact persistent Redis CLOSED tombstone, absence of contradictory final SQL receipt/state and a fresh actual current-owner observation. Serving-index absence is never negative evidence. Missing tombstones and closure before SQL proof retention remain indeterminate. The credential-free owner-local continuation independently verifies an already-committed tenant-slot effect and persists any missing final SQL receipt before retaining terminal evidence. The existing original-attempt closure entry point invokes that positive reconciliation before refusing negative closure; it does not need the original LOGIN, credential, live grant or fresh OPEN barriers, and it never dispatches a new final effect. Serving retirement must wait for retained positive evidence or independently retained exact closure. Capacity authorization locks and checks the durable region owner before creating dispatch custody; ordinary owner replacement takes that same lock and refuses unresolved installation or authorization unless the normal-handoff evidence below is complete. Lease expiry alone never satisfies this gate. The coordinator revalidates its grant immediately before final dispatch and preserves verified positive receipt/retention before a later currentness failure can withhold success. The existing never-admitted cleanup owner accepts only untouched PREPARED dispatches; cleanup of this already-acknowledged PROVISIONAL final-admission boundary and finalized-usage retirement on real runtime teardown remain separate unfinished Account/owner work. No default owner, receiver, recovery scheduler or source custody is registered by this slice. The capacity execution owner uses one absolute budget for each complete operation: the earlier incoming gRPC or explicit coordinator deadline, capped at five seconds. Its local SQL connection provider and transaction provider derive from the existing configuration without changing shared datasource settings. Four resource operations are admitted without a waiting queue. Acquisition, SQL and cleanup stay in the admitted worker; cancellation requests the active JDBC statement's cancellation, while a late acquisition cannot execute SQL. Statement close and pool return detach the statement under the same monitor as cancellation. A blocked driver cancellation or acquisition retains its admission slot until it exits. A throwing pool return preserves uncertain connection ownership and retains the slot rather than blindly retrying or claiming disposal. The JVM-wide Micrometer gauge `original_new_capacity_sql_release_failure_retained_operations`, exposed through the existing Prometheus actuator path, counts retained operation slots once per affected operation, even if several connections fail to return. A nonzero value identifies lost local admission capacity; four retained slots exhaust this SQL boundary. Investigate the provider failure before a controlled process restart. Restart recovers local admission slots only and supplies no reservation or selected-owner outcome proof. JDBC query timeouts back up cancellation; neither cancellation nor deadline return proves driver termination or an owner outcome. The separate four-slot Redis connector, scoped capacity INSTALL/CLOSE writes and all successive Redis commands consume the same remaining operation budget. INSTALL and the first CLOSE mutation carry that operation's frozen absolute deadline, enforced by Redis time; completed CLOSE replay remains read-only. Other final-admission callers retain their existing connection and command policy. +### Normal-handoff future-execution fencing + +Game Session may exclude an unresolved original from future execution while its historical outcome remains indeterminate. This normal-handoff operation is separate from original-attempt closure, reservation recovery and cleanup. Its permanent tenant-slot `FENCED_INDETERMINATE` hash contains only the exact retained execution binding, digest and denying state. It may be created when the execution key is absent or replace the state of an exact persistent `AUTHORIZED` hash; neither action establishes that an earlier effect did not happen. The existing `INSTALL`, `FINAL` and `CLOSE` arms, including the predecessor script, reject that state. It never creates an authorization, session candidate, session or index, and supplies no `NOT_EXECUTED_AFTER_AUTHORIZATION` evidence. The Account reservation, original attempt/fence and complete capacity hold remain pending or quarantined under Account's existing recovery policy. + +Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The frozen generation refuses new dispatch markers, including through the database guard. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. + +The protected receiver has a separate `REGION_OWNER_TRANSFER` purpose and signed schema. Its actual SQL source binds the frozen transfer, original execution, immutable tenant-tag assignment and complete protected deployment/registry/ACL/configuration/storage/AOF identity. Nonce, signature, exact carrier, time and two-source-read checks apply to each observation. Before and after fencing, and around a complete streamed physical verification before owner installation, fresh purpose-correct observations must agree with the transfer's retained incarnation. Historical SQL receipts alone cannot qualify a missing marker or a changed, unavailable, reset, restored or rolled-back store. Verification never recreates a previously retained missing fence. An inventory which cannot be completely re-read within the operation deadline remains frozen rather than dropping the currentness requirement. Normal handoff does not authorize adoption across storage loss; the owning reset/recovery qualification remains required. + +An observed `COMMITTED` hash is not a transfer exemption: the existing positive continuation must verify the complete serving/session/index outcome, persist any missing final SQL receipt and retain immutable `COMMITTED` evidence before that item is handled. Missing positive proof blocks transfer. Existing exact `CLOSED` evidence likewise follows the existing independent closure-retention path. Neither terminal record is overwritten. Only the privately constructed current fencing capability and complete locked inventory check permit the actual acquire/install/revalidate path to install the successor and immutable transfer completion in one transaction. The original attempts remain fenced and non-admitting. A completed transfer supports a separately phase-bound signed currentness read only while its immutable successor still matches the actual current region source; completed observations cannot enroll items, change receipts or authorize another installation. Loss of the original completion reply does not grant a fresh transfer or recreate a private lease handle. + +V1065 retains the transfer control and per-original receipt families, their immutable source and completion guards, and the next owner catalog epoch. Their retention hold is not a cleanup horizon. The composition remains manual and unregistered. Controlled signed-source fixtures do not establish operational attestor custody, storage continuity, deployed recovery, runtime activation or player admission. + ## Runtime Model Game Session coordinates with Redis to store volatile session state and command queues and with PostgreSQL to persist durable game-instance control-plane metadata. It provides a single point of truth for current tick and world time while exposing gameplay-session state to the protocol front door. diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index eb6cb274f1..f39a7da1dc 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -512,6 +512,8 @@ For capacity admission, an entitlement-preserving one-for-one replacement cutove When the bounded reconciliation deadline expires without durable positive runtime-commit evidence or durable no-accept/no-runtime-mutation evidence, the Account-owned reservation-recovery worker must durably escalate the original outer request within the same Account-owned recovery workflow, preserving a durable claim, retry budget, evidence history, and final-outcome record. Admission remains closed, the current reservation fence remains authoritative, and timeout, process death, local absence, or operator assertion cannot release the reservation, finalize an uncommitted attempt, advance `capacityRearmFence`, start a fresh/replacement attempt, or reopen the target. Account owns the escalation and reconciliation record; lock expiry does not transfer that authority. The Account-owned recovery continuation continues read-only evidence collection and records one durable authoritative outcome only when its proof permits it: `COMMITTED` from positive runtime-commit evidence, `RELEASED` from durable owner no-accept/no-runtime-mutation evidence (and, only for a request rejected before commitment, Account no-accept evidence), or terminal `QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION` when neither fact can be established after the bounded recovery policy. `QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION` is a durable reservation state, not an absence: the original reservation identity, complete capacity hold, outer tuple, attempt identity, payload digest, and current fence remain represented, and the hold remains excluded from available quota until resolution. No replacement reservation, owner retry, automatic expiry, or unilateral operator release is permitted. Only an audited Account-owned remediation transition fenced to that original tuple, attempt, digest, reservation identity, and current fence may resolve quarantine. It may transition only to `COMMITTED` when independent positive runtime-commit evidence is recorded, or to `RELEASED` when durable owner no-accept/no-runtime-mutation proof establishes that the owner did not accept the Account commitment or mutate authoritative runtime state; if Account did not accept the commitment, Account no-accept evidence is also required. Any missing, conflicting, or unavailable evidence leaves the reservation quarantined. The transition updates usage and available quota exactly once according to the selected terminal outcome and retains the evidence linking the resolution to the original reservation. Release, finalization of an uncommitted reservation, rearm, or replacement still requires the durable no-accept/no-runtime-mutation proof bound to the original tuple, attempt, digest, reservation, and current fence. A positively committed runtime may only finalize the original accepted workflow from its independent positive commit evidence; it is not a deadline-expiry cleanup or rearm proof. +Game Session's forward V1065 migration classifies retained normal-handoff control and per-original fencing receipts and seals the next owner catalog epoch. V1063/V1064, predecessor catalog bytes, retained snapshots and migration histories remain unchanged. The [Game Session normal-handoff contract](./microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing) governs that future-execution exclusion; its deny state is neither an Account outcome nor a retained-data, reset or activation compatibility waiver. + ### Realm Routing Contract For Player-Addressable Realms Version cutover contract for a player-addressable realm: 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 f780e44654..42a998c921 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -36,11 +36,11 @@ The Account-owned family comprises immutable evaluation, attempt-history, and re 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. -Focused local validation on base `2e23db82384efa3221a53633dd43b45c62cd6ecc` passes 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. Physical PostgreSQL migration, fresh-bootstrap, retention/rollback, reservation finalization/release and bounded recovery/quarantine definitions remain unrun; their controlled entitlement and execution readback do not qualify genuine World lifecycle or final admission CAS. +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 then cleared the Java scopes but was interrupted by denial of the external Harmony CLA link request; external-link validation remains blocked and was not retried. Physical PostgreSQL, concurrency, runtime, admission and finalized-usage retirement remain unrun or held. -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 and is the sole negative source for Account's authorized transition. The guarded bounded Account-only read and exact Account recovery client are prepared without runtime registration. V1063 classifies the added evidence and advances the genuine catalog frontier while retaining old epochs. +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 guarded bounded Account-only read and exact Account recovery client are prepared without runtime registration. 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. @@ -50,7 +50,9 @@ Receiving from parent `3cfe7a68`, all seven [original-NEW Account/Game Session c 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. Durable unresolved execution custody excludes region-generation replacement until exact terminal reconciliation. Five new component regressions cover these crash windows, owner movement and missing-evidence refusal; physical execution of this new batch remains unverified. 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. +Remaining qualification includes these exact-source checks, complete Account rearm/stale-worker concurrency through the final owner, deployed source/PKI/Redis custody, source registration and fresh packaged runtime proof. Positive terminal replay is durable only after independent immutable actual-outcome retention. The owner-local continuation now recovers a positive final effect across both pre-receipt and pre-retention crash windows without the original credential or grant; the existing closure lifecycle calls it before refusing negative closure. Ordinary replacement remains blocked by unresolved custody; the separately prepared normal-handoff path below excludes future effects without resolving the retained outcome. Five new component regressions cover these crash windows, owner movement and missing-evidence refusal; physical execution of this new batch remains unverified. 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 new [normal-handoff source](../../architecture/microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing) prepares V1065 transfer custody, bounded region census/verification, real signed transfer-purpose currentness and deny-only tenant-slot fencing through the actual lease-owner path. New physical definitions cover abrupt process stop after the real SQL authorization commit, native handoff, predecessor Lua rejection, positive-retention refusal, current marker loss, Account hold/quarantine preservation and retained catalog upgrade. This edit batch has not been compiled, formatted or executed; it establishes no new passing proof. The multi-page/concurrency definitions are also authored with controlled reservation envelopes, separate from the actual Account composition; compilation, physical execution and final exact-source qualification remain pending. Production attestor custody, storage continuity, registration, runtime activation and admission remain held. The prepared recovery policy `capacity-recovery/1` retains an immutable observation per current fenced claim, with twelve bounded read attempts and the original reconciliation deadline. Unavailable, invalid, late and ambiguous reads never release the hold. Exhaustion durably quarantines the original reservation, fence, exact payload and full held quota; replay performs no further source call. No operator release, automatic expiry, replacement reservation or unaudited quarantine-resolution API is supplied. The physical fixture includes controlled-source exhaustion/quarantine proof definitions; these remain unrun. Genuine audited Account remediation from independent owner evidence remains an activation prerequisite. @@ -662,7 +664,7 @@ With canonical scope consumers absent from the default composition, Account conn | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. The default public bootstrap discovery, direct-scope, JOIN, and connect-token receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured receivers follow the [Account API composition boundaries](../../architecture/microservices/account-service/api-contracts.md); connect-token validates bootstrap identity and reads scope but remains held before replay or issuance. The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Target current-authority and postcondition revalidation remain unproved. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. Prepared JOIN component behavior retains the subscription-row lock boundary, remote scope/target/entitlement checks outside the lock-holding transaction, and atomic membership, operation-outcome, and audit-outbox persistence. These components are not reachable through the default receiving facade. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal retained numeric subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; the canonical UUID billing-owner detection gap is recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving), and retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionProvisioner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java); [AccountHostingSubscriptionProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionProvisionerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java); [AccountHostingSubscriptionProvisioningServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java); [AccountHostingSubscriptionDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | -| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | +| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml); [bounded capacity owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java); [original-NEW final owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [Account/Game Session capacity composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java); [native final-admission evidence](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | Bounded reservation/final-admission source and focused proof are prepared but unregistered; [strict capacity status](#strict-tenant-capacity-owner-preparation) records the executed and unrun boundaries and remaining production qualification. The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [Authenticated TCP receiver](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java); [live LOGIN custody](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java); [verified TCP origin](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java); [dedicated mTLS Gateway client](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java); [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [authenticated receiver units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java); [live custody units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java); [Gateway mTLS client units](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java); [TCP listener admission integration](../../../services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Authenticated TCP receiving preserves the Gateway-verified origin over the dedicated exact-namespace mTLS hop and retains LOGIN custody on the original live backend generation. Missing protected owners or custody fail closed as `UNAVAILABLE`; malformed commands and missing local LOGIN/WORLDS/REALMS steps return bounded actionable errors. Source and controlled-component proof do not qualify a deployed authenticated LOGIN-to-PLAY chain, canonical admission, fresh-image runtime behavior, or production Redis/PKI/source custody. Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN has selectable default-off dispatch through the existing Account gRPC service and composition of its existing owner graph; genuine runtime caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index c30d5971b3..5b11824a87 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -213,6 +213,36 @@ void retainedActualCasEvidenceStillFinalizesCapacityAfterControlledServingRetire } } + @Test + void actualNormalHandoffKeepsUnknownCapacityHeldAndBoundedRecoveryQuarantinesSameReservation() + throws Exception { + try(Session session=session()) { + var reservation=session.gs.authorizeThenFenceAndHandoffWithoutFinal( + session.client,session.jwks,session.jwt,session.capacityClient,session.capacityRequest, + System.currentTimeMillis()+5000L); + assertThatThrownBy(() -> session.capacityRead.readExact(session.capacityRequest,reservation,CLOCK.instant().plusSeconds(5))) + .isInstanceOf(RuntimeException.class); + TenantCapacityAdmission.Result result=reservation; + for(int attempt=0;attempt<12;attempt++) { + var recovery=new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + session.capacityOwner,session.dsl,session.capacityRead, + Clock.offset(CLOCK,Duration.ofSeconds(attempt*20L))); + result=recovery.reconcile(session.capacityRequest, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker.NoCommitAction.RELEASE); + assertThat(result.reservationId()).isEqualTo(reservation.reservationId()); + assertThat(result.reservationFence()).isEqualTo(reservation.reservationFence()); + assertThat(result.admissionAttemptId()).isEqualTo(reservation.admissionAttemptId()); + } + assertThat(result.state()).isEqualTo(TenantCapacityAdmission.State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); + var usage=session.dsl.fetchSingle("SELECT held_units,used_units FROM account_tenant_capacity_usage WHERE tenant_uuid=? AND owner_service='game-session-service'",reservation.identity().tenantId()); + assertThat(usage.get("held_units",Long.class)).isOne(); + assertThat(usage.get("used_units",Long.class)).isZero(); + assertThat(session.dsl.fetchCount(org.jooq.impl.DSL.table("account_tenant_capacity_reservations"))).isOne(); + assertThat(session.dsl.fetchSingle("SELECT execution_status FROM account_tenant_capacity_reservations WHERE reservation_id=?",reservation.reservationId()).get(0,String.class)) + .isEqualTo("OWNER_EXECUTION_PENDING"); + } + } + @Test void targetResolutionRefusesChangedRetainedSelectorsWithoutMutatingOwners() throws Exception { try (Session session = session()) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java index 60fc27cb14..6c8482d5ec 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java @@ -41,8 +41,18 @@ void clear() { @Test void onlyExactTlsGameSessionAndMethodCanInstallPrivateAssertion() throws Exception { var method = AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod(); - assertThat(invoke(method, tls("firemud", "game-session-service"))).isNull(); - assertThat(invoke(method, tls("firemud", "world-management-service"))).isNull(); + assertThat( + invoke( + method, + tls("firemud", "game-session-service"), + "spiffe://firemud/ns/firemud/sa/game-session-service")) + .isNull(); + assertThat( + invoke( + method, + tls("firemud", "world-management-service"), + "spiffe://firemud/ns/firemud/sa/world-management-service")) + .isNull(); assertThatThrownBy(guard::requireAuthenticatedCaller) .isInstanceOf(StatusRuntimeException.class); assertThat(invoke(method, tls("other", "game-session-service")).getCode()) @@ -80,8 +90,12 @@ void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { } } + private Status invoke(MethodDescriptor method, SSLSession ssl) { + return invoke(method, ssl, null); + } + @SuppressWarnings({"unchecked", "rawtypes"}) - private Status invoke(MethodDescriptor method, SSLSession ssl) { + private Status invoke(MethodDescriptor method, SSLSession ssl, String expectedCallerUri) { ServerCall call = mock(ServerCall.class); when(call.getMethodDescriptor()).thenReturn(method); when(call.getAttributes()) @@ -92,10 +106,7 @@ private Status invoke(MethodDescriptor method, SSLSession ssl) { AtomicInteger starts = new AtomicInteger(); ServerCallHandler next = (ignored, headers) -> { - assertThat(guard.requireAuthenticatedCaller()) - .isIn( - "spiffe://firemud/ns/firemud/sa/game-session-service", - "spiffe://firemud/ns/firemud/sa/world-management-service"); + assertThat(guard.requireAuthenticatedCaller()).isEqualTo(expectedCallerUri); starts.incrementAndGet(); return new ServerCall.Listener() {}; }; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index f3ad398a3e..fd446824d0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -586,7 +586,75 @@ private static void requireSelectedOwner( || !binding .regionEpoch() .equals(java.math.BigInteger.valueOf(current.get("region_epoch", Long.class))) - || !Boolean.FALSE.equals(current.get("paused", Boolean.class))) throw unavailable(); + || !Boolean.FALSE.equals(current.get("paused", Boolean.class)) + || CanonicalGameplayRegionOwnerTransferRepository.frozen( + tx, binding.tenantId(), binding.gameInstanceId(), binding.regionId())) throw unavailable(); + } + + CanonicalGameplayOriginalNewCapacityExecutionOwner forTransferBudget( + CanonicalGameplayOriginalNewCapacityExecutionBudget operationBudget) { + return new CanonicalGameplayOriginalNewCapacityExecutionOwner( + dsl, redis, scripts, clock, tags, operationBudget); + } + + /** Fences future work without resolving the retained original or its Account capacity hold. */ + TransferFence fenceForTransfer(CanonicalGameplayRegionOwnerTransferRepository.Item item, long deadline) { + if (budget == null) return within(deadline, owner -> owner.fenceForTransfer(item, deadline)); + budget.check(); + var execution = item.execution(); + Record row = find(sql(), execution); + if (row == null) throw unavailable(); + exact(row, execution); + long result = scopedFinalOwner().fenceCapacityExecutionOnce( + execution, item.candidate(), item.assignment(), budget.absoluteDeadlineMillis()); + if (result == 2) { + // Merely seeing a COMMITTED hash must not release old-generation custody. + retainCommittedBeforeCleanup(execution.request(), execution.reservation(), deadline); + } else if (result == 4) { + closeOriginalAttempt(execution.request(), execution.reservation()); + } else if (result != 5) throw unavailable(); + return readTransferFence(item, deadline); + } + + /** Read only. In particular, a lost/reset denying hash is never recreated by verification. */ + TransferFence readTransferFence(CanonicalGameplayRegionOwnerTransferRepository.Item item, long deadline) { + if (budget == null) return within(deadline, owner -> owner.readTransferFence(item, deadline)); + budget.check(); + var execution = item.execution(); + Map physical = readExecution(execution, item.assignment().tenantGameplayTag()); + String state = text(physical.get("state")); + if ("FENCED_INDETERMINATE".equals(state)) { + if (physical.size() != 3 || !Arrays.equals(execution.canonicalBytes(),physical.get("binding")) + || !execution.digest().equals(text(physical.get("digest")))) throw unavailable(); + } else { + if (!"COMMITTED".equals(state) && !"CLOSED".equals(state)) throw unavailable(); + exactPhysicalBinding(physical, execution, state); + Record retained = find(sql(), execution); + if (retained == null || !state.equals(retained.get("status",String.class))) throw unavailable(); + // The immutable terminal reader independently proves the full retained positive/negative result. + readExact(execution.request(), execution.reservation(), false); + } + var output = new java.io.ByteArrayOutputStream(); + physical.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> { + for (byte[] value : new byte[][] {bytes(entry.getKey()), entry.getValue()}) { + output.writeBytes(bytes(Integer.toString(value.length))); + output.write(':'); + output.writeBytes(value); + } + }); + return new TransferFence(execution.digest(), output.toByteArray()); + } + + /** Only physical inspection above constructs this future-exclusion capability. */ + static final class TransferFence { + private final String executionDigest; + private final byte[] canonicalReadback; + private TransferFence(String executionDigest, byte[] canonicalReadback) { + this.executionDigest=executionDigest; + this.canonicalReadback=canonicalReadback.clone(); + } + String executionDigest() { return executionDigest; } + byte[] canonicalReadback() { return canonicalReadback.clone(); } } private CurrentOwner currentOwner(CanonicalGameplayOriginalNewCandidate candidate) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index ab12e70c43..c322060aac 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -110,6 +110,10 @@ final class CanonicalGameplayOriginalNewFinalAdmissionRedisOwner { "CAPACITY_EXECUTION_CLOSED", RedisScriptDescriptor.OutcomeCategory.SUCCESS, RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "CAPACITY_EXECUTION_FENCED_INDETERMINATE", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), outcome( "CURRENT_PHYSICAL_STATE_REFUSED", RedisScriptDescriptor.OutcomeCategory.STALE, @@ -349,6 +353,27 @@ long closeCapacityExecutionOnce( execution, candidate, assignment, Math.addExact(clock.millis(), COMMAND_TIMEOUT_MILLIS)); } + /** Normal-handoff future exclusion only. A result is not an execution outcome. */ + long fenceCapacityExecutionOnce( + OriginalNewCapacityExecution execution, + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + long absoluteDeadlineMillis) { + requireNoAmbientTransaction(); + requireAssignment(assignment, candidate); + String accountKey = ACCOUNT_PREFIX + "{" + assignment.tenantGameplayTag() + "}:" + + assignment.accountId() + ":" + assignment.playableStateNamespaceId(); + var keys = requireKeys(candidate, assignment, accountKey, execution); + byte[] script = scriptSource(requireDescriptor()); + try { + return execute(script, keys, candidate, assignment, candidate.canonicalBytes(), + characterProjection(candidate), ascii("{}"), 1, ascii("{}"), ascii("{}"), + absoluteDeadlineMillis, ascii("transfer-fence"), execution, "FENCE"); + } finally { + wipe(script); + } + } + long closeCapacityExecutionOnce( OriginalNewCapacityExecution execution, CanonicalGameplayOriginalNewCandidate candidate, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java index 8f590f928d..97b6563493 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -40,6 +40,8 @@ final class CanonicalGameplayProtectedIncarnationReceiver { private static final String OBSERVATION_SCHEMA = "firemud.gs.protected-incarnation-read/v1"; private static final String INITIAL_OBSERVATION_SCHEMA = "firemud.gs.protected-initial-account-barrier-read/v1"; + private static final String REGION_OWNER_TRANSFER_OBSERVATION_SCHEMA = + "firemud.gs.protected-region-owner-transfer-read/v1"; private static final String INCARNATION_BINDING_SCHEMA = "firemud.gs.protected-incarnation-binding/v1"; private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); @@ -91,6 +93,24 @@ final class CanonicalGameplayProtectedIncarnationReceiver { "tenantGameplayTag", "workloadNamespace", "allocationVersion"); + private static final Set REGION_OWNER_TRANSFER_OWNER_FIELDS = + Set.of( + "ownerKind", + "transferId", + "transferIntentDigest", + "frozenSourceDigest", + "oldRegionOwnerId", + "oldRegionOwnerFence", + "gameInstanceId", + "regionId", + "regionEpoch", + "transitionId", + "requestId", + "accountId", + "executionDigest", + "candidateDigest", + "controlState", + "completionDigest"); private static final Set EVIDENCE_FIELDS = Set.of( "deploymentIdentity", @@ -112,6 +132,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { private final CanonicalGameplayAccountAdmissionBarrierRepository intentRepository; private final CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository; + private final CanonicalGameplayRegionOwnerTransferObservationSource regionOwnerTransferSource; private final CanonicalGameplayTenantGameplayTagRepository tenantTagRepository; private final ProtectedObservationChannel observationChannel; private final TrustedConfiguration trustedConfiguration; @@ -127,6 +148,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { this( intentRepository, null, + null, tenantTagRepository, observationChannel, trustedConfiguration, @@ -144,6 +166,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { this( intentRepository, null, + null, tenantTagRepository, observationChannel, trustedConfiguration, @@ -160,6 +183,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { this( null, initialRepository, + null, tenantTagRepository, observationChannel, trustedConfiguration, @@ -167,9 +191,20 @@ final class CanonicalGameplayProtectedIncarnationReceiver { new SecureRandom()); } + static CanonicalGameplayProtectedIncarnationReceiver forRegionOwnerTransfer( + CanonicalGameplayRegionOwnerTransferObservationSource source, + CanonicalGameplayTenantGameplayTagRepository tags, + ProtectedObservationChannel channel, + TrustedConfiguration trust, + Clock clock) { + return new CanonicalGameplayProtectedIncarnationReceiver( + null, null, source, tags, channel, trust, clock, new SecureRandom()); + } + private CanonicalGameplayProtectedIncarnationReceiver( CanonicalGameplayAccountAdmissionBarrierRepository intentRepository, CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, + CanonicalGameplayRegionOwnerTransferObservationSource regionOwnerTransferSource, CanonicalGameplayTenantGameplayTagRepository tenantTagRepository, ProtectedObservationChannel observationChannel, TrustedConfiguration trustedConfiguration, @@ -177,6 +212,7 @@ private CanonicalGameplayProtectedIncarnationReceiver( SecureRandom secureRandom) { this.intentRepository = intentRepository; this.initialRepository = initialRepository; + this.regionOwnerTransferSource = regionOwnerTransferSource; this.tenantTagRepository = tenantTagRepository; this.observationChannel = observationChannel; this.trustedConfiguration = trustedConfiguration; @@ -212,15 +248,50 @@ VerifiedIncarnation observeForInitialAccountBarrier(UUID originalRequestId) { return observeCurrentContext(before, () -> loadInitialCurrentContext(originalRequestId)); } + /** + * Current-read proof for normal transfer or sealed successor currentness, never mutation + * authority. It is not reset recovery or historical no-execution proof. + */ + VerifiedIncarnation observeForRegionOwnerTransfer( + UUID transferId, long targetOrdinal, long absoluteDeadlineMillis) { + requireNoAmbientTransaction(); + requireNonNil(transferId, "transferId"); + if (targetOrdinal < 0L) { + throw new IllegalArgumentException("targetOrdinal must not be negative"); + } + requireAvailable(OwnerKind.REGION_OWNER_TRANSFER); + if (absoluteDeadlineMillis <= clock.millis()) { + throw new ObservationUnavailableException("Protected transfer observation deadline expired"); + } + CurrentContext before = loadRegionOwnerTransferCurrentContext(transferId, targetOrdinal); + return observeCurrentContext( + before, + () -> loadRegionOwnerTransferCurrentContext(transferId, targetOrdinal), + absoluteDeadlineMillis); + } + private VerifiedIncarnation observeCurrentContext( CurrentContext before, java.util.function.Supplier reload) { + return observeCurrentContext(before, reload, Long.MAX_VALUE); + } + + private VerifiedIncarnation observeCurrentContext( + CurrentContext before, + java.util.function.Supplier reload, + long absoluteDeadlineMillis) { long issuedAt = clock.millis(); - if (issuedAt <= 0L) { + if (issuedAt <= 0L || absoluteDeadlineMillis <= issuedAt) { throw new ObservationUnavailableException("Protected observation clock is unavailable"); } long expiresAt; try { - expiresAt = Math.addExact(issuedAt, trustedConfiguration.observationTtlMillis()); + expiresAt = + Math.addExact( + issuedAt, + before.ownerKind() == OwnerKind.REGION_OWNER_TRANSFER + ? Math.min( + trustedConfiguration.observationTtlMillis(), absoluteDeadlineMillis - issuedAt) + : trustedConfiguration.observationTtlMillis()); } catch (ArithmeticException overflow) { throw new ObservationUnavailableException("Protected observation time window is invalid"); } @@ -280,6 +351,7 @@ private VerifiedIncarnation observeCurrentContext( private void requireAvailable(OwnerKind ownerKind) { if ((ownerKind == OwnerKind.ACCOUNT_FENCE && intentRepository == null) || (ownerKind == OwnerKind.INITIAL_ACCOUNT_BARRIER && initialRepository == null) + || (ownerKind == OwnerKind.REGION_OWNER_TRANSFER && regionOwnerTransferSource == null) || tenantTagRepository == null || observationChannel == null || trustedConfiguration == null @@ -347,6 +419,7 @@ private CurrentContext loadCurrentContext(UUID operationId, long targetOrdinal) null, null, null, + null, null); } @@ -388,7 +461,57 @@ private CurrentContext loadInitialCurrentContext(UUID originalRequestId) { context.sourceControlState(), context.sourceControlEpoch().toString(), context.accountLoginEvidenceDigest(), - context.sourceControlDigest()); + context.sourceControlDigest(), + null); + } + + private CurrentContext loadRegionOwnerTransferCurrentContext(UUID transferId, long targetOrdinal) { + requireNoAmbientTransaction(); + CanonicalGameplayRegionOwnerTransferObservationSource.Context context = + regionOwnerTransferSource.readCurrent(transferId, targetOrdinal); + if (context == null + || !transferId.equals(context.transferId()) + || targetOrdinal != context.targetOrdinal()) { + throw new ObservationRejectedException("Protected transfer observation source differs"); + } + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + regionOwnerTransferSource.readAssignment(context.transitionId(), tenantTagRepository); + if (assignment == null + || !assignment.isBindingTransition() + || !context.transitionId().equals(assignment.transitionId()) + || !context.accountId().equals(assignment.accountId()) + || !context.tenantId().equals(assignment.tenantId()) + || !context.gameInstanceId().equals(assignment.gameInstanceId()) + || !context.playableStateNamespaceId().equals(assignment.playableStateNamespaceId()) + || !context.tenantGameplayTag().equals(assignment.tenantGameplayTag()) + || !context.workloadNamespace().equals(assignment.workloadNamespace()) + || context.allocationVersion() != assignment.allocationVersion()) { + throw new ObservationRejectedException( + "Protected transfer observation differs from current transition assignment"); + } + return new CurrentContext( + OwnerKind.REGION_OWNER_TRANSFER, + context.transferId(), + context.requestId(), + context.accountId(), + null, + null, + null, + null, + null, + context.targetOrdinal(), + context.tenantId(), + context.playableStateNamespaceId(), + context.tenantGameplayTag(), + context.workloadNamespace(), + context.allocationVersion(), + null, + 0L, + null, + null, + null, + null, + context); } private VerifiedPayload verifyObservation( @@ -422,9 +545,11 @@ private VerifiedPayload verifyObservation( requireExactFields(root, ROOT_FIELDS); String expectedSchema = - expected.ownerKind() == OwnerKind.ACCOUNT_FENCE - ? OBSERVATION_SCHEMA - : INITIAL_OBSERVATION_SCHEMA; + switch (expected.ownerKind()) { + case ACCOUNT_FENCE -> OBSERVATION_SCHEMA; + case INITIAL_ACCOUNT_BARRIER -> INITIAL_OBSERVATION_SCHEMA; + case REGION_OWNER_TRANSFER -> REGION_OWNER_TRANSFER_OBSERVATION_SCHEMA; + }; requireText(root, "schema", expectedSchema); requireText(root, "attestorBinding", trustedConfiguration.attestorBinding()); requireText(root, "attestorKeyId", keyId); @@ -454,7 +579,7 @@ private VerifiedPayload verifyObservation( requireText(owner, "inventorySnapshotRevision", expected.inventorySnapshotRevision()); requireText(owner, "cohortDigest", expected.cohortDigest()); requireText(owner, "barrierTargetDigest", expected.barrierTargetDigest()); - } else { + } else if (expected.ownerKind() == OwnerKind.INITIAL_ACCOUNT_BARRIER) { requireExactFields(owner, INITIAL_OWNER_FIELDS); requireText(owner, "ownerKind", OwnerKind.INITIAL_ACCOUNT_BARRIER.name()); requireText(owner, "initializerId", expected.operationId().toString()); @@ -470,6 +595,33 @@ private VerifiedPayload verifyObservation( requireText(owner, "accountLoginEvidenceDigest", expected.accountLoginEvidenceDigest()); requireText(owner, "sourceControlDigest", expected.sourceControlDigest()); requireText(owner, "targetDigest", expected.barrierTargetDigest()); + } else { + requireExactFields(owner, REGION_OWNER_TRANSFER_OWNER_FIELDS); + var transfer = expected.regionOwnerTransferContext(); + requireText(owner, "ownerKind", OwnerKind.REGION_OWNER_TRANSFER.name()); + requireText(owner, "transferId", transfer.transferId().toString()); + requireText(owner, "transferIntentDigest", transfer.transferIntentDigest()); + requireText(owner, "frozenSourceDigest", transfer.frozenSourceDigest()); + requireText(owner, "oldRegionOwnerId", transfer.oldRegionOwnerId()); + if (requiredPositiveLong(owner, "oldRegionOwnerFence") != transfer.oldRegionOwnerFence() + || requiredPositiveLong(owner, "regionEpoch") != transfer.regionEpoch()) { + throw new ObservationRejectedException("Protected transfer owner fence or epoch differs"); + } + requireText(owner, "gameInstanceId", transfer.gameInstanceId().toString()); + requireText(owner, "regionId", transfer.regionId().toString()); + requireText(owner, "transitionId", transfer.transitionId().toString()); + requireText(owner, "requestId", transfer.requestId().toString()); + requireText(owner, "accountId", transfer.accountId().toString()); + requireText(owner, "executionDigest", transfer.executionDigest()); + requireText(owner, "candidateDigest", transfer.candidateDigest()); + requireText(owner, "controlState", transfer.controlState()); + if (transfer.completionDigest() == null) { + if (!owner.get("completionDigest").isNull()) { + throw new ObservationRejectedException("Protected FROZEN context has a completion"); + } + } else { + requireText(owner, "completionDigest", transfer.completionDigest()); + } } JsonNode target = requiredObject(root, "target"); @@ -943,7 +1095,8 @@ private static void requireDigestValue(String value, String field) { enum OwnerKind { ACCOUNT_FENCE, - INITIAL_ACCOUNT_BARRIER + INITIAL_ACCOUNT_BARRIER, + REGION_OWNER_TRANSFER } /** Discriminated current owner and exact target tuple obtained from the actual SQL owners. */ @@ -968,7 +1121,8 @@ record CurrentContext( String sourceControlState, String sourceControlEpoch, String accountLoginEvidenceDigest, - String sourceControlDigest) { + String sourceControlDigest, + CanonicalGameplayRegionOwnerTransferObservationSource.Context regionOwnerTransferContext) { CurrentContext { Objects.requireNonNull(ownerKind, "ownerKind"); Objects.requireNonNull(operationId, "operationId"); @@ -983,7 +1137,7 @@ record CurrentContext( Objects.requireNonNull(operationFence, "operationFence"); Objects.requireNonNull(cohortDigest, "cohortDigest"); Objects.requireNonNull(barrierTargetDigest, "barrierTargetDigest"); - } else { + } else if (ownerKind == OwnerKind.INITIAL_ACCOUNT_BARRIER) { Objects.requireNonNull(originalCallerContextId, "originalCallerContextId"); Objects.requireNonNull(sourceControlState, "sourceControlState"); Objects.requireNonNull(accountLoginEvidenceDigest, "accountLoginEvidenceDigest"); @@ -997,6 +1151,33 @@ record CurrentContext( throw new IllegalArgumentException( "INITIAL owner context is not the positively read NO_ACTIVE arm"); } + } else { + Objects.requireNonNull(regionOwnerTransferContext, "regionOwnerTransferContext"); + if (!operationId.equals(regionOwnerTransferContext.transferId()) + || !requestId.equals(regionOwnerTransferContext.requestId()) + || !accountId.equals(regionOwnerTransferContext.accountId()) + || targetOrdinal != regionOwnerTransferContext.targetOrdinal() + || !tenantId.equals(regionOwnerTransferContext.tenantId()) + || !playableStateNamespaceId.equals(regionOwnerTransferContext.playableStateNamespaceId()) + || !tenantGameplayTag.equals(regionOwnerTransferContext.tenantGameplayTag()) + || !workloadNamespace.equals(regionOwnerTransferContext.workloadNamespace()) + || allocationVersion != regionOwnerTransferContext.allocationVersion() + || operationFence != null + || plannedAccountAdmissionFence != null + || inventorySnapshotRevision != null + || cohortDigest != null + || barrierTargetDigest != null + || originalCallerContextId != null + || originalAttemptFence != 0L + || sourceControlState != null + || sourceControlEpoch != null + || accountLoginEvidenceDigest != null + || sourceControlDigest != null) { + throw new IllegalArgumentException("Transfer context must use its separate typed owner arm"); + } + } + if (ownerKind != OwnerKind.REGION_OWNER_TRANSFER && regionOwnerTransferContext != null) { + throw new IllegalArgumentException("Transfer context cannot be used by another owner kind"); } } } @@ -1048,6 +1229,13 @@ OwnerKind ownerKind() { return context.ownerKind(); } + CanonicalGameplayRegionOwnerTransferObservationSource.Context regionOwnerTransferContext() { + if (context.ownerKind() != OwnerKind.REGION_OWNER_TRANSFER) { + throw new ObservationRejectedException("Protected observation is not a region-owner transfer"); + } + return context.regionOwnerTransferContext(); + } + UUID requestId() { return context.requestId(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index f1f1b35c68..d6ec1e851f 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 @@ -71,6 +71,14 @@ Installation installForTransition( Installation existingRegionInstallation, UUID transitionId, CanonicalInitialPlayerLocationRequest worldRequest) { + return installForTransition(existingRegionInstallation,transitionId,worldRequest,null,Long.MAX_VALUE); + } + + /** Explicit normal handoff, using actual acquire/install/revalidation and transfer-purpose proof. */ + Installation installForTransition( + Installation existingRegionInstallation, UUID transitionId, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner,long absoluteDeadlineMillis) { requireNoAmbientTransaction(); Objects.requireNonNull(transitionId, "transitionId"); Objects.requireNonNull(worldRequest, "worldRequest"); @@ -85,6 +93,7 @@ Installation installForTransition( CanonicalGameplayRegionRuntimeStatus prior = statusRepository.find(source).orElse(null); if (prior == null && expectedRegionEpoch != 1L) throw unavailable(); if (prior != null && prior.regionEpoch() != expectedRegionEpoch) throw unavailable(); + UUID transferId=null; CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; @@ -189,6 +198,13 @@ Installation installForTransition( throw unavailable(); } if (existingRegionInstallation == null) { + if(transferOwner!=null) { + // Preserve ordinary timeline/incarnation qualification before any transfer effect. + // A lost completion reply is not permission to freeze/advance its successor again. + if(transferOwner.alreadyCompleted(prior,runtimeIdentity.serviceInstanceId(),absoluteDeadlineMillis)) + throw unavailable(); + transferId=transferOwner.advance(source,prior,absoluteDeadlineMillis); + } grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); } else { requireReusableRegionGrant( @@ -212,15 +228,17 @@ Installation installForTransition( redisOwner.verifyInitializedTimeline(grant, preparation); Instant installedAt = clock.instant(); - CanonicalGameplayRegionRuntimeStatus installed = - statusRepository.installOwner( + CanonicalGameplayRegionRuntimeStatus installed = transferId==null + ? statusRepository.installOwner( source, expectedRegionEpoch, prior, grant.tokenCorrelation(), grant.ownerService(), grant.ownerInstanceId(), - installedAt); + installedAt) + : transferOwner.install(transferId,source,prior,grant.tokenCorrelation(), + grant.ownerService(),grant.ownerInstanceId(),absoluteDeadlineMillis); redisOwner.requireCurrent(grant); redisOwner.verifyInitializedTimeline(grant, preparation); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java new file mode 100644 index 0000000000..7e4fa3495a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.time.Clock; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import org.jooq.DSLContext; + +/** Explicit normal-handoff composition; not a receiver, scheduler, reset owner or Account owner. */ +final class CanonicalGameplayRegionOwnerTransferCoordinator { + private final DSLContext dsl; + private final Clock clock; + private final CanonicalGameplayRegionOwnerTransferRepository repository; + private final CanonicalGameplayOriginalNewCapacityExecutionOwner capacity; + private final CanonicalGameplayProtectedIncarnationReceiver observations; + + CanonicalGameplayRegionOwnerTransferCoordinator( + DSLContext dsl, Clock clock, CanonicalGameplayRegionOwnerTransferRepository repository, + CanonicalGameplayOriginalNewCapacityExecutionOwner capacity, + CanonicalGameplayProtectedIncarnationReceiver observations) { + this.dsl=Objects.requireNonNull(dsl); + this.clock=Objects.requireNonNull(clock); + this.repository=Objects.requireNonNull(repository); + this.capacity=Objects.requireNonNull(capacity); + this.observations=Objects.requireNonNull(observations); + } + + /** Read-only lost-completion gate; it never authorizes another generation or recreates a grant. */ + boolean alreadyCompleted(CanonicalGameplayRegionRuntimeStatus prior,String requestingOwner,long deadline) { + return repository.completedForCurrent(prior,requestingOwner,deadline); + } + + /** A bounded step; incomplete progress remains durable and the caller must resume this intent. */ + UUID advance(CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, long deadline) { + return repository.within(deadline, budget -> { + UUID transfer=repository.begin(source,prior); + if(transfer==null) return null; + var owner=capacity.forTransferBudget(budget); + for (var item:repository.capture(transfer)) { + var before=observe(item,budget.absoluteDeadlineMillis()); + var physical=owner.fenceForTransfer(item,budget.absoluteDeadlineMillis()); + var after=observe(item,budget.absoluteDeadlineMillis()); + repository.retainFence(item,physical,before,after); + } + // A verification round re-reads every retained marker, including older generations, + // through bounded restartable pages. It never reinstalls a missing retained fence. + long cursor=repository.verificationCursor(transfer); + List page=repository.page(transfer,cursor); + for (var item:page) { + var before=observe(item,budget.absoluteDeadlineMillis()); + var actual=owner.readTransferFence(item,budget.absoluteDeadlineMillis()); + var after=observe(item,budget.absoluteDeadlineMillis()); + repository.retainVerification(item,actual,before,after); + } + if (!repository.finishVerification(transfer)) throw held(); + return transfer; + }); + } + + CanonicalGameplayRegionRuntimeStatus install( + UUID transferId, CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, String leaseCorrelation, + String ownerService,String ownerInstanceId,long deadline) { + return repository.within(deadline,budget -> { + var first=repository.page(transferId,-1); + if (first.isEmpty()) { + return new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) + .installOwner(source,prior.regionEpoch(),prior,leaseCorrelation,ownerService, + ownerInstanceId,clock.instant()); + } + var before=observe(first.getFirst(),budget.absoluteDeadlineMillis()); + var owner=capacity.forTransferBudget(budget); + // Stream the entire frozen inventory through bounded pages under this one absolute + // operation budget. Earlier page receipts cannot hide a subsequently lost marker. + // An inventory that cannot be currently proved inside the deadline stays frozen. + var page=first; + while(!page.isEmpty()) { + budget.check(); + for(var item:page) { + var actual=owner.readTransferFence(item,budget.absoluteDeadlineMillis()); + repository.requireRetainedPhysical(item,actual); + } + page=repository.page(transferId,page.getLast().ordinal()); + } + var after=observe(first.getFirst(),budget.absoluteDeadlineMillis()); + var proof=repository.qualify(transferId,before,after,budget.absoluteDeadlineMillis()); + var installed=new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) + .installOwner(source,prior.regionEpoch(),prior,leaseCorrelation,ownerService, + ownerInstanceId,clock.instant(),proof); + // Completion grants no historical-fence exemption. The source now independently checks + // the immutable completed successor against the actual current region owner. + var completed=observations.observeForRegionOwnerTransfer( + transferId,first.getFirst().ordinal(),budget.absoluteDeadlineMillis()); + if(!after.incarnationDigest().equals(completed.incarnationDigest())) throw held(); + owner.readTransferFence(first.getFirst(),budget.absoluteDeadlineMillis()); + return installed; + }); + } + + private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observe( + CanonicalGameplayRegionOwnerTransferRepository.Item item,long deadline) { + var value=observations.observeForRegionOwnerTransfer(item.transferId(),item.ordinal(),deadline); + if(!repository.readCurrent(item.transferId(),item.ordinal()).equals(value.regionOwnerTransferContext()) + || value.ownerKind()!=CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER) throw held(); + return value; + } + + private static IllegalStateException held() { + return new IllegalStateException("Normal region handoff requires complete current transfer evidence"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java new file mode 100644 index 0000000000..bbf846b543 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Current SQL transfer intent/item or sealed completion, never transfer mutation authority. */ +@FunctionalInterface +interface CanonicalGameplayRegionOwnerTransferObservationSource { + Context readCurrent(UUID transferId, long targetOrdinal); + + /** Independent topology read; SQL implementations retain their operation's admitted budget. */ + default CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository tags) { + return tags.assignmentForTransition(transitionId); + } + + /** + * One frozen item and its original owner, with its exact current control phase. A COMPLETED + * context requires independently current sealed successor evidence and is read-only currentness, + * never permission for mutation. Mutable per-item progress is deliberately excluded: completing + * a different item must not change this item's observation identity. + */ + record Context( + UUID transferId, + long targetOrdinal, + String transferIntentDigest, + String frozenSourceDigest, + String oldRegionOwnerId, + long oldRegionOwnerFence, + UUID tenantId, + UUID gameInstanceId, + UUID regionId, + long regionEpoch, + UUID transitionId, + UUID requestId, + UUID accountId, + UUID playableStateNamespaceId, + String executionDigest, + String candidateDigest, + String tenantGameplayTag, + String workloadNamespace, + int allocationVersion, + String controlState, + String completionDigest) { + public Context { + requireNonNil(transferId, "transferId"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(gameInstanceId, "gameInstanceId"); + requireNonNil(regionId, "regionId"); + requireNonNil(transitionId, "transitionId"); + requireNonNil(requestId, "requestId"); + requireNonNil(accountId, "accountId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireDigest(transferIntentDigest, "transferIntentDigest"); + requireDigest(frozenSourceDigest, "frozenSourceDigest"); + requireDigest(executionDigest, "executionDigest"); + requireDigest(candidateDigest, "candidateDigest"); + if (targetOrdinal < 0L || oldRegionOwnerFence <= 0L || regionEpoch <= 0L) { + throw new IllegalArgumentException("Transfer ordinal, owner fence or region epoch is invalid"); + } + if (oldRegionOwnerId == null + || oldRegionOwnerId.isBlank() + || !oldRegionOwnerId.equals(oldRegionOwnerId.trim()) + || oldRegionOwnerId.codePointCount(0, oldRegionOwnerId.length()) > 120) { + throw new IllegalArgumentException("Transfer original region owner id is invalid"); + } + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag(tenantGameplayTag); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) || allocationVersion <= 0) { + throw new IllegalArgumentException("Transfer workload or allocation version is invalid"); + } + if ("FROZEN".equals(controlState)) { + if (completionDigest != null) { + throw new IllegalArgumentException("FROZEN transfer context cannot contain a completion"); + } + } else if ("COMPLETED".equals(controlState)) { + requireDigest(completionDigest, "completionDigest"); + } else { + throw new IllegalArgumentException("Transfer observation control state is invalid"); + } + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } + + private static void requireDigest(String value, String field) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(field + " must be canonical SHA-256"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java new file mode 100644 index 0000000000..ce0d4551ab --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -0,0 +1,451 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Retained normal-handoff custody. It supplies neither an execution outcome nor Account authority. */ +final class CanonicalGameplayRegionOwnerTransferRepository + implements CanonicalGameplayRegionOwnerTransferObservationSource { + static final int PAGE_SIZE = 32; + private static final String TRANSFER = "game_session_region_owner_transfer"; + private static final String ITEM = "game_session_region_owner_transfer_item"; + private static final String PENDING = + " FROM game_session_original_new_capacity_execution e" + + " JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=e.transition_id" + + " WHERE b.tenant_id=? AND b.game_instance_id=? AND b.region_id=?" + + " AND e.status IN ('INSTALL_DISPATCHED','AUTHORIZED')"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private final DSLContext dsl; + private final Clock clock; + private final CanonicalGameplayTenantGameplayTagRepository tags; + private final ThreadLocal admitted = + new ThreadLocal<>(); + + CanonicalGameplayRegionOwnerTransferRepository( + DSLContext dsl, Clock clock, CanonicalGameplayTenantGameplayTagRepository tags) { + this.dsl = Objects.requireNonNull(dsl); + this.clock = Objects.requireNonNull(clock); + this.tags = Objects.requireNonNull(tags); + } + + T within(long deadline, Function work) { + noSql(); + if (admitted.get() != null) return work.apply(admitted.get()); + return CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + clock, + deadline, + budget -> { + admitted.set(budget); + try { + return work.apply(budget); + } finally { + admitted.remove(); + } + }); + } + + DSLContext sql() { + var budget = admitted.get(); + if (budget == null) throw unavailable(); + return budget.sql(dsl); + } + + UUID begin( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior) { + noSql(); + String sourceDigest = sourceDigest(source, prior); + return sql().transactionResult( + configuration -> { + var tx = DSL.using(configuration); + requireOldOwner(tx, source, prior); + Record old = tx.fetchOne("SELECT * FROM " + TRANSFER + " WHERE old_owner_fence=?", prior.executorFence().longValueExact()); + if (old != null) { + if (!sourceDigest.equals(old.get("source_digest", String.class)) + || !"FROZEN".equals(old.get("state", String.class))) throw unavailable(); + return old.get("transfer_id", UUID.class); + } + if (!exists(tx,"SELECT 1" + PENDING, source.tenantId(),source.gameInstanceId(),source.regionId())) return null; + UUID id = UUID.randomUUID(); + String intentDigest = digest(bytes("region-owner-transfer/v1/" + id + "/" + sourceDigest)); + if (tx.execute( + "INSERT INTO " + TRANSFER + + " (transfer_id,tenant_id,game_instance_id,region_id,region_epoch,old_owner_id,old_owner_fence,old_lease_correlation,source_digest,intent_digest,state) VALUES (?,?,?,?,?,?,?,?,?,?,'FROZEN')", + id, source.tenantId(), source.gameInstanceId(), source.regionId(), prior.regionEpoch(), + prior.ownerInstanceId(), prior.executorFence().longValueExact(), prior.leaseTokenCorrelation(), sourceDigest, intentDigest) + != 1) throw unavailable(); + return id; + }); + } + + boolean completedForCurrent(CanonicalGameplayRegionRuntimeStatus prior,String requestingOwner,long deadline) { + return within(deadline,ignored -> exists(sql(),"SELECT 1 FROM " + TRANSFER + " WHERE tenant_id=? AND game_instance_id=? AND region_id=? AND state='COMPLETED' AND new_owner_id=? AND new_owner_id=? AND new_owner_fence=? AND new_lease_correlation=?", + prior.tenantId(),prior.gameInstanceId(),prior.regionId(),prior.ownerInstanceId(),requestingOwner, + prior.executorFence().longValueExact(),prior.leaseTokenCorrelation())); + } + + /** One bounded enrollment step. The final anti-join, not a cursor or page size, proves completeness. */ + List capture(UUID transferId) { + noSql(); + sql().transaction( + configuration -> { + var tx = DSL.using(configuration); + Record transfer = current(tx, transferId, true); + var rows = tx.fetch( + "SELECT DISTINCT e.execution_digest" + PENDING + + " AND NOT EXISTS (SELECT 1 FROM " + ITEM + " i WHERE i.transfer_id=? AND i.execution_digest=e.execution_digest)" + + " ORDER BY e.execution_digest LIMIT ?", + transfer.get("tenant_id", UUID.class), transfer.get("game_instance_id", UUID.class), + transfer.get("region_id", UUID.class), transferId, PAGE_SIZE); + long ordinal = tx.fetchSingle("SELECT coalesce(max(target_ordinal),-1) FROM " + ITEM + " WHERE transfer_id=?", transferId).get(0, Long.class); + for (Record row : rows) { + String executionDigest = row.get("execution_digest", String.class); + // The actual retained execution and original candidate, never a caller selector. + Record retained = tx.fetchSingle("SELECT canonical_execution,tenant_gameplay_tag FROM game_session_original_new_capacity_execution WHERE execution_digest=?", executionDigest); + var execution = decode(retained.get("canonical_execution", byte[].class)); + ordinal = Math.incrementExact(ordinal); + String tag = retained.get("tenant_gameplay_tag", String.class); + int allocation = Integer.parseInt(tag.substring(1, tag.indexOf('-'))); + tx.execute("INSERT INTO " + ITEM + " (transfer_id,target_ordinal,execution_digest,canonical_execution,candidate_digest,tenant_gameplay_tag,workload_namespace,allocation_version) VALUES (?,?,?,?,?,?,?,?)", + transferId, ordinal, executionDigest, execution.canonicalBytes(), + execution.candidateDigest(), tag, execution.request().targetNamespace(), allocation); + } + }); + List result = new ArrayList<>(); + for (Record row : sql().fetch("SELECT target_ordinal,execution_digest FROM " + ITEM + " WHERE transfer_id=? AND fence_readback IS NULL ORDER BY target_ordinal LIMIT ?", transferId, PAGE_SIZE)) { + result.add(loadItem(sql(), transferId, row.get("target_ordinal", Long.class), row.get("execution_digest", String.class))); + } + return List.copyOf(result); + } + + List page(UUID transferId, long afterOrdinal) { + current(sql(), transferId, false); + List result = new ArrayList<>(); + for (Record row : sql().fetch("SELECT target_ordinal,execution_digest FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal>? ORDER BY target_ordinal LIMIT ?", transferId, afterOrdinal, PAGE_SIZE)) { + result.add(loadItem(sql(), transferId, row.get("target_ordinal", Long.class), row.get("execution_digest", String.class))); + } + return List.copyOf(result); + } + + void retainFence(Item item, CanonicalGameplayOriginalNewCapacityExecutionOwner.TransferFence actual, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after) { + var context = readCurrent(item.transferId(), item.ordinal()); + requireObservation(context, before); + requireObservation(context, after); + if (!before.incarnationDigest().equals(after.incarnationDigest()) + || !item.execution().digest().equals(actual.executionDigest())) throw unavailable(); + sql().transaction(configuration -> { + var tx = DSL.using(configuration); + Record transfer = current(tx, item.transferId(), true); + String retained = transfer.get("incarnation_digest", String.class); + if (retained != null && !retained.equals(after.incarnationDigest())) throw unavailable(); + tx.execute("UPDATE " + TRANSFER + " SET incarnation_digest=? WHERE transfer_id=? AND incarnation_digest IS NULL", after.incarnationDigest(), item.transferId()); + Record row = tx.fetchSingle("SELECT * FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=? FOR UPDATE", item.transferId(), item.ordinal()); + byte[] prior = row.get("fence_readback", byte[].class); + if (prior != null && !Arrays.equals(prior, actual.canonicalReadback())) throw unavailable(); + tx.execute("UPDATE " + ITEM + " SET fence_readback=?,incarnation_digest=?,before_payload_digest=?,after_payload_digest=? WHERE transfer_id=? AND target_ordinal=? AND fence_readback IS NULL", + actual.canonicalReadback(), after.incarnationDigest(), before.payloadDigest(), after.payloadDigest(), item.transferId(), item.ordinal()); + }); + } + + /** Private capability is minted only after a complete current physical verification pass. */ + Completion qualify(UUID transferId, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after, long deadline) { + if (clock.millis() >= deadline || !before.incarnationDigest().equals(after.incarnationDigest()) + || !"FROZEN".equals(before.regionOwnerTransferContext().controlState()) + || !"FROZEN".equals(after.regionOwnerTransferContext().controlState())) throw unavailable(); + requireObservation(readCurrent(transferId, before.targetOrdinal()), before); + requireObservation(readCurrent(transferId, after.targetOrdinal()), after); + Record transfer = current(sql(), transferId, false); + if (!before.incarnationDigest().equals(transfer.get("incarnation_digest", String.class))) throw unavailable(); + UUID round = transfer.get("verification_round", UUID.class); + if (round == null || !Boolean.TRUE.equals(transfer.get("verification_complete", Boolean.class)) + || exists(sql(),"SELECT 1 FROM " + ITEM + " WHERE transfer_id=? AND verified_round IS DISTINCT FROM ?", transferId, round)) throw unavailable(); + requireComplete(sql(), transferId); + return new Completion(transferId, transfer.get("source_digest", String.class), after.incarnationDigest(), round, deadline); + } + + long verificationCursor(UUID transferId) { + Record transfer = current(sql(), transferId, false); + requireComplete(sql(), transferId); + if (transfer.get("verification_round") == null) { + UUID round = UUID.randomUUID(); + sql().execute("UPDATE " + TRANSFER + " SET verification_round=?,verification_cursor=-1,verification_complete=false WHERE transfer_id=? AND verification_round IS NULL", round, transferId); + return -1; + } + return transfer.get("verification_cursor", Long.class); + } + + void retainVerification(Item item, CanonicalGameplayOriginalNewCapacityExecutionOwner.TransferFence actual, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after) { + requireObservation(readCurrent(item.transferId(), item.ordinal()), before); + requireObservation(readCurrent(item.transferId(), item.ordinal()), after); + if (!before.incarnationDigest().equals(after.incarnationDigest())) throw unavailable(); + sql().transaction(configuration -> { + var tx=DSL.using(configuration); + Record transfer=current(tx,item.transferId(),true); + if (!after.incarnationDigest().equals(transfer.get("incarnation_digest",String.class))) throw unavailable(); + Record row=tx.fetchSingle("SELECT fence_readback FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=?",item.transferId(),item.ordinal()); + if (!Arrays.equals(actual.canonicalReadback(),row.get("fence_readback",byte[].class))) throw unavailable(); + tx.execute("UPDATE " + ITEM + " SET verified_round=? WHERE transfer_id=? AND target_ordinal=?",transfer.get("verification_round",UUID.class),item.transferId(),item.ordinal()); + tx.execute("UPDATE " + TRANSFER + " SET verification_cursor=? WHERE transfer_id=? AND verification_cursor= proof.deadline || !sourceDigest(source, prior).equals(proof.sourceDigest)) throw unavailable(); + Record transfer = current(tx, proof.transferId, true); + if (!proof.incarnationDigest.equals(transfer.get("incarnation_digest", String.class)) + || !proof.round.equals(transfer.get("verification_round",UUID.class)) + || !Boolean.TRUE.equals(transfer.get("verification_complete",Boolean.class))) throw unavailable(); + requireComplete(tx, proof.transferId); + if (tx.execute("UPDATE " + TRANSFER + " SET state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=? WHERE transfer_id=? AND state='FROZEN'", newOwner, newFence, newLease, proof.transferId) != 1) throw unavailable(); + } + + static boolean frozen(DSLContext tx, UUID tenant, UUID game, UUID region) { + return tx.fetchExists(DSL.selectOne().from(DSL.table(TRANSFER)).where(DSL.field("tenant_id").eq(tenant)) + .and(DSL.field("game_instance_id").eq(game)).and(DSL.field("region_id").eq(region)).and(DSL.field("state").eq("FROZEN"))); + } + + /** Terminal originals need no new denial; close only the now-empty control intent atomically. */ + static void completeTerminalOnly(DSLContext tx,CanonicalGameplayRegionRuntimeStatus prior, + String newOwner,long newFence,String newLease) { + if(exists(tx,"SELECT 1"+PENDING,prior.tenantId(),prior.gameInstanceId(),prior.regionId())) throw unavailable(); + tx.execute("UPDATE " + TRANSFER + " SET state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=? WHERE tenant_id=? AND game_instance_id=? AND region_id=? AND old_owner_fence=? AND state='FROZEN'", + newOwner,newFence,newLease,prior.tenantId(),prior.gameInstanceId(),prior.regionId(),prior.executorFence().longValueExact()); + } + + @Override public Context readCurrent(UUID transferId, long targetOrdinal) { + if (admitted.get() == null) return within(Long.MAX_VALUE, ignored -> readCurrent(transferId, targetOrdinal)); + Record transfer = observationCurrent(sql(), transferId); + Record row = sql().fetchOne("SELECT execution_digest FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=?", transferId, targetOrdinal); + if (row == null) throw unavailable(); + Item item = loadItem(sql(), transferId, targetOrdinal, row.get("execution_digest", String.class)); + var binding = item.candidate().bindingIdentity(); + return new Context(transferId, targetOrdinal, transfer.get("intent_digest", String.class), transfer.get("source_digest", String.class), + transfer.get("old_owner_id", String.class), transfer.get("old_owner_fence", Long.class), binding.tenantId(), binding.gameInstanceId(), binding.regionId(), + transfer.get("region_epoch", Long.class), item.execution().transitionId(), item.execution().request().identity().requestId(), binding.accountId(), + binding.playableStateNamespaceId(), item.execution().digest(), item.execution().candidateDigest(), item.assignment().tenantGameplayTag(), item.assignment().workloadNamespace(), item.assignment().allocationVersion(), + transfer.get("state",String.class), completionDigest(transfer)); + } + + @Override public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId,CanonicalGameplayTenantGameplayTagRepository sourceTags) { + if(admitted.get()==null) return within(Long.MAX_VALUE,ignored -> readAssignment(transitionId,sourceTags)); + return sourceTags.withCapacityExecutionDsl(sql()).assignmentForTransition(transitionId); + } + + private static Record observationCurrent(DSLContext tx,UUID id) { + Record row=tx.fetchOne("SELECT t.*,r.* FROM " + TRANSFER + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND r.region_epoch=t.region_epoch AND ((t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence) OR (t.state='COMPLETED' AND r.owner_instance_id=t.new_owner_id AND r.executor_fence=t.new_owner_fence AND r.lease_token_correlation=t.new_lease_correlation))",id); + if(row==null) throw unavailable(); + var actual=CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row); + if(!"game-session-service".equals(actual.ownerService())) throw unavailable(); + String observed=sourceDigest(actual,row.get("old_owner_id",String.class),row.get("old_owner_fence",Long.class),row.get("old_lease_correlation",String.class)); + if(!observed.equals(row.get("source_digest",String.class))) throw unavailable(); + return row; + } + + private static String completionDigest(Record transfer) { + if(!"COMPLETED".equals(transfer.get("state",String.class))) return null; + return digest(bytes(transfer.get("transfer_id",UUID.class) + "/" + transfer.get("new_owner_id",String.class) + + "/" + transfer.get("new_owner_fence",Long.class) + "/" + transfer.get("new_lease_correlation",String.class))); + } + + private Item loadItem(DSLContext tx, UUID transferId, long ordinal, String executionDigest) { + Record row = tx.fetchOne("SELECT e.*,t.original_new_candidate_bytes FROM game_session_original_new_capacity_execution e JOIN game_session_canonical_binding_transition t ON t.transition_id=e.transition_id WHERE e.execution_digest=?", executionDigest); + if (row == null) throw unavailable(); + var candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical(row.get("original_new_candidate_bytes", byte[].class)); + var execution = decode(row.get("canonical_execution", byte[].class)); + if (!execution.digest().equals(executionDigest) || !execution.transitionId().equals(candidate.bindingDecisionId()) + || !execution.candidateDigest().equals(digest(candidate.canonicalBytes())) + || !execution.selectedOwnerId().equals(row.get("selected_owner_id",String.class)) + || execution.selectedOwnerFence()!=row.get("selected_owner_fence",Long.class) + || !execution.request().identity().requestId().equals(row.get("request_id",UUID.class)) + || !execution.request().admissionAttemptId().equals(row.get("admission_attempt_id",UUID.class))) throw unavailable(); + var assignment = tags.withCapacityExecutionDsl(sql()).assignmentForTransition(execution.transitionId()); + if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class))) throw unavailable(); + var binding = candidate.bindingIdentity(); + Record transfer=observationCurrent(tx,transferId); + if(!binding.tenantId().equals(transfer.get("tenant_id",UUID.class)) + || !binding.gameInstanceId().equals(transfer.get("game_instance_id",UUID.class)) + || !binding.regionId().equals(transfer.get("region_id",UUID.class)) + || binding.regionEpoch().longValueExact()!=transfer.get("region_epoch",Long.class) + || execution.selectedOwnerFence()>transfer.get("old_owner_fence",Long.class)) throw unavailable(); + Record retained=tx.fetchOne("SELECT * FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=?",transferId,ordinal); + if(retained==null || !executionDigest.equals(retained.get("execution_digest",String.class)) + || !Arrays.equals(execution.canonicalBytes(),retained.get("canonical_execution",byte[].class)) + || !execution.candidateDigest().equals(retained.get("candidate_digest",String.class)) + || !assignment.tenantGameplayTag().equals(retained.get("tenant_gameplay_tag",String.class)) + || !assignment.workloadNamespace().equals(retained.get("workload_namespace",String.class)) + || assignment.allocationVersion()!=retained.get("allocation_version",Integer.class)) throw unavailable(); + var player = (TenantCapacityAdmission.PlayerContext) execution.request().context(); + if (!binding.accountId().equals(player.accountId()) || !binding.tenantId().equals(player.tenantId()) + || !binding.gameInstanceId().equals(player.gameInstanceId()) || !binding.playableStateNamespaceId().equals(player.playableStateNamespaceId()) + || !binding.characterId().equals(player.characterId()) || !binding.sessionId().equals(player.sessionId().toString())) throw unavailable(); + return new Item(transferId, ordinal, execution, candidate, assignment); + } + + private static Record current(DSLContext tx, UUID id, boolean lock) { + Record row = tx.fetchOne("SELECT t.*,r.* FROM " + TRANSFER + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence AND r.region_epoch=t.region_epoch" + (lock ? " FOR UPDATE OF r,t" : ""), id); + if (row == null) throw unavailable(); + if (!sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row)).equals(row.get("source_digest",String.class))) throw unavailable(); + return row; + } + + private static void requireComplete(DSLContext tx, UUID id) { + Record transfer = current(tx, id, false); + boolean missing = exists(tx,"SELECT 1" + PENDING + + " AND NOT EXISTS (SELECT 1 FROM " + ITEM + " i WHERE i.transfer_id=? AND i.execution_digest=e.execution_digest AND i.canonical_execution=e.canonical_execution AND i.fence_readback IS NOT NULL AND i.incarnation_digest=?)", + transfer.get("tenant_id", UUID.class), transfer.get("game_instance_id", UUID.class), transfer.get("region_id", UUID.class), id, transfer.get("incarnation_digest", String.class)); + if (missing) throw unavailable(); + } + + private static void requireOldOwner(DSLContext tx, CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior) { + Record row = tx.fetchOne("SELECT * FROM game_session_region_runtime_status WHERE tenant_id=? AND game_instance_id=? AND region_id=? FOR UPDATE", source.tenantId(), source.gameInstanceId(), source.regionId()); + if (row == null || !prior.ownerInstanceId().equals(row.get("owner_instance_id", String.class)) + || prior.executorFence().longValueExact() != row.get("executor_fence", Long.class) + || prior.regionEpoch() != row.get("region_epoch", Long.class) + || !Arrays.equals(prior.lifecycleRequest().canonicalBytes(), row.get("lifecycle_request_bytes", byte[].class)) + || !sourceDigest(source,prior).equals(sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row)))) throw unavailable(); + } + + static String sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior) { + if (!source.tenantId().equals(prior.tenantId()) || !source.gameInstanceId().equals(prior.gameInstanceId()) + || !source.regionId().equals(prior.regionId()) || !source.canonicalRegionId().equals(prior.canonicalRegionId()) + || source.lifecycleEpoch() != prior.lifecycleEpoch() || source.lifecycleRowVersion() != prior.lifecycleRowVersion() + || !source.captureId().equals(prior.captureId()) || !source.graphSha256().equals(prior.graphSha256()) + || !source.preparationInputDigest().equals(prior.preparationInputDigest()) + || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId(source.lifecycleRequest(), prior.lifecycleRequest())) throw unavailable(); + return sourceDigest(prior); + } + + private static String sourceDigest(CanonicalGameplayRegionRuntimeStatus prior) { + return sourceDigest(prior,prior.ownerInstanceId(),prior.executorFence().longValueExact(),prior.leaseTokenCorrelation()); + } + + private static String sourceDigest(CanonicalGameplayRegionRuntimeStatus prior,String owner,long fence,String lease) { + return digest(bytes(prior.tenantId() + "/" + prior.gameInstanceId() + "/" + prior.regionId() + "/" + prior.canonicalRegionId() + + "/" + prior.lifecycleEpoch() + "/" + prior.lifecycleRowVersion() + "/" + Base64.getEncoder().encodeToString(prior.lifecycleRequest().canonicalBytes()) + + "/" + prior.captureId() + "/" + prior.graphSha256() + "/" + prior.preparationInputDigest() + "/" + prior.regionEpoch() + + "/" + prior.ownerService() + "/" + owner + "/" + fence + "/" + lease)); + } + + private void requireObservation(Context context, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation value) { + if (value.ownerKind() != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER + || !context.equals(value.regionOwnerTransferContext()) || clock.millis() >= value.expiresAtEpochMillis()) throw unavailable(); + } + + /** Strictly reconstruct the existing retained envelope; canonical re-encoding excludes alternate grammars. */ + static OriginalNewCapacityExecution decode(byte[] canonical) { + try { + if (canonical == null || canonical.length == 0 || canonical.length > 1048576) throw unavailable(); + JsonNode node = JSON.readTree(canonical); + byte[] payload = Base64.getDecoder().decode(node.get("canonicalAttemptPayload").textValue()); + var parser = new Frame(payload); + if (!"mutationDigest/v1".equals(parser.segment())) throw unavailable(); + Map fields = parser.fields(7, 0); + var scope = object(fields, "scope"); var target = object(fields, "target"); + var player = object(target, "ownerContext"); var expected = object(fields, "expectedVersion"); + var mutation = object(fields, "mutation"); + var identity = new TenantCapacityAdmission.Identity(uuid(scope,"tenantId"), uuid(scope,"requestId"), uuid(scope,"admissionId")); + var request = new TenantCapacityAdmission.Request(identity, uuid(expected,"admissionAttemptId"), number(expected,"capacityRearmFence"), text(target,"targetNamespace"), + new TenantCapacityAdmission.PlayerContext(uuid(player,"accountId"), uuid(player,"tenantId"), uuid(player,"playableStateNamespaceId"), uuid(player,"gameInstanceId"), uuid(player,"characterId"), uuid(player,"sessionId"), uuid(player,"realmId"), uuid(player,"requestId"), text(player,"playableStateScope")), + TenantCapacityAdmission.Operation.valueOf(text(mutation,"operation")), shape(object(mutation,"priorShape")), shape(object(mutation,"requestedShape")), + TenantCapacityAdmission.Evidence.parse(Base64.getDecoder().decode(text(mutation,"accountEvidence")), TenantCapacityAdmission.Owner.GAME_SESSION), number(mutation,"capacityDelta"), node.get("mutationDigest").textValue()); + if (!parser.done() || !Arrays.equals(payload, CapacityAdmissionDigest.preimage(request))) throw unavailable(); + var reservation = new TenantCapacityAdmission.Result(identity, request.admissionAttemptId(), request.capacityRearmFence(), request.mutationDigest(), UUID.fromString(node.get("reservationId").textValue()), Long.parseLong(node.get("reservationFence").textValue()), Instant.parse(node.get("expiresAt").textValue()), TenantCapacityAdmission.State.RESERVED, node.get("snapshotIdentity").textValue(), node.get("evaluationIdentity").textValue()); + var result = new OriginalNewCapacityExecution(request, reservation, UUID.fromString(node.get("transitionId").textValue()), node.get("candidateDigest").textValue(), node.get("selectedOwnerId").textValue(), Long.parseLong(node.get("selectedOwnerFence").textValue())); + if (!Arrays.equals(canonical, result.canonicalBytes())) throw unavailable(); + return result; + } catch (java.io.IOException | RuntimeException invalid) { throw unavailable(); } + } + + private static TenantCapacityAdmission.Shape shape(Map value) { return new TenantCapacityAdmission.Shape(number(value,"activeSessions"), number(value,"concurrentGameInstances"), number(value,"storageBytes")); } + @SuppressWarnings("unchecked") private static Map object(Map value,String key) { if (!(value.get(key) instanceof Map)) throw unavailable(); return (Map)value.get(key); } + private static String text(Map value,String key) { if (!(value.get(key) instanceof String text)) throw unavailable(); return text; } + private static long number(Map value,String key) { if (!(value.get(key) instanceof Long number)) throw unavailable(); return number; } + private static UUID uuid(Map value,String key) { return UUID.fromString(text(value,key)); } + private static byte[] bytes(String text) { return text.getBytes(StandardCharsets.UTF_8); } + private static String digest(byte[] value) { return "sha256:" + OriginalNewCapacityExecution.sha256(value); } + private static boolean exists(DSLContext tx,String query,Object... bindings) { return Boolean.TRUE.equals(tx.fetchSingle("SELECT EXISTS (" + query + ")",bindings).get(0,Boolean.class)); } + private static void noSql() { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); } + private static IllegalStateException unavailable() { return new IllegalStateException("Normal region owner transfer is held"); } + + private static final class Frame { + private final byte[] data; private int offset; + private Frame(byte[] data) { if (data.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES) throw unavailable(); this.data=data; } + private String segment() { + int start=offset; while (offset='0' && data[offset]<='9') offset++; + if (offset==start || offset>=data.length || data[offset++]!=':' || offset-start>8) throw unavailable(); + int size=Integer.parseInt(new String(data,start,offset-start-1,StandardCharsets.US_ASCII)); + if (size<0 || size>CapacityAdmissionDigest.MAX_SEGMENT_BYTES || size>data.length-offset) throw unavailable(); + String result=new String(data,offset,size,StandardCharsets.UTF_8); offset+=size; return result; + } + private Map fields(int count,int depth) { + if (count<0 || count>16 || depth>8) throw unavailable(); + Map result=new LinkedHashMap<>(); + for(int index=0;index=data.length || data[offset++]!='1') throw unavailable(); + String payload=segment(); Object value; + if (type.equals("object")) { Frame nested=new Frame(bytes(payload)); value=nested.fields(Integer.parseInt(nested.segment()),depth+1); if(!nested.done()) throw unavailable(); } + else if(type.equals("string")) value=payload; + else if(type.equals("number") && payload.matches("0|[1-9][0-9]{0,18}")) value=Long.parseLong(payload); + else throw unavailable(); + if(result.put(name,value)!=null) throw unavailable(); + } + return result; + } + private boolean done() { return offset==data.length; } + } + + record Item(UUID transferId,long ordinal,OriginalNewCapacityExecution execution,CanonicalGameplayOriginalNewCandidate candidate,CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) {} + static final class Completion { + private final UUID transferId; private final String sourceDigest; private final String incarnationDigest; private final UUID round; private final long deadline; + private Completion(UUID transferId,String sourceDigest,String incarnationDigest,UUID round,long deadline) { this.transferId=transferId;this.sourceDigest=sourceDigest;this.incarnationDigest=incarnationDigest;this.round=round;this.deadline=deadline; } + } +} 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 a39e13d8d0..d423fbfd21 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 @@ -678,6 +678,14 @@ CanonicalGameplayRegionRuntimeStatus installOwner( String ownerService, String ownerInstanceId, Instant now) { + return installOwner(source, expectedRegionEpoch, prior, leaseTokenCorrelation, + ownerService, ownerInstanceId, now, null); + } + + CanonicalGameplayRegionRuntimeStatus installOwner( + Source source, long expectedRegionEpoch, CanonicalGameplayRegionRuntimeStatus prior, + String leaseTokenCorrelation, String ownerService, String ownerInstanceId, Instant now, + CanonicalGameplayRegionOwnerTransferRepository.Completion transferProof) { requireNoAmbientTransaction(); Objects.requireNonNull(source, "source"); requireDigest(leaseTokenCorrelation); @@ -727,8 +735,9 @@ CanonicalGameplayRegionRuntimeStatus installOwner( throw unavailable(); } if (prior == null || !current.equals(prior)) throw unavailable(); - // The old generation owns any dispatched original effect until exact COMMITTED - // retention or irreversible CLOSED proof. Lease expiry alone cannot release it. + // Past-outcome custody remains with the original. Only exact terminal retention + // or privately qualified future exclusion permits this normal owner handoff. + // Lease expiry alone cannot satisfy either condition. // Capacity authorization takes this same row lock before creating that custody. if (transaction.fetchExists( DSL.selectOne() @@ -743,7 +752,8 @@ CanonicalGameplayRegionRuntimeStatus installOwner( .where(DSL.field("binding.tenant_id").eq(source.tenantId())) .and(DSL.field("binding.game_instance_id").eq(source.gameInstanceId())) .and(DSL.field("binding.region_id").eq(source.regionId())) - .and(DSL.field("execution.status").in("INSTALL_DISPATCHED", "AUTHORIZED")))) { + .and(DSL.field("execution.status").in("INSTALL_DISPATCHED", "AUTHORIZED"))) + && transferProof == null) { throw unavailable(); } } else if (prior != null || expectedRegionEpoch != 1L) { @@ -754,6 +764,16 @@ CanonicalGameplayRegionRuntimeStatus installOwner( transaction.fetchOne("SELECT nextval('" + FENCE_SEQUENCE + "') AS fence"); Long fence = fenceRow == null ? null : fenceRow.get("fence", Long.class); if (fence == null || fence <= 0L) throw unavailable(); + if (transferProof != null) { + if (current == null) throw unavailable(); + CanonicalGameplayRegionOwnerTransferRepository.requireAndComplete( + transaction, transferProof, source, current, ownerInstanceId, fence, + leaseTokenCorrelation, now); + } else if(current!=null && CanonicalGameplayRegionOwnerTransferRepository.frozen( + transaction,current.tenantId(),current.gameInstanceId(),current.regionId())) { + CanonicalGameplayRegionOwnerTransferRepository.completeTerminalOnly( + transaction,current,ownerInstanceId,fence,leaseTokenCorrelation); + } Record installed; if (current == null) { if (expectedRegionEpoch != 1L) throw unavailable(); @@ -845,7 +865,7 @@ CanonicalGameplayRegionRuntimeStatus installOwner( } } - private static CanonicalGameplayRegionRuntimeStatus toStatus(Record row) { + static CanonicalGameplayRegionRuntimeStatus toStatus(Record row) { return new CanonicalGameplayRegionRuntimeStatus( row.get("tenant_id", UUID.class), row.get("game_instance_id", UUID.class), diff --git a/services/game-session-service/src/main/resources/db/migration/V1065__original_new_capacity_owner_transfer_fencing.sql b/services/game-session-service/src/main/resources/db/migration/V1065__original_new_capacity_owner_transfer_fencing.sql new file mode 100644 index 0000000000..a9e129cbfb --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065__original_new_capacity_owner_transfer_fencing.sql @@ -0,0 +1,219 @@ +-- Future execution exclusion only. Account retains every unresolved reservation and full hold. +CREATE TABLE game_session_region_owner_transfer ( + transfer_id UUID PRIMARY KEY, + tenant_id UUID NOT NULL, + game_instance_id UUID NOT NULL, + region_id UUID NOT NULL, + region_epoch BIGINT NOT NULL CHECK (region_epoch > 0), + old_owner_id VARCHAR(120) NOT NULL CHECK (old_owner_id <> '' AND btrim(old_owner_id)=old_owner_id), + old_owner_fence BIGINT NOT NULL UNIQUE CHECK (old_owner_fence > 0), + old_lease_correlation CHAR(64) NOT NULL CHECK (old_lease_correlation ~ '^[0-9a-f]{64}$'), + source_digest VARCHAR(71) NOT NULL CHECK (source_digest ~ '^sha256:[0-9a-f]{64}$'), + intent_digest VARCHAR(71) NOT NULL CHECK (intent_digest ~ '^sha256:[0-9a-f]{64}$'), + state VARCHAR(16) NOT NULL CHECK (state IN ('FROZEN','COMPLETED')), + incarnation_digest VARCHAR(71) CHECK (incarnation_digest ~ '^sha256:[0-9a-f]{64}$'), + verification_round UUID, + verification_cursor BIGINT NOT NULL DEFAULT -1 CHECK (verification_cursor >= -1), + verification_complete BOOLEAN NOT NULL DEFAULT false, + new_owner_id VARCHAR(120), + new_owner_fence BIGINT CHECK (new_owner_fence > old_owner_fence), + new_lease_correlation CHAR(64) CHECK (new_lease_correlation ~ '^[0-9a-f]{64}$'), + FOREIGN KEY (tenant_id,game_instance_id,region_id) + REFERENCES game_session_region_runtime_status(tenant_id,game_instance_id,region_id), + CHECK ((state='COMPLETED') = (new_owner_id IS NOT NULL AND new_owner_fence IS NOT NULL AND new_lease_correlation IS NOT NULL)), + CHECK (state='COMPLETED' OR (new_owner_id IS NULL AND new_owner_fence IS NULL AND new_lease_correlation IS NULL)) +); +CREATE UNIQUE INDEX gs_region_owner_transfer_frozen_scope + ON game_session_region_owner_transfer(tenant_id,game_instance_id,region_id) WHERE state='FROZEN'; + +CREATE TABLE game_session_region_owner_transfer_item ( + transfer_id UUID NOT NULL REFERENCES game_session_region_owner_transfer(transfer_id), + target_ordinal BIGINT NOT NULL CHECK (target_ordinal >= 0), + execution_digest VARCHAR(71) NOT NULL REFERENCES game_session_original_new_capacity_execution(execution_digest), + canonical_execution BYTEA NOT NULL CHECK (octet_length(canonical_execution) BETWEEN 1 AND 1048576), + candidate_digest VARCHAR(71) NOT NULL CHECK (candidate_digest ~ '^sha256:[0-9a-f]{64}$'), + tenant_gameplay_tag VARCHAR(44) NOT NULL, + workload_namespace VARCHAR(253) NOT NULL, + allocation_version INTEGER NOT NULL CHECK (allocation_version > 0), + fence_readback BYTEA CHECK (octet_length(fence_readback) BETWEEN 1 AND 1048576), + incarnation_digest VARCHAR(71) CHECK (incarnation_digest ~ '^sha256:[0-9a-f]{64}$'), + before_payload_digest VARCHAR(71) CHECK (before_payload_digest ~ '^sha256:[0-9a-f]{64}$'), + after_payload_digest VARCHAR(71) CHECK (after_payload_digest ~ '^sha256:[0-9a-f]{64}$'), + verified_round UUID, + PRIMARY KEY (transfer_id,target_ordinal), + UNIQUE (transfer_id,execution_digest), + CHECK ((fence_readback IS NULL AND incarnation_digest IS NULL AND before_payload_digest IS NULL AND after_payload_digest IS NULL) + OR (fence_readback IS NOT NULL AND incarnation_digest IS NOT NULL AND before_payload_digest IS NOT NULL AND after_payload_digest IS NOT NULL)), + CHECK (verified_round IS NULL OR fence_readback IS NOT NULL) +); +CREATE INDEX gs_original_new_capacity_unresolved_transition + ON game_session_original_new_capacity_execution(transition_id,execution_digest) + WHERE status IN ('INSTALL_DISPATCHED','AUTHORIZED'); + +-- [jooq ignore start] +CREATE FUNCTION guard_gs_region_owner_transfer() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='DELETE' THEN + RAISE EXCEPTION 'Region owner transfer custody is retained' USING ERRCODE='23514'; + END IF; + IF ROW(NEW.transfer_id,NEW.tenant_id,NEW.game_instance_id,NEW.region_id,NEW.region_epoch, + NEW.old_owner_id,NEW.old_owner_fence,NEW.old_lease_correlation,NEW.source_digest,NEW.intent_digest) + IS DISTINCT FROM ROW(OLD.transfer_id,OLD.tenant_id,OLD.game_instance_id,OLD.region_id,OLD.region_epoch, + OLD.old_owner_id,OLD.old_owner_fence,OLD.old_lease_correlation,OLD.source_digest,OLD.intent_digest) + OR (OLD.state='COMPLETED' AND NEW IS DISTINCT FROM OLD) + OR (OLD.incarnation_digest IS NOT NULL AND NEW.incarnation_digest IS DISTINCT FROM OLD.incarnation_digest) + OR (OLD.verification_round IS NOT NULL AND NEW.verification_round IS DISTINCT FROM OLD.verification_round) + OR NEW.verification_cursor'FROZEN' THEN + RAISE EXCEPTION 'Completed transfer cannot acquire or change custody' USING ERRCODE='23514'; + END IF; + IF TG_OP='INSERT' AND NOT EXISTS ( + SELECT 1 FROM game_session_original_new_capacity_execution e + JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=e.transition_id + JOIN game_session_canonical_binding_transition t ON t.transition_id=e.transition_id + WHERE e.execution_digest=NEW.execution_digest AND e.canonical_execution=NEW.canonical_execution + AND e.tenant_gameplay_tag=NEW.tenant_gameplay_tag AND t.original_new_candidate_digest=NEW.candidate_digest + AND b.tenant_id=parent.tenant_id AND b.game_instance_id=parent.game_instance_id AND b.region_id=parent.region_id) THEN + RAISE EXCEPTION 'Transfer item differs from original region execution' USING ERRCODE='23514'; + END IF; + IF TG_OP='UPDATE' AND ( + ROW(NEW.transfer_id,NEW.target_ordinal,NEW.execution_digest,NEW.canonical_execution,NEW.candidate_digest, + NEW.tenant_gameplay_tag,NEW.workload_namespace,NEW.allocation_version) + IS DISTINCT FROM ROW(OLD.transfer_id,OLD.target_ordinal,OLD.execution_digest,OLD.canonical_execution,OLD.candidate_digest, + OLD.tenant_gameplay_tag,OLD.workload_namespace,OLD.allocation_version) + OR (OLD.fence_readback IS NOT NULL AND ROW(NEW.fence_readback,NEW.incarnation_digest,NEW.before_payload_digest,NEW.after_payload_digest) + IS DISTINCT FROM ROW(OLD.fence_readback,OLD.incarnation_digest,OLD.before_payload_digest,OLD.after_payload_digest)) + OR (OLD.verified_round IS NOT NULL AND NEW.verified_round IS DISTINCT FROM OLD.verified_round)) THEN + RAISE EXCEPTION 'Transfer original and retained fence receipt are immutable' USING ERRCODE='23514'; + END IF; + IF NEW.verified_round IS NOT NULL AND NEW.verified_round IS DISTINCT FROM parent.verification_round THEN + RAISE EXCEPTION 'Transfer verification round differs from current intent' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE FUNCTION reject_gs_region_owner_transfer_truncate() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Region owner transfer custody is retained' USING ERRCODE='23514'; +END; +$$; +CREATE TRIGGER gs_region_owner_transfer_guard BEFORE UPDATE OR DELETE ON game_session_region_owner_transfer + FOR EACH ROW EXECUTE FUNCTION guard_gs_region_owner_transfer(); +CREATE TRIGGER gs_region_owner_transfer_item_guard BEFORE INSERT OR UPDATE OR DELETE ON game_session_region_owner_transfer_item + FOR EACH ROW EXECUTE FUNCTION guard_gs_region_owner_transfer_item(); +CREATE TRIGGER gs_region_owner_transfer_no_truncate BEFORE TRUNCATE ON game_session_region_owner_transfer + FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_region_owner_transfer_truncate(); +CREATE TRIGGER gs_region_owner_transfer_item_no_truncate BEFORE TRUNCATE ON game_session_region_owner_transfer_item + FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_region_owner_transfer_truncate(); + +CREATE FUNCTION fence_gs_capacity_dispatch_during_transfer() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE scope RECORD; +BEGIN + SELECT DISTINCT tenant_id,game_instance_id,region_id INTO STRICT scope + FROM game_session_canonical_binding_region_bridge_obligation WHERE transition_id=NEW.transition_id; + PERFORM 1 FROM game_session_region_runtime_status r + WHERE r.tenant_id=scope.tenant_id AND r.game_instance_id=scope.game_instance_id AND r.region_id=scope.region_id FOR UPDATE; + IF EXISTS (SELECT 1 FROM game_session_region_owner_transfer t WHERE t.tenant_id=scope.tenant_id + AND t.game_instance_id=scope.game_instance_id AND t.region_id=scope.region_id AND t.state='FROZEN') THEN + RAISE EXCEPTION 'Region dispatch is frozen for normal owner transfer' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER gs_capacity_dispatch_transfer_fence BEFORE INSERT ON game_session_original_new_capacity_execution + FOR EACH ROW EXECUTE FUNCTION fence_gs_capacity_dispatch_during_transfer(); + +CREATE FUNCTION require_gs_region_owner_transfer_custody() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF ROW(NEW.executor_fence,NEW.owner_instance_id,NEW.lease_token_correlation) + IS NOT DISTINCT FROM ROW(OLD.executor_fence,OLD.owner_instance_id,OLD.lease_token_correlation) THEN RETURN NEW; END IF; + IF EXISTS (SELECT 1 FROM game_session_region_owner_transfer t WHERE t.tenant_id=OLD.tenant_id + AND t.game_instance_id=OLD.game_instance_id AND t.region_id=OLD.region_id AND t.state='FROZEN') THEN + RAISE EXCEPTION 'Region transfer must complete with owner installation' USING ERRCODE='23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_session_original_new_capacity_execution e + JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=e.transition_id + WHERE b.tenant_id=OLD.tenant_id AND b.game_instance_id=OLD.game_instance_id AND b.region_id=OLD.region_id + AND e.status IN ('INSTALL_DISPATCHED','AUTHORIZED')) AND NOT EXISTS ( + SELECT 1 FROM game_session_region_owner_transfer t WHERE t.tenant_id=OLD.tenant_id + AND t.game_instance_id=OLD.game_instance_id AND t.region_id=OLD.region_id + AND t.region_epoch=OLD.region_epoch AND t.old_owner_id=OLD.owner_instance_id AND t.old_owner_fence=OLD.executor_fence + AND t.old_lease_correlation=OLD.lease_token_correlation AND t.state='COMPLETED' + AND t.new_owner_id=NEW.owner_instance_id AND t.new_owner_fence=NEW.executor_fence + AND t.new_lease_correlation=NEW.lease_token_correlation AND t.verification_complete) THEN + RAISE EXCEPTION 'Region owner replacement lacks exact transfer custody' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER gs_region_owner_transfer_custody BEFORE UPDATE ON game_session_region_runtime_status + FOR EACH ROW EXECUTE FUNCTION require_gs_region_owner_transfer_custody(); + +INSERT INTO game_session_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +VALUES ('game_session_region_owner_transfer','game_session_region_owner_transfer','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED', + 'Normal-handoff dispatch freeze and exact successor custody are retained. Future exclusion is not an execution outcome or Account release authority.'), + ('game_session_region_owner_transfer_item','game_session_region_owner_transfer_item','CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED', + 'Exact original execution, current storage-bound denial and bounded verification remain retained. Never clone, discard from expiry, or infer non-execution from missing storage.'); + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1064' + );$needle$; + replacement := $replacement$WHERE version='1064' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065__original_new_capacity_owner_transfer_fencing.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065' + );$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog frontier'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1064'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1064','V1064__restore_final_human_completion_lower_bound.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065'',''V1065__original_new_capacity_owner_transfer_fencing.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua index da519f3890..a7578545b6 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua @@ -1,6 +1,7 @@ -- Final original-NEW controller boundary. All seven keys share the persisted tenant slot. --- The two OPEN barriers are checked only. The only write replaces the exact non-admitting --- session candidate and its capacity outcome; all three installed tenant indexes remain exact. +-- FINAL checks both OPEN barriers and replaces only the exact non-admitting session candidate +-- and capacity outcome. FENCE denies future execution without asserting historical non-execution; +-- it writes only the capacity outcome. All three installed tenant indexes remain exact. local admissionPlaceholder = '__ORIGINAL_NEW_ADMISSION_AT_MS__' local continuityPlaceholder = '__ORIGINAL_NEW_CONTINUITY_EXPIRES_AT_MS__' local accountNames = {'schema', 'accountId', 'tenantId', 'playableStateNamespaceId', @@ -63,7 +64,7 @@ local function decode(bytes, maximum) end if #KEYS ~= 7 or #ARGV ~= 19 then return -2 end local capacityBytes, action, capacityDigest = ARGV[17], ARGV[18], ARGV[19] -if action ~= 'FINAL' and action ~= 'INSTALL' and action ~= 'CLOSE' then return -2 end +if action ~= 'FINAL' and action ~= 'INSTALL' and action ~= 'CLOSE' and action ~= 'FENCE' then return -2 end local capacity = decode(capacityBytes, 1048576) if not capacity or capacity.schema ~= 'gs-original-new-capacity-execution/v1' or type(capacityDigest) ~= 'string' or #capacityDigest ~= 71 @@ -96,6 +97,49 @@ if KEYS[1] ~= prefix .. slot .. ':' .. gameInstanceId .. ':' .. sessionId or KEYS[6] ~= prefix .. 'issuer-admission:' .. slot .. ':firemud-account-service:' .. tenantId .. ':' .. namespaceId or KEYS[7] ~= prefix .. 'capacity-execution:' .. slot .. ':' .. capacity.admissionAttemptId or capacity.tenantId ~= tenantId then return -2 end +-- Only a separately qualified current incarnation may dispatch FENCE during normal owner handoff. +-- It excludes future execution, including delayed old callers, but never proves no earlier commit. +if action == 'FENCE' then + local capacityNames = {'schema', 'tenantId', 'requestId', 'admissionId', 'admissionAttemptId', + 'reservationId', 'reservationFence', 'capacityRearmFence', 'selectedOwnerId', + 'selectedOwnerFence', 'transitionId', 'expiresAtMillis'} + if not objectWithFields(capacity, capacityNames) then return -2 end + local capacityType = redis.call('TYPE', KEYS[7]).ok + if capacityType ~= 'none' then + if capacityType ~= 'hash' or redis.call('PTTL', KEYS[7]) ~= -1 + or redis.call('HGET', KEYS[7], 'binding') ~= capacityBytes + or redis.call('HGET', KEYS[7], 'digest') ~= capacityDigest then return -1 end + local state, fields = redis.call('HGET', KEYS[7], 'state'), redis.call('HLEN', KEYS[7]) + if state == 'COMMITTED' then + local sessionSha1 = redis.call('HGET', KEYS[7], 'sessionSha1') + local admissionAt = exactNumber(redis.call('HGET', KEYS[7], 'admissionAt')) + local continuity = exactNumber(redis.call('HGET', KEYS[7], 'continuityExpiresAt')) + if fields ~= 6 or type(sessionSha1) ~= 'string' or #sessionSha1 ~= 40 + or not string.match(sessionSha1, '^[0-9a-f]+$') or not admissionAt or not continuity + or continuity <= admissionAt or continuity - admissionAt > 300000 then return -1 end + return 2 + end + if fields ~= 3 then return -1 end + -- Completed exact outcomes are read-only, even after the operation deadline. + if state == 'FENCED_INDETERMINATE' then return 5 end + if state == 'CLOSED' then return 4 end + if state ~= 'AUTHORIZED' then return -1 end + end + local fenceTime = redis.call('TIME') + local fenceSeconds, fenceMicros = tonumber(fenceTime[1]), tonumber(fenceTime[2]) + if not fenceSeconds or not fenceMicros or fenceSeconds < 1 or fenceSeconds ~= math.floor(fenceSeconds) + or fenceSeconds > math.floor((9007199254740991 - 999) / 1000) + or fenceMicros < 0 or fenceMicros >= 1000000 or fenceMicros ~= math.floor(fenceMicros) then return -1 end + local fenceNow = fenceSeconds * 1000 + math.floor(fenceMicros / 1000) + if fenceNow <= 0 or fenceNow >= deadline then return -1 end + if capacityType == 'none' then + redis.call('HSET', KEYS[7], 'binding', capacityBytes, 'digest', capacityDigest, + 'state', 'FENCED_INDETERMINATE') + else + redis.call('HSET', KEYS[7], 'state', 'FENCED_INDETERMINATE') + end + return 5 +end -- Closure uses retained SQL attempt/candidate identity, not a fresh credential or OPEN grant. -- It remains available after process restart/credential expiry and never infers from absence. if action == 'CLOSE' then diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json index 25ec2651bd..42b71ac832 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.original-new-final-admission.v1", "resourcePath": "redis/lua/game-session-original-new-final-admission.lua", - "sha256": "224ffb4457c1c6113b1c76b0b9ac1e42c5016b3d51a9c1b1ac51688d2731acbc", + "sha256": "a9c4f5505d12ed4a06cc96f4ab29c5738889ebb5c9321536b084fa82faa273d4", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -123,6 +123,11 @@ "category": "SUCCESS", "effect": "MUTATING" }, + { + "code": "CAPACITY_EXECUTION_FENCED_INDETERMINATE", + "category": "SUCCESS", + "effect": "MUTATING" + }, { "code": "CURRENT_PHYSICAL_STATE_REFUSED", "category": "STALE", @@ -136,7 +141,7 @@ ], "resetSensitivity": "CLUSTER", "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", - "tailLossBehavior": "Missing capacity execution remains indeterminate and cannot be reinstalled by retry. CLOSED is irreversible and fences every delayed same-attempt FINAL. Account alone consumes exact terminal evidence to mutate capacity. A missing or changed candidate, tenant index, OPEN barrier, or Redis state fails closed. Exact retry is read-only and preserves the first Redis TIME values; the script never repairs indexes, recreates barriers, transfers a controller, or claims that the supplied OPEN sources establish the complete admission flow. The owner returns evidence only after independent exact physical readback. Reset-sensitive state requires its owning recovery before the final consumer can proceed.", + "tailLossBehavior": "Missing capacity execution remains historically indeterminate and cannot be reinstalled as AUTHORIZED by retry. Under separately qualified current-incarnation normal owner handoff only, FENCE creates or retains an exact persistent FENCED_INDETERMINATE deny, excluding delayed INSTALL/FINAL without claiming no earlier execution, permitting reset adoption, or authorizing Account release/rearm. FENCE preserves exact COMMITTED and CLOSED outcomes; first mutation must meet the frozen Redis TIME deadline and completed exact replay is read-only. CLOSED is irreversible and fences every delayed same-attempt FINAL. Account alone consumes exact terminal evidence to mutate capacity. A missing or changed candidate, tenant index, OPEN barrier, or Redis state fails closed for admission. Exact final retry is read-only and preserves the first Redis TIME values; the script never repairs indexes, recreates barriers, transfers a controller, or claims that the supplied OPEN sources establish the complete admission flow. The owner returns evidence only after independent exact physical readback. Reset-sensitive state requires its owning recovery before the final consumer can proceed.", "compatibilityLevel": "REQUIRES_CLUSTER_RESET", "supportedCoexistence": [ { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture.java new file mode 100644 index 0000000000..2e454b2eaa --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** + * Controlled transfer-purpose signer custody only. Actual FROZEN or sealed-COMPLETED context and + * mapping must come from the SQL owners and are independently rechecked by the real receiver. + * COMPLETED observations supply read-only currentness, never mutation authority. This fixture + * supplies no transfer outcome, Account settlement, deployment custody or reset proof. + */ +final class CanonicalGameplayControlledRegionTransferObservationFixture { + private static final String KEY_ID = "controlled-region-transfer-attestor"; + private static final String BINDING = "controlled-region-transfer-attestor-binding"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final KeyPair keys; + private final Clock clock; + + CanonicalGameplayControlledRegionTransferObservationFixture() throws Exception { + this(Clock.systemUTC()); + } + + CanonicalGameplayControlledRegionTransferObservationFixture(Clock clock) throws Exception { + this.clock = Objects.requireNonNull(clock, "clock"); + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + keys = generator.generateKeyPair(); + } + + CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayRegionOwnerTransferObservationSource source, + CanonicalGameplayTenantGameplayTagRepository tags) { + return receiver(source, tags, "storage-1"); + } + + CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayRegionOwnerTransferObservationSource source, + CanonicalGameplayTenantGameplayTagRepository tags, + String storageGeneration) { + var expected = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-transfer-target", + "generation-1", + List.of("redis-node-a"), + "controlled-redis-build", + "controlled-registry-v1", + "sha256:" + "d".repeat(64), + "READY", + "boot-1", + "startup-1", + storageGeneration, + "aof-1"); + var trust = + new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + BINDING, + "sha256:" + "a".repeat(64), + Map.of(KEY_ID, (RSAPublicKey) keys.getPublic()), + expected, + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64), + 16 * 1024, + 1, + Duration.ofSeconds(30)); + return CanonicalGameplayProtectedIncarnationReceiver.forRegionOwnerTransfer( + source, tags, this::observe, trust, clock); + } + + private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + var context = request.context(); + if (context.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER) { + throw new IllegalArgumentException("Controlled channel is limited to transfer observations"); + } + var transfer = context.regionOwnerTransferContext(); + Map owner = new LinkedHashMap<>(); + owner.put("ownerKind", context.ownerKind().name()); + owner.put("transferId", transfer.transferId().toString()); + owner.put("transferIntentDigest", transfer.transferIntentDigest()); + owner.put("frozenSourceDigest", transfer.frozenSourceDigest()); + owner.put("oldRegionOwnerId", transfer.oldRegionOwnerId()); + owner.put("oldRegionOwnerFence", transfer.oldRegionOwnerFence()); + owner.put("gameInstanceId", transfer.gameInstanceId().toString()); + owner.put("regionId", transfer.regionId().toString()); + owner.put("regionEpoch", transfer.regionEpoch()); + owner.put("transitionId", transfer.transitionId().toString()); + owner.put("requestId", transfer.requestId().toString()); + owner.put("accountId", transfer.accountId().toString()); + owner.put("executionDigest", transfer.executionDigest()); + owner.put("candidateDigest", transfer.candidateDigest()); + owner.put("controlState", transfer.controlState()); + owner.put("completionDigest", transfer.completionDigest()); + Map target = new LinkedHashMap<>(); + target.put("targetOrdinal", context.targetOrdinal()); + target.put("tenantId", context.tenantId().toString()); + target.put("playableStateNamespaceId", context.playableStateNamespaceId().toString()); + target.put("tenantGameplayTag", context.tenantGameplayTag()); + target.put("workloadNamespace", context.workloadNamespace()); + target.put("allocationVersion", context.allocationVersion()); + var evidence = request.expectedEvidence(); + Map deployment = new LinkedHashMap<>(); + deployment.put("deploymentIdentity", evidence.deploymentIdentity()); + deployment.put("deploymentGeneration", evidence.deploymentGeneration()); + deployment.put("canonicalNodeSet", evidence.canonicalNodeSet()); + deployment.put("redisBuildIdentity", evidence.redisBuildIdentity()); + deployment.put("luaScriptRegistryVersion", evidence.luaScriptRegistryVersion()); + deployment.put("luaScriptRegistryDigest", evidence.luaScriptRegistryDigest()); + deployment.put("startupState", evidence.startupState()); + deployment.put("bootGeneration", evidence.bootGeneration()); + deployment.put("startupGeneration", evidence.startupGeneration()); + deployment.put("storageGeneration", evidence.storageGeneration()); + deployment.put("aofGeneration", evidence.aofGeneration()); + Map root = new LinkedHashMap<>(); + root.put("schema", "firemud.gs.protected-region-owner-transfer-read/v1"); + root.put("attestorBinding", request.attestorBinding()); + root.put("attestorKeyId", KEY_ID); + root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); + root.put("observationNonce", request.nonce()); + root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis()); + root.put("owner", owner); + root.put("target", target); + root.put("targetDeploymentEvidence", deployment); + root.put("coordOpsRoAclDigest", request.coordOpsRoAclDigest()); + root.put("coordRedisConfigObservedDigest", request.coordRedisConfigObservedDigest()); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keys.getPrivate()); + signer.update(canonical); + return new CanonicalGameplayProtectedIncarnationReceiver.SignedObservation( + KEY_ID, canonical, signer.sign()); + } catch (java.security.GeneralSecurityException | java.io.IOException failure) { + throw new IllegalStateException("Controlled transfer observation signing failed", failure); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java index 0c2ba1b9d9..79a1bd1f52 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 @@ -667,6 +667,43 @@ public Candidate candidate() { return binding.candidate(); } + /** Real Account hold/credential and GS authorization, intentionally stopped before FINAL. */ + public net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result + authorizeThenFenceAndHandoffWithoutFinal( + AccountGameplayAdmissionLeaseClient account,AccountPublicJwksCache jwks, + String originalLoginJwt, + net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient capacityClient, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, + long deadline) throws Exception { + var inventory=new CanonicalGameplayBindingInventoryRepository(binding.dsl()); + var source=inventory.readOriginalNewFinalAdmissionSource(decision); + var executionOwner=new CanonicalGameplayOriginalNewCapacityExecutionOwner( + binding.dsl(),coordination,scripts,CLOCK,tags); + var reservation=capacityClient.commit(request,deadline); + var execution=executionOwner.bind(source,request,reservation,deadline); + var issuerSource=binding.currentIssuerSource(); + var issuer=new CanonicalGameplayIssuerAdmissionBarrierRedisOwner(coordination,scripts, + new CanonicalGameplayIssuerAdmissionBarrierRepository(binding.dsl(),tags,issuerSource),issuerSource); + try(var credential=account.issueOriginalNewBoundGameplayCredential(originalLoginJwt, + decision.leaseEvidence().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var raw=CanonicalGameplayOriginalNewAuthenticatedSession.template(source.candidate(),credential, + new CanonicalGameplayOriginalNewBoundCredentialVerifier(jwks,CLOCK),120_000L); + var template=raw.bindCapacityExecution(execution)) { + var current=initialOwner().verifyCurrentOpenForTarget(request.context() instanceof net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext player ? player.accountId() : null, + request.identity().tenantId(),source.candidate().bindingIdentity().playableStateNamespaceId()); + if(!(current instanceof CanonicalGameplayAccountInitialOpenProof.CurrentOpen open)) + throw new IllegalStateException("Actual INITIAL source is not OPEN"); + executionOwner.authorize(source,template,open,issuer.initializeAndRead(source.issuerAcknowledgement().operationId()),execution,deadline); + } + var repository=new CanonicalGameplayRegionOwnerTransferRepository(binding.dsl(),CLOCK,tags); + var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); + var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(binding.dsl(),CLOCK,repository,executionOwner,receiver); + administration.sync().pexpire(ascii(regionInstallation.grant.key()),0); + regionInstallation=CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + binding.dsl(),coordination,scripts,regionInstallation,sources.resolver,transfer,deadline); + return reservation; + } + public Target target() { return binding.target(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java index 7016ecf7e6..d98d8bf773 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java @@ -12,14 +12,17 @@ import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.CommandType; +import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.Duration; +import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.zip.GZIPInputStream; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution; @@ -57,6 +60,68 @@ class CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest { private static final long DURATION_MILLIS = 120_000L; private static final byte[] ISSUER_PAYLOAD = new byte[] {0, 1, 2, 0, (byte) 0xff, 13, 10}; private static final JsonMapper JSON = JsonMapper.builder().build(); + // Immutable pre-FENCE production source, gzip/base64 encoded to keep the pinned fixture compact. + // Decode and verify its original descriptor digest before loading it into actual Redis. + private static final String PRE_FENCE_LUA_SHA256 = + "224ffb4457c1c6113b1c76b0b9ac1e42c5016b3d51a9c1b1ac51688d2731acbc"; + private static final String PRE_FENCE_LUA_GZIP_BASE64 = + """ + H4sIAAAAAAACA90ba3PbNvK7fwXGuY7MRlIlW3biNPaM4yiJpn7kLLW9NuPTwCIksaFIHR9+pNP77beLFwESpOW0/XLJTEKC + u4vdxWKxD6jTIe+CiIYkToIFPnQuhj+TWRxlSRyGLCE3cR75NHnokpMwJCm7ZRH5zB5Ski5pwki2ZGTNkjRIM+aTjEU0ykga + xll3q9MhE/ia3cXk8uPwgtzQJAkAlCDebMlmnwEjjkIgjXD4RO6SIGMkYeuQzljKqbN7OstIFEcd6q+CLAuiBZJOWZoGcURm + NPIDnwIWPJAgS2FkTWdB9kDiPJvFK/Y9ocB5tkwYI0GUZvBWsBpEPruHmRK2okEkJutuhfEMVILz8Uk+IjfLOPRBH0ekNZ1e + Xo3ejy5OzqagrOnJ2/PReDy6vJieTKbn4+m0JfFRi0GUAyvNBE4vLyajix9Hk1+mw399HF0Nx2VKdDaDZcgu6ApYPSK/t1LQ + 34q22qQlP418fBFCiWdQ4QO9Cdk4A+VwTFALw29bREG+h2GEm9AFosR3EUsuYTlpBlILMnzsHYtmbLiOZ0scCqIZTSIO8zZY + sDTDwRSnaf0hGQa95Sxx8Su+/CXsiilRB2qhNIsuSYIoyAIaBl9KX5C+8c0QU48VYq7pQxhTvzJQkvycZRSMkv7fa0CJLbdj + Wd6f0DXEkcXiWDGtXM6p2sI4eAM7Erb4exZJBgV7ysxxu2oCUpPWWMIWgPQmCfwFG1fUc8JFoHm2nMSfWfSBpktJXw2NkKZf + ghver4OEpWI0wxGTP8EIhS3C94ngAuX4AIKFTExQOIM3QkKL5oqtbkBVy2D9hqYsDCKm5gclZQ+TfB0KleXZTXx/is5zHQdR + lkriFPxjAOswFsvwNhe8nQdhGKSIqJzi8J7NcmPnqvWb59EMh0meB/7OLQ1z5gHlhGV5EpHsYc3kIDk6QrtLQIIWd7nP+DgO + 7x3wAf0uoLphfMeSgiQxgP4LtHryT8fxj/rT0niS5opms6WgCcL9+5v70t/Ohk+lv/9oechTFIRbLPLLqlnHKeyHW/Y16jkm + PfP19RHZ3T94RKpP/c7h9ace/PNtM2P81LrI0YQK3oI5HJpZmWk45wuW+gd4wkZKDKBOkDohgn7EKcJuzuLITVxCAE35dEwO + e70X/cPD3f3Bi0Hv8LCPH6V48zgBCXda33R7c7BJgcLlEgy5eVEDHNolfXzzG5tlPwfZ8l3AQj9VCpzzN8mtuURodRl62pY1 + 5ZyGKbMUwF0OyN+DEWAe4542hBhsBWEDWdMgSRVJP+ZrqRDE/89Jn49KfjGQgm98Gj6OJKegB/CZSDAQFCXbQBL5hinRpDgM + Z1aRyZKcMysZ1ksivgNlziegzn5L46gb5TwGcksr/gUCgm/QzzPBRS3GJqxz1XxCkGsuQlDDgL3OKJfTxv+T03AnZPOsTeDc + WMJ/PltnS7m+/BnM72CAsvPVRli+2PyN43i1AikT0UguC8GPKAqnVbWUM84cf7ziEGA5bdt4hKFr6xGzmcZzxqcwnpURyeUV + apAWzvn4BISvpTIQ2ntkmfnSFSxIvcCSWYwbL0DTXiKDURPQtWo+m8U+27l5yFjaJit6H6zylbkl+RehcOU10UPxYSTfM16P + FYFGrxV/Vmo+ImsYCHfEDhCstImYsfBh8WdtMc3+oeKSODiXGkg9+2H4yxhRX3COT67e/4Rv/UOLRmeXFFpSZ/IboR3KVdbW + w+KEBimQ1qf+C1hk8fRSPx1e49QCkbP9DpMKcfAYo6OL8eTkrDp+enY5HrYeZxB4kAtZYrnfG7zcf3HgbUldFqlXop+7IhLk + Ey7Sjs4zI3bXUTAdpsKS72774rBXa2Jro2opJW3hAvQVAWTJOlptYDxjIYuFg/gVnrK0M79+Dgetic2jIS1JArsP8Ea+5/6u + w0yAqKdiBKPgotf15CA6ZMmtjNI9p1a6ECzC4cf8Swz3kVKdfsqQ5DXpNwNAfLDbqxcjS2iEoUVFWh1xaFD1cMVosuIxslcP + bEgtQJtpW1xL2o8aNI+90azNyEmTZCoyF+Fzxboldu0sKqlrE52ci6NSJnSwxZc0gYm5mtX+Vpt6Vz3sqYfBtSS8ABojrGBE + goxMuvBxofORNsnoQlHdVzQO1IN2Iy+vtVJk+iU3tWZOvqORhuqzInyofVBPP/UVRT9XrPiM+pjNlFQt4HevvbZjeP9aa5xb + nFKnvUu0au1hQ82lXVWovLo3bcXaiFrJVZstlG7vTliA6kbEVTkmg0GtcwIA9EgLI+z/plPnmJSK8V0/H5M9ni5pIKV9h6mq + A1jo/OC6yrD6UhzDeuSY7O8Odl++rN8D64TNg3ssdkn9vUIdv1IFLawQ4sffW6Tb5QYL/7X+aCFbeJDCdkB+JBX4xhEQ5hXH + sBfM+KBXSymLU9stUWvxst8rbRMS157DMCVj1LAja4o99xTSTDvCiJ3zaEu26A3c9Mp0LJz9Mo6aXR85zQy4hbemOKiwxWsw + 9TPMwZWucr+jWEHnHsyYAFNbe4OJX5QnrsYOTuEajl1FvzjSFDuYNKhnh4l3OuQ0jNM8YSRPefE4o7DNfDL+5xmhgvx3RWE6 + 8FmUAf0235SUzOFwWZJZwvg4r72LCvkCjlRROB9lsiKdEnpLgxCjUULnYHaggngGRg7fwfwTmKegw8TBhFFexG4BNojmWHCf + J/GK0JsUT8euETEe2TGgiImBXJB2eeDcmvzycQiZulwArwuxMnqJJZbNkGsT9uNkcmbAImBHRGKkDPrh/XBSgBZFP1HksGLM + DQn4oppl4cuI0Fq/vpUq8PIpuKFG0qLGKhMGiaH09laE1Bb+2fDCVAPWxSweBkXGaVC7PD8fTSYbErTLNrtlgrhEJz9OPlxe + jX5FimXllQgC+J5bzeby94vlNw6JOgPoNxuAoWMJaQchj7Oz+yR2djdmR0LaMdDj7OwZ7LCskZe9Zl7Go/H58PzN8KqANwI9 + jtp/nJ/B5vwMnsjPoMqPe4+hl4whdGTYGeQtPXBNN/EtOET0XtTvYMvve3SIQQIble8ossozEcyschhbMYY7GBBi1bBopTqu + 6Rb1F3DHbBKsyrt5Mjof8r1rgI0hlY18DHTx7TyYJXFqFjk1LbTNtmscjKSoH5g0VeBlUsYDxgSReZc1BkqEGHDZnYdxLCeS + n7xiVSyMYxNhp1J07ZDDw0OPfAcZeq9XpiEZey2iOnPo+IgjyBDS/OLgUHzxmhwsh7uI77CgZHL/LZ+GPK+hafCNRUlF5PWR + wTEOHB/VhLhFwcpwe2OnY29rV24U9AdbZs6oznGjCmJnTCIY9nT6J/KlAt7KoIyqidXcLcBFmI37vn+w93LgWZ3FMhhux2oZ + RrHMoxv50l3nCaQu4nywyjBWc72jEcxaDK+UlQvtSq621f7zGnGktG2rp92MIgRvu1qrRd4lWelafUcUddf6bHchRRXs8vzj + 2XAybFVoGSEjQjrvA5jw9T0+fqa4rgNU5qz0PxG1SDQt2FInkkvTd4hR7p2KCOH0h4vLn8+Gb9/LGEHDl9uqVfDKFJWu6wY4 + zU1LJKDKBA5UZzezGv2ZdiVK55pGpfvcLrZKm/TK9Ta1ieT6WFXiKlRRHDMBa0iGjKZseItpwoy54Cuzd4uUDe1SvzhhXVlN + PeW6Wwi8/Wi8OpHNupYZRTVNWErl0drtESeWjkAQoZL0V+HVpQuu3Zqc1KHvYh0f25i1U79ls6Bg1Vk+bbBS+wqAYaK21VTg + el4D0eptg3rCLthG4pUrCvW0HaC9qke3LldYuUKJnAVoF+RMdeqbH44anRMOwQ4a6nZOJN7AdxTvbH7MeyIN7JhgCDXYe5wb + E4czc9L5lXa+AEvTjsWR3AXdInnEYkTL+mS2cKZydKrPw6m82mcGDAq13lMpiCb/pGCe4JVsssaFKU6fLhRp4RFcUqsvltBi + sFlmibiRrzHgmxQgQZ4gv0W0Kr6zFiwnETe7dEfi4NqMPP2TrE10a6RU0K/uAXWPqlTirwLqGEnFuWJTuzs07o3PyiRkn3iI + uCrnsBKYSsKkMg4ZQSuJtY/TcsNA8QIZiYK0Fgwxj51cWOi1IDilqYbaMjvQ4t2vU3XS8qL6tj4Qt19t22VxXhndbm/bZ6wC + s0dBJAldOfs0QnEaclBRwberJ2h4VT5rRbJvNb0Ru2yH355QVGQ3zastWAL0RsVKhGssVIpSmQJ7xqd94qUYwaq65KHaLkoU + cT/GaypkyYok1wBCe6ZC5f2a5isf5as1DVXeP1Pm+5vKdV9TrPs7SnVfW6j7O8p0X1Gks0I2c2vJ1pHOyBtS8yoe9pXt/Fxg + ueoxsjxSW6VTN4lleW5Vqcxl1aJcpupx0nGnthNd6RpcapffUmflLTWLbgbU06ttgLyyymwrV4Vt5SqurerravJeJi+opQ21 + tJVdRuO6KepnUal0poaIQzBOFE6pnaKnv48067lTGc4E3Fx5nSvtpFIzyrqoZBOCr1EcMbNTJeUoXct4YqvhKwqHqlvVLt/g + Um2o8h0us9hoNGaMguOe8suW0F/Ra/uTnba/ts9mG8T4Kd02QxXjSs+t2k6rgJd7YKZBWaU/1XZzsA9Ed6pMlKk+1lrT/sBB + 6wltP8xBvRouXTvIhNwzViO+wQyE+aWFsLfJFlLVkO49Izo8PHJV3R2zryMFyngPG3/Hpept5o/L0HunRRdnjt+DL5w5WeRW + TBhF7uLmZrlQrPFLBemmFoVZ47WzDU3NrAMbvSRdzq3Fq68HG1KYDGD6arw6PbJ584cX+/UkRpun4M2sW5/gZV6N71SKU+g2 + 2UQm4q6Qt2sL39aVZmPtirZCzzPvZ7j27Yb3A6Q5jJe0L5yXgE7hfcnutZV5G5Izf0/Eybl/4VCym00oF7oqfh/UMEMB7tUd + ZOKOwNZGXrIIDuxDtYgB+UczNS1Gi7xWhCSVjFhGKscc4TmPI+pPDa27UxGTFpLygS3DY4jjq3hsl5CJ1t4izW/K3bjWtrFM + Kq91tnp4hit+cOXCqfmVS3znSUzP4rEkUIlJE7K1Xb/p1OTu35qaHD9Oo1YAw2sUsuC5Y6uZXwWwvI8x7sj3rQzGPH/axrp6 + Wxs2cbVLKG33dmmvG6TFL/+s3wbWL2LN5mxvpjYUg8ve3/ofBzgikHM9AAA= + """; + @Container private static final GenericContainer REDIS = @@ -69,6 +134,7 @@ class CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest { private RedisCommands admin; private RedisCommands owner; private String scriptSha; + private String preFenceScriptSha; @BeforeEach void setUp() throws Exception { @@ -121,10 +187,25 @@ void setUp() throws Exception { } assertThat(HexFormatHolder.sha256(script)).isEqualTo(descriptor.sha256()); scriptSha = owner.scriptLoad(script); + byte[] preFenceScript = predecessorLuaForOwnerProof(); + preFenceScriptSha = owner.scriptLoad(preFenceScript); + assertThat(HexFormatHolder.sha1(preFenceScript)).isEqualTo(preFenceScriptSha); assertThat(HexFormatHolder.sha1(script)).isEqualTo(scriptSha); assertThat(owner.aclWhoami()).isEqualTo(PRINCIPAL); } + static byte[] predecessorLuaForOwnerProof() throws Exception { + byte[] preFenceScript; + try (var input = + new GZIPInputStream( + new ByteArrayInputStream( + Base64.getMimeDecoder().decode(PRE_FENCE_LUA_GZIP_BASE64)))) { + preFenceScript = input.readAllBytes(); + } + assertThat(HexFormatHolder.sha256(preFenceScript)).isEqualTo(PRE_FENCE_LUA_SHA256); + return preFenceScript; + } + @AfterEach void tearDown() { if (ownerConnection != null) ownerConnection.close(); @@ -259,7 +340,232 @@ void resetLossRefusesWithoutRecreatingCandidateIndexesOrBarriers() throws Except } } + @Test + void absentExecutionFenceInstallsOnlyTheExactPersistentDenyWithoutRecreatingRuntimeState() + throws Exception { + ScriptCase original = seed(false); + for (int index = 0; index < 6; index++) + admin.del(new byte[][] {ascii(original.keys()[index])}); + Map before = physicalImage(original); + + // No credential, template, OPEN barrier, candidate or index is needed to deny future execution. + byte[][] arguments = action(original, "FENCE").arguments().clone(); + arguments[8] = ascii("unavailable-candidate"); + arguments[10] = ascii("unavailable-template"); + arguments[12] = ascii("unavailable-account"); + arguments[13] = ascii("unavailable-issuer"); + assertThat(eval(new ScriptCase(original.keys(), arguments))).isEqualTo(5L); + assertHash(original.keys()[6], capacityPhysicalFields(original, "FENCED_INDETERMINATE")); + assertThat(admin.pttl(ascii(original.keys()[6]))).isEqualTo(-1L); + assertPhysicalImage(original, before, 6); + + Map denied = physicalImage(original); + assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(5L); + assertPhysicalImage(original, denied, 7); + } + + @Test + void authorizedFenceChangesOnlyStateAndEveryDelayedCurrentOrPinnedOldCallRefuses() + throws Exception { + ScriptCase original = seed(); + Map before = physicalImage(original); + + assertThat(eval(action(original, "FENCE"))).isEqualTo(5L); + assertHash(original.keys()[6], capacityPhysicalFields(original, "FENCED_INDETERMINATE")); + assertPhysicalImage(original, before, 6); + Map denied = physicalImage(original); + // These are the actual immutable old production bytes, not a reconstruction of its guards. + assertThat(eval(preFenceScriptSha, action(original, "INSTALL"))).isEqualTo(-1L); + assertThat(eval(preFenceScriptSha, original)).isEqualTo(-1L); + assertThat(eval(preFenceScriptSha, action(original, "CLOSE"))).isEqualTo(-1L); + assertThat(eval(action(original, "INSTALL"))).isEqualTo(-1L); + assertThat(eval(original)).isEqualTo(-1L); + assertThat(eval(action(original, "CLOSE"))).isEqualTo(-1L); + assertThat(eval(action(original, "FENCE"))).isEqualTo(5L); + assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(5L); + assertPhysicalImage(original, denied, 7); + for (String key : original.keys()) assertThat(admin.pttl(ascii(key))).isEqualTo(-1L); + } + + @Test + void fenceBeforeDelayedPinnedOldInstallationPreventsItFromInstallingAuthorization() + throws Exception { + ScriptCase original = seed(false); + assertThat(eval(action(original, "FENCE"))).isEqualTo(5L); + Map denied = physicalImage(original); + + assertThat(eval(preFenceScriptSha, action(original, "INSTALL"))).isEqualTo(-1L); + assertThat(eval(preFenceScriptSha, original)).isEqualTo(-1L); + assertPhysicalImage(original, denied, 7); + } + + @Test + void finalBeforeFencePreservesEveryCommittedByteHashAndControllerTimeIncludingExpiredReplay() + throws Exception { + ScriptCase original = seed(); + assertThat(eval(original)).isEqualTo(1L); + Map committed = physicalImage(original); + + assertThat(eval(action(original, "FENCE"))).isEqualTo(2L); + assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(2L); + byte[][] credentialFree = action(original, "FENCE").arguments().clone(); + credentialFree[11] = ascii("1"); + assertThat(eval(new ScriptCase(original.keys(), credentialFree))).isEqualTo(2L); + assertThat(eval(expired(new ScriptCase(original.keys(), credentialFree)))).isEqualTo(2L); + assertThat(eval(preFenceScriptSha, original)).isEqualTo(2L); + assertPhysicalImage(original, committed, 7); + assertThat(admin.hlen(ascii(original.keys()[6]))).isEqualTo(6L); + for (String key : original.keys()) assertThat(admin.pttl(ascii(key))).isEqualTo(-1L); + } + + @Test + void alreadyClosedFenceIsReadOnlyAndNeverReclassifiesTheHistoricalOutcome() throws Exception { + ScriptCase original = seed(); + assertThat(eval(action(original, "CLOSE"))).isEqualTo(4L); + Map closed = physicalImage(original); + + assertThat(eval(action(original, "FENCE"))).isEqualTo(4L); + assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(4L); + assertPhysicalImage(original, closed, 7); + assertHash(original.keys()[6], capacityPhysicalFields(original, "CLOSED")); + } + + @Test + void expiredFirstFenceRefusesBothAbsentAndAuthorizedWithoutAnyMutation() throws Exception { + for (boolean install : new boolean[] {false, true}) { + admin.flushdb(); + ScriptCase original = seed(install); + Map before = physicalImage(original); + + assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(-1L); + assertPhysicalImage(original, before, 7); + assertThat(admin.pttl(ascii(original.keys()[6]))).isEqualTo(install ? -1L : -2L); + } + } + + @Test + void fenceRefusesWrongTypeTtlIdentityAndEveryUnexpectedPhysicalShapeWithoutMutation() + throws Exception { + for (String fault : + List.of( + "type", + "ttl", + "binding", + "digest", + "extra-field", + "missing-state", + "unknown-state", + "fenced-extra-field", + "closed-extra-field", + "committed-missing-fields", + "committed-foreign-field", + "committed-invalid-hash", + "committed-invalid-time")) { + admin.flushdb(); + ScriptCase original = seed(); + byte[] key = ascii(original.keys()[6]); + switch (fault) { + case "type" -> { + admin.del(new byte[][] {key}); + admin.set(key, ascii("foreign-type")); + } + case "ttl" -> admin.pexpire(key, 60_000L); + case "binding" -> admin.hset(key, ascii("binding"), ascii("different-envelope")); + case "digest" -> admin.hset(key, ascii("digest"), ascii("sha256:" + "0".repeat(64))); + case "extra-field" -> admin.hset(key, ascii("unexpected"), ascii("foreign")); + case "missing-state" -> admin.hdel(key, ascii("state")); + case "unknown-state" -> admin.hset(key, ascii("state"), ascii("FOREIGN")); + case "fenced-extra-field", "closed-extra-field" -> { + admin.hset( + key, + ascii("state"), + ascii(fault.equals("fenced-extra-field") ? "FENCED_INDETERMINATE" : "CLOSED")); + admin.hset(key, ascii("unexpected"), ascii("foreign")); + } + case "committed-missing-fields" -> admin.hset(key, ascii("state"), ascii("COMMITTED")); + case "committed-foreign-field", "committed-invalid-hash", "committed-invalid-time" -> { + assertThat(eval(original)).isEqualTo(1L); + if (fault.equals("committed-foreign-field")) { + byte[] value = admin.hget(key, ascii("sessionSha1")); + admin.hdel(key, ascii("sessionSha1")); + admin.hset(key, ascii("foreignSha1"), value); + } else if (fault.equals("committed-invalid-hash")) { + admin.hset(key, ascii("sessionSha1"), ascii("invalid")); + } else { + admin.hset(key, ascii("continuityExpiresAt"), ascii("1")); + } + } + default -> throw new IllegalStateException("Unknown fixture fault: " + fault); + } + Map before = physicalImage(original); + + assertThat(eval(action(original, "FENCE"))).as(fault).isEqualTo(-1L); + assertPhysicalImage(original, before, 7); + if (fault.equals("ttl")) assertThat(admin.pttl(key)).isPositive(); + else assertThat(admin.pttl(key)).isEqualTo(-1L); + } + } + + @Test + void fenceRequiresTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() throws Exception { + for (String fault : + List.of("missing-field", "extra-field", "wrong-tenant", "invalid-fence", "wrong-key")) { + admin.flushdb(); + ScriptCase original = seed(false); + byte[][] arguments = action(original, "FENCE").arguments().clone(); + String[] keys = original.keys().clone(); + var envelope = (tools.jackson.databind.node.ObjectNode) JSON.readTree(arguments[16]); + switch (fault) { + case "missing-field" -> envelope.remove("reservationId"); + case "extra-field" -> envelope.put("unexpected", "foreign"); + case "wrong-tenant" -> envelope.put("tenantId", ACCOUNT); + case "invalid-fence" -> envelope.put("selectedOwnerFence", "0"); + case "wrong-key" -> keys[6] = keys[6] + ":foreign"; + default -> throw new IllegalStateException("Unknown fixture fault: " + fault); + } + arguments[16] = canonicalBytes(envelope); + arguments[18] = ascii("sha256:" + HexFormatHolder.sha256(arguments[16])); + Map before = physicalImage(original); + + assertThat(eval(new ScriptCase(keys, arguments))).as(fault).isEqualTo(-2L); + assertPhysicalImage(original, before, 7); + assertThat(admin.type(ascii(keys[6]))).isEqualTo("none"); + } + } + + private Map physicalImage(ScriptCase original) { + Map image = new LinkedHashMap<>(); + for (String key : original.keys()) image.put(key, admin.dump(ascii(key))); + return image; + } + + private void assertPhysicalImage( + ScriptCase original, Map expected, int keyCount) { + for (int index = 0; index < keyCount; index++) { + String key = original.keys()[index]; + if (expected.get(key) == null) assertThat(admin.dump(ascii(key))).as(key).isNull(); + else assertThat(admin.dump(ascii(key))).as(key).containsExactly(expected.get(key)); + } + } + + private static Map capacityPhysicalFields(ScriptCase original, String state) { + return Map.of( + "binding", original.arguments()[16], + "digest", original.arguments()[18], + "state", ascii(state)); + } + + private static ScriptCase expired(ScriptCase original) { + byte[][] arguments = original.arguments().clone(); + arguments[14] = ascii("1"); + return new ScriptCase(original.keys(), arguments); + } + private ScriptCase seed() throws Exception { + return seed(true); + } + + private ScriptCase seed(boolean install) throws Exception { String sessionKey = "session:game:{" + TAG + "}:" + INSTANCE + ":" + SESSION; String characterKey = "session:game:index:character:{" + TAG + "}:" + NAMESPACE + ":" + CHARACTER; @@ -340,7 +646,7 @@ private ScriptCase seed() throws Exception { issuerPhysical.put("payloadDigest", ascii("sha256:" + "f".repeat(64))); admin.hset(ascii(issuerBarrierKey), encodedBytes(issuerPhysical)); ScriptCase result = new ScriptCase(keys, arguments); - assertThat(eval(action(result, "INSTALL"))).isEqualTo(3L); + if (install) assertThat(eval(action(result, "INSTALL"))).isEqualTo(3L); return result; } @@ -630,10 +936,14 @@ private static Map issuerPhysicalFields() { } private long eval(ScriptCase testCase) { + return eval(scriptSha, testCase); + } + + private long eval(String sha, ScriptCase testCase) { byte[][] keyBytes = new byte[testCase.keys().length][]; for (int index = 0; index < keyBytes.length; index++) keyBytes[index] = ascii(testCase.keys()[index]); - return owner.evalsha(scriptSha, ScriptOutputType.INTEGER, keyBytes, testCase.arguments()); + return owner.evalsha(sha, ScriptOutputType.INTEGER, keyBytes, testCase.arguments()); } private RedisClient createClient(String username, String password) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 59da77f2e8..d0a06d7727 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -330,6 +330,341 @@ void recreatedCapacityOwnerClosesExactAttemptAndRejectsDelayedFinalCas() throws .containsExactly(proof.canonicalReadback()); } + @Test + void processStopAfterActualSqlAuthorizationBeforeRedisSendFencesUnknownAndActuallyHandsOff() + throws Exception { + repairAccountMember(); + bridge(false); + var executionFile=directory.resolve("original-execution.json"); + java.nio.file.Files.write(executionFile,controlledCapacity.canonicalBytes()); + var process=new ProcessBuilder( + Path.of(System.getProperty("java.home"),"bin","java").toString(),"-cp",childClasspath(), + StopAfterAuthorizationCommit.class.getName(),POSTGRES.getJdbcUrl(),POSTGRES.getUsername(), + POSTGRES.getPassword(),executionFile.toString()).redirectErrorStream(true).start(); + try { + assertThat(process.waitFor(20,java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + assertThat(process.exitValue()).isEqualTo(72); + assertThat(new String(process.getInputStream().readAllBytes(),StandardCharsets.UTF_8)) + .contains("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); + } finally { + if(process.isAlive()) { + process.destroyForcibly(); + assertThat(process.waitFor(5,java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + String originalKey=capacityKey(tags.assignmentForTransition(fixture.transitionId())); + assertThat(admin.type(ascii(originalKey))).isEqualTo("none"); + var original=regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()),0); + var successor=actualTransferHandoff(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(admin.hget(ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))),ascii("state"))) + .containsExactly(ascii("FENCED_INDETERMINATE")); + assertThat(fixture.dsl().fetchSingle("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?",controlledCapacity.digest()).get(0,String.class)) + .isEqualTo("INSTALL_DISPATCHED"); + assertThatThrownBy(() -> capacityOwner().readExact(controlledCapacity.request(),controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> capacityOwner().closeOriginalAttempt(controlledCapacity.request(),controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void authorizedUnknownHandoffKeepsOriginalCandidateAndRefusesCompletedMutation() throws Exception { + repairAccountMember(); bridge(); + var original=regionBinding.installation(); + byte[] candidate=admin.get(ascii(installation.sessionKey())); + var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); + var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); + var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); + UUID transferId=transfer.advance(original.source,original.status,deadline()); + assertThatThrownBy(() -> replaceRegionOwner("unproved-successor")) + .isInstanceOf(IllegalStateException.class); + admin.pexpire(ascii(original.grant.key()),0); + var successor=CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(),ownerClient,catalog,original,sources.resolver,transfer,deadline()); + var completed=receiver.observeForRegionOwnerTransfer(transferId,0,deadline()); + assertThat(completed.regionOwnerTransferContext().controlState()).isEqualTo("COMPLETED"); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(candidate); + assertThatThrownBy(() -> repository.within(deadline(),ignored -> repository.capture(transferId))) + .isInstanceOf(IllegalStateException.class); + assertThat(successor.status.ownerInstanceId()).isEqualTo("final-owner-handoff"); + } + + @Test + void retainedTransferFenceLossCannotBeReinstalledOrQualifyHandoff() throws Exception { + repairAccountMember(); bridge(); + var original=regionBinding.installation(); + var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); + var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); + var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); + transfer.advance(original.source,original.status,deadline()); + String key=capacityKey(tags.assignmentForTransition(fixture.transitionId())); + admin.del(ascii(key)); + String retained=sqlImage(); + admin.pexpire(ascii(original.grant.key()),0); + assertThatThrownBy(() -> CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(),ownerClient,catalog,original,sources.resolver,transfer,deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(admin.type(ascii(key))).isEqualTo("none"); + assertThat(sqlImage()).isEqualTo(retained); + assertThat(new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source).orElseThrow().executorFence()) + .isEqualTo(original.status.executorFence()); + } + + private CanonicalGameplayRegionLeaseOwner.Installation actualTransferHandoff() throws Exception { + var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); + var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); + var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); + return CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(),ownerClient,catalog,regionBinding.installation(),sources.resolver,transfer,deadline()); + } + + @Test + void retainedTransferFenceWithTtlCannotQualifyNativeHandoff() throws Exception { + retainedTransferTamperBlocks("ttl"); + } + + @Test + void retainedTransferFenceWrongTypeCannotQualifyNativeHandoff() throws Exception { + retainedTransferTamperBlocks("type"); + } + + @Test + void retainedTransferFenceChangedEnvelopeCannotQualifyNativeHandoff() throws Exception { + retainedTransferTamperBlocks("binding"); + } + + private void retainedTransferTamperBlocks(String fault) throws Exception { + repairAccountMember();bridge(); + var original=regionBinding.installation(); + var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); + var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); + var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); + transfer.advance(original.source,original.status,deadline()); + byte[] key=ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))); + if(fault.equals("ttl")) admin.pexpire(key,10000); + else if(fault.equals("type")) { admin.del(key);admin.set(key,ascii("wrong-type")); } + else admin.hset(key,ascii("binding"),ascii("{}")); + byte[] physical=admin.dump(key); + admin.pexpire(ascii(original.grant.key()),0); + assertThatThrownBy(() -> CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(),ownerClient,catalog,original,sources.resolver,transfer,deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(admin.dump(key)).containsExactly(physical); + assertThat(new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source).orElseThrow().executorFence()) + .isEqualTo(original.status.executorFence()); + } + + @Test + void correctlySignedDifferentStorageGenerationCannotAdoptRetainedTransferReceipts() throws Exception { + repairAccountMember();bridge(); + var original=regionBinding.installation(); + var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); + var attestor=new CanonicalGameplayControlledRegionTransferObservationFixture(); + var originalTransfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),attestor.receiver(repository,tags)); + originalTransfer.advance(original.source,original.status,deadline()); + String retained=sqlImage(); + var changed=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),attestor.receiver(repository,tags,"storage-2")); + admin.pexpire(ascii(original.grant.key()),0); + assertThatThrownBy(() -> CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(),ownerClient,catalog,original,sources.resolver,changed,deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(retained); + assertThat(new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source).orElseThrow().executorFence()) + .isEqualTo(original.status.executorFence()); + } + + @Test + void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff() throws Exception { + repairAccountMember();bridge(); + var source=inventory.readOriginalNewFinalAdmissionSource(decision); + byte[] committed; + try(var credential=new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(),CLOCK); + var template=credential.template(); + var ignored=finalOwner().finalizeOriginalNewOnce(source,template,controlledAccountOpen(),issuerOpen(),controlledCapacity,deadline())) { + committed=admin.get(ascii(installation.sessionKey())); + } + // No SQL final receipt was retained by the interrupted final caller. + assertThat(fixture.dsl().fetchSingle("SELECT original_new_final_session_sha256 FROM game_session_canonical_binding_transition WHERE transition_id=?",fixture.transitionId()).get(0,String.class)).isNull(); + var original=regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()),0); + var successor=actualTransferHandoff(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(fixture.dsl().fetchSingle("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?",controlledCapacity.digest()).get(0,String.class)).isEqualTo("COMMITTED"); + assertThat(capacityOwner().readExact(controlledCapacity.request(),controlledCapacity.reservation()).disposition()).isEqualTo("COMMITTED"); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); + } + + @Test + void committedHashWithoutCompletePositiveServingProofStillBlocksActualTransfer() throws Exception { + repairAccountMember();bridge(); + var source=inventory.readOriginalNewFinalAdmissionSource(decision); + try(var credential=new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(),CLOCK); + var template=credential.template(); + var ignored=finalOwner().finalizeOriginalNewOnce(source,template,controlledAccountOpen(),issuerOpen(),controlledCapacity,deadline())) { + admin.del(ascii(installation.sessionKey())); + } + var original=regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()),0); + assertThatThrownBy(this::actualTransferHandoff).isInstanceOf(IllegalStateException.class); + assertThat(new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source).orElseThrow().executorFence()) + .isEqualTo(original.status.executorFence()); + assertThat(fixture.dsl().fetchSingle("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?",controlledCapacity.digest()).get(0,String.class)).isEqualTo("AUTHORIZED"); + assertThat(admin.hget(ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))),ascii("state"))) + .containsExactly(ascii("COMMITTED")); + assertThatThrownBy(() -> capacityOwner().readExact(controlledCapacity.request(),controlledCapacity.reservation())).isInstanceOf(IllegalStateException.class); + } + + private static String childClasspath() throws Exception { + var paths=new java.util.LinkedHashSet(); + paths.addAll(List.of(System.getProperty("java.class.path").split(java.io.File.pathSeparator))); + for(ClassLoader loader=CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.class.getClassLoader();loader!=null;loader=loader.getParent()) { + if(loader instanceof java.net.URLClassLoader urls) for(var url:urls.getURLs()) { + if("file".equals(url.getProtocol())) paths.add(Path.of(url.toURI()).toString()); + } + } + paths.add(Path.of(CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString()); + return String.join(java.io.File.pathSeparator,paths); + } + + @Test + void delayedActualPredecessorInstallRefusesAfterNativeHandoffWithinOriginalDeadline() throws Exception { + delayedPredecessorAfterHandoff(true); + } + + @Test + void delayedActualPredecessorFinalRefusesAfterNativeHandoffWithinOriginalDeadline() throws Exception { + delayedPredecessorAfterHandoff(false); + } + + private void delayedPredecessorAfterHandoff(boolean installAction) throws Exception { + repairAccountMember();bridge(!installAction); + var source=inventory.readOriginalNewFinalAdmissionSource(decision); + var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); + var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); + var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); + String oldSha=admin.scriptLoad(CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.predecessorLuaForOwnerProof()); + var entered=new java.util.concurrent.CountDownLatch(1); + var release=new java.util.concurrent.CountDownLatch(1); + var calls=new java.util.concurrent.atomic.AtomicInteger(); + String action=installAction ? "INSTALL" : "FINAL"; + RedisClient delayed=mock(RedisClient.class); + when(delayed.connect(ByteArrayCodec.INSTANCE)).thenAnswer(ignored -> + delayedConnection(ownerClient.connect(ByteArrayCodec.INSTANCE),oldSha,action,entered,release,calls)); + try(var credential=new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(),CLOCK); + var raw=credential.template();var template=raw.bindCapacityExecution(controlledCapacity)) { + var account=controlledAccountOpen();var issuer=issuerOpen(); + long frozenDeadline=CLOCK.millis()+5000L; + var old=java.util.concurrent.CompletableFuture.runAsync(() -> { + if(installAction) { + new CanonicalGameplayOriginalNewCapacityExecutionOwner(fixture.dsl(),delayed,catalog,CLOCK,tags) + .authorize(source,template,account,issuer,controlledCapacity,frozenDeadline); + } else { + var owner=new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner(delayed,catalog,CLOCK,tags, + () -> delayed.connect(ByteArrayCodec.INSTANCE),() -> frozenDeadline-CLOCK.millis()); + try(var ignored=owner.finalizeOriginalNewOnce(source,template,account,issuer,controlledCapacity,frozenDeadline)) { + throw new AssertionError("Delayed old FINAL must not produce an admission receipt"); + } + } + }); + try { + assertThat(entered.await(3,java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + var original=regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()),0); + var successor=CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(),ownerClient,catalog,original,sources.resolver,transfer,frozenDeadline); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(CLOCK.millis()).isLessThan(frozenDeadline); + release.countDown(); + assertThatThrownBy(() -> old.get(2,java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class); + assertThat(calls.get()).isOne(); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(source.candidate().canonicalBytes()); + assertThat(admin.hget(ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))),ascii("state"))) + .containsExactly(ascii("FENCED_INDETERMINATE")); + } finally { + release.countDown(); + try { old.get(5,java.util.concurrent.TimeUnit.SECONDS); } + catch(java.util.concurrent.ExecutionException expected) { /* already asserted failure */ } + } + } + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection delayedConnection( + StatefulRedisConnection actual,String predecessorSha,String action, + java.util.concurrent.CountDownLatch entered,java.util.concurrent.CountDownLatch release, + java.util.concurrent.atomic.AtomicInteger calls) { + var commands=actual.async(); + Object delayedCommands=java.lang.reflect.Proxy.newProxyInstance( + io.lettuce.core.api.async.RedisAsyncCommands.class.getClassLoader(), + new Class[]{io.lettuce.core.api.async.RedisAsyncCommands.class},(proxy,method,args) -> { + if(method.getName().equals("evalsha") && args.length==4 && args[3] instanceof byte[][] values + && values.length==19 && action.equals(new String(values[17],StandardCharsets.US_ASCII))) { + calls.incrementAndGet();entered.countDown(); + if(!release.await(4,java.util.concurrent.TimeUnit.SECONDS)) throw new IllegalStateException("Delayed old invocation not released"); + Object[] original=args.clone();original[0]=predecessorSha; + try { return method.invoke(commands,original); } + catch(java.lang.reflect.InvocationTargetException failure) { throw failure.getCause(); } + } + try { return method.invoke(commands,args); } + catch(java.lang.reflect.InvocationTargetException failure) { throw failure.getCause(); } + }); + return (StatefulRedisConnection)java.lang.reflect.Proxy.newProxyInstance( + StatefulRedisConnection.class.getClassLoader(),new Class[]{StatefulRedisConnection.class}, + (proxy,method,args) -> { + if(method.getName().equals("async")) return delayedCommands; + try { return method.invoke(actual,args); } + catch(java.lang.reflect.InvocationTargetException failure) { throw failure.getCause(); } + }); + } + + /** A real child JVM halts only after independent visibility of the real owner's SQL commit. */ + public static final class StopAfterAuthorizationCommit { + private StopAfterAuthorizationCommit() {} + public static void main(String[] args) throws Exception { + var raw=new DriverManagerDataSource(args[0],args[1],args[2]); + var execution=CanonicalGameplayRegionOwnerTransferRepository.decode(java.nio.file.Files.readAllBytes(Path.of(args[3]))); + var stopping=new org.springframework.jdbc.datasource.DelegatingDataSource(raw) { + @Override public java.sql.Connection getConnection() throws java.sql.SQLException { + var actual=raw.getConnection(); + return (java.sql.Connection)java.lang.reflect.Proxy.newProxyInstance( + java.sql.Connection.class.getClassLoader(),new Class[]{java.sql.Connection.class},(proxy,method,values) -> { + Object result; + try { result=method.invoke(actual,values); } + catch(java.lang.reflect.InvocationTargetException failure) { throw failure.getCause(); } + if(method.getName().equals("commit")) { + try(var independent=raw.getConnection();var check=independent.prepareStatement("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?")) { + check.setString(1,execution.digest()); + try(var rows=check.executeQuery()) { + if(rows.next() && "INSTALL_DISPATCHED".equals(rows.getString(1))) { + System.out.println("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); + System.out.flush(); + Runtime.getRuntime().halt(72); + } + } + } + } + return result; + }); + } + }; + var sql=org.jooq.impl.DSL.using(stopping,org.jooq.SQLDialect.POSTGRES); + var candidate=CanonicalGameplayOriginalNewCandidate.parseCanonical(sql.fetchSingle( + "SELECT original_new_candidate_bytes FROM game_session_canonical_binding_transition WHERE transition_id=?",execution.transitionId()).get(0,byte[].class)); + var inventory=new CanonicalGameplayBindingInventoryRepository(sql); + var decision=inventory.readAdmissionDecision(execution.transitionId(),candidate.leaseEvidence()); + var source=inventory.readOriginalNewFinalAdmissionSource(decision); + try(var unused=RedisClient.create("redis://127.0.0.1:1")) { + var scripts=RedisScriptCatalog.fromContributions(List.of(new net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution())); + var owner=new CanonicalGameplayOriginalNewCapacityExecutionOwner(sql,unused,scripts,Clock.systemUTC(),new CanonicalGameplayTenantGameplayTagRepository(sql,"test",1)); + owner.authorize(source,null,null,null,execution,System.currentTimeMillis()+5000); + } + throw new IllegalStateException("Expected committed authorization to stop the process before Redis dispatch"); + } + } + @Test void retainedClosedProofSurvivesControlledServingRemovalAndStillRejectsDelayedFinal() throws Exception { @@ -1880,7 +2215,9 @@ private String sqlImage() { "game_session_canonical_tenant_gameplay_tag", "game_session_canonical_issuer_admission_initializer", "game_session_canonical_issuer_admission_initializer_receipt", - "game_session_original_new_capacity_execution")) { + "game_session_original_new_capacity_execution", + "game_session_region_owner_transfer", + "game_session_region_owner_transfer_item")) { rows.put( table, fixture 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 d3be153112..a03ef3da4e 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 @@ -118,6 +118,19 @@ record ExistingBinding( CanonicalGameplayRegionLeaseOwner.Installation installation, CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement acknowledgement) {} + /** Actual acquire/install/revalidate path; only upstream placement/incarnation remain controlled. */ + static CanonicalGameplayRegionLeaseOwner.Installation handoffExistingOriginal( + DSLContext dsl, RedisClient coordinationRedis, RedisScriptCatalog catalog, + CanonicalGameplayRegionLeaseOwner.Installation original, + CanonicalInitialPlayerLocationRegionResolver resolver, + CanonicalGameplayRegionOwnerTransferCoordinator transfer,long deadline) { + var identity=new RuntimeIdentity("game-session-service","final-owner-handoff", + "localhost",Instant.now(),"test","test","controlled-test-image"); + var successor=CanonicalGameplayRegionLeaseOwnerFactory.compose(dsl,coordinationRedis,catalog, + new ControlledStableIncarnationSource(),resolver,identity,Duration.ofSeconds(30),Clock.systemUTC()); + return successor.installForTransition(null,original.transitionId,original.worldRequest,transfer,deadline); + } + /** * Creates one real first-NEW provisional candidate from the exact placement selector, installs * the first region timeline and SQL fence, then retries the same binding bridge as a lost reply. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index f066e1a453..7deacd9478 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -3,29 +3,50 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.codec.ByteArrayCodec; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; +import org.jooq.ExecuteContext; import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.containers.GenericContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -34,8 +55,6 @@ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest { private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); - private static final UUID GAME_INSTANCE_ID = - UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID OTHER_GAME_INSTANCE_ID = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); private static final UUID CANONICAL_REGION_ID = @@ -52,6 +71,12 @@ class CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest { private static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @TempDir Path directory; + private DSLContext dsl; private CanonicalGameplayRegionRuntimeStatusRepository repository; private CanonicalGameplayRegionRuntimeStatusRepository.Source source; @@ -75,12 +100,11 @@ void setUpRepository() { dsl = DSL.using(dataSource, SQLDialect.POSTGRES); repository = new CanonicalGameplayRegionRuntimeStatusRepository(dsl); - source = source(GAME_INSTANCE_ID, CAPTURE_ID); } @BeforeEach - void clearOwnerRows() { - dsl.execute("TRUNCATE TABLE game_session_region_runtime_status"); + void selectFreshOwnerScopeWithoutDiscardingRetainedCustody() { + source = source(UUID.randomUUID(), CAPTURE_ID); } @Test @@ -111,7 +135,7 @@ void initializesOnlyAnAbsentRegionAtItsFirstEpochAndFirstTick() { assertThat(installed.tenantRegionTag()) .isEqualTo( CanonicalGameplayRegionRedisKeys.tenantRegionTag( - TENANT_ID, GAME_INSTANCE_ID, OPERATIONAL_REGION_ID)); + TENANT_ID, source.gameInstanceId(), OPERATIONAL_REGION_ID)); assertThat(installed.regionEpoch()).isEqualTo(1L); assertThat(installed.lifecycleEpoch()).isEqualTo(4L); assertThat(installed.lastCommittedTickId()).isEqualTo(-1L); @@ -159,7 +183,7 @@ void exactOwnerRetryReplacesFenceWithoutResettingRegionTimeline() { + " SET last_committed_tick_batch_id = 'batch-7', last_committed_tick_id = 7" + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", TENANT_ID, - GAME_INSTANCE_ID, + source.gameInstanceId(), OPERATIONAL_REGION_ID); var current = repository.find(source).orElseThrow(); @@ -207,7 +231,7 @@ void sameNaturalScopeRejectsChangedWorldCaptureEvidence() { assertThatThrownBy( () -> repository.find( - source(GAME_INSTANCE_ID, new UUID(0x6666666666666666L, 0x8666666666666666L)))) + source(source.gameInstanceId(), new UUID(0x6666666666666666L, 0x8666666666666666L)))) .isInstanceOf(IllegalStateException.class); } @@ -247,7 +271,7 @@ void ownerGrantAcceptsOnlyChangedLifecycleReadCorrelationAndKeepsInitialRequestB "SELECT lifecycle_request_bytes FROM game_session_region_runtime_status" + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", TENANT_ID, - GAME_INSTANCE_ID, + source.gameInstanceId(), OPERATIONAL_REGION_ID) .get("lifecycle_request_bytes", byte[].class)) .containsExactly(source.lifecycleRequest().canonicalBytes()); @@ -328,6 +352,740 @@ void concurrentNewGrantsFromOnePriorOwnerInstallOnlyOneNewFence() throws Excepti } } + @Test + void actualAuthorizationHoldingRegionRowMakesFreezeWaitAndRetainsThatOriginal() throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), Clock.systemUTC()); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution); + var gate = new RegionRowLockGate(); + ExecutorService executor = Executors.newFixedThreadPool(2)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + Future authorization = + executor.submit( + () -> + proof.capacity(gate.attach(proof.sql)) + .authorize( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline())); + gate.awaitLock(); + Future freeze = + executor.submit( + () -> + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.begin(proof.scope, proof.prior))); + try { + assertDatabaseWaitsFor(proof.sql, gate.backendPid()); + assertThat(freeze.isDone()).isFalse(); + } finally { + gate.release(); + } + authorization.get(10, TimeUnit.SECONDS); + UUID id = freeze.get(10, TimeUnit.SECONDS); + assertThat(id).isNotNull(); + assertThat(proof.executionState(proof.execution)).isEqualTo("AUTHORIZED"); + assertThat( + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id))) + .extracting(item -> item.execution().digest()) + .containsExactly(proof.execution.digest()); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + } + } + + @Test + void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch() throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), Clock.systemUTC()); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution); + var gate = new RegionRowLockGate(); + ExecutorService executor = Executors.newFixedThreadPool(2)) { + var seeded = proof.newControlledExecution(); + proof.seedUndeliveredDispatch(seeded); + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + var freezing = proof.transfers(gate.attach(proof.sql)); + Future freeze = + executor.submit( + () -> + freezing.within( + transferDeadline(), ignored -> freezing.begin(proof.scope, proof.prior))); + gate.awaitLock(); + Future refused = + executor.submit( + () -> { + try { + proof.capacity(proof.sql) + .authorize( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline()); + return false; + } catch (IllegalStateException frozen) { + return true; + } + }); + try { + assertDatabaseWaitsFor(proof.sql, gate.backendPid()); + assertThat(refused.isDone()).isFalse(); + } finally { + gate.release(); + } + UUID id = freeze.get(10, TimeUnit.SECONDS); + assertThat(refused.get(10, TimeUnit.SECONDS)).isTrue(); + assertThat(proof.executionState(proof.execution)).isNull(); + assertThat(proof.executionState(seeded)).isEqualTo("INSTALL_DISPATCHED"); + assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); + // The INSERT trigger independently takes the same row lock and rejects raw late dispatch. + assertSqlGuard(() -> proof.seedUndeliveredDispatch(proof.execution)); + assertThat( + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id))) + .extracting(item -> item.execution().digest()) + .containsExactly(seeded.digest()); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + } + } + + @Test + void competingTransferCreatorsAndLostBeginReplyKeepOneOriginalIntent() throws Exception { + try (var proof = new TransferSqlProof(); + ExecutorService executor = Executors.newFixedThreadPool(2)) { + proof.seedUndeliveredDispatch(proof.execution); + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var other = proof.transfers(proof.sql); + Future first = + executor.submit(() -> beginAfterBarrier(proof, proof.transfers, ready, start)); + Future second = + executor.submit(() -> beginAfterBarrier(proof, other, ready, start)); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + UUID retained = first.get(10, TimeUnit.SECONDS); + assertThat(second.get(10, TimeUnit.SECONDS)).isEqualTo(retained); + String original = proof.transferImage(retained); + assertThatThrownBy( + () -> { + other.within( + transferDeadline(), ignored -> other.begin(proof.scope, proof.prior)); + throw new IllegalStateException("Controlled lost begin reply after committed readback"); + }) + .hasMessage("Controlled lost begin reply after committed readback"); + var recreated = proof.transfers(proof.sql); + assertThat( + recreated.within( + transferDeadline(), ignored -> recreated.begin(proof.scope, proof.prior))) + .isEqualTo(retained); + assertThat(proof.transferImage(retained)).isEqualTo(original); + assertThat( + proof.sql.fetchSingle("SELECT count(*) FROM game_session_region_owner_transfer") + .get(0, Long.class)) + .isEqualTo(1L); + } + } + + @Test + void boundedCensusAndVerificationResumeBeyondThirtyTwoWithoutLosingAnyOriginal() throws Exception { + try (var proof = new TransferSqlProof()) { + // Controlled reservation envelopes seed SQL custody, not Account-authorized multiattempt + // behavior. Every candidate, bridge, mapping and owner source is retained by its real owner. + List originals = new ArrayList<>(); + for (int index = 0; index < 65; index++) { + var original = proof.newControlledExecution(); + originals.add(original); + proof.seedUndeliveredDispatch(original); + } + UUID id = proof.begin(); + var first = proof.captureAndFence(id); + assertThat(first).hasSize(32); + assertThatThrownBy( + () -> + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id))) + .isInstanceOf(IllegalStateException.class); + proof.recreateTransferOwners(); + assertThat(proof.begin()).isEqualTo(id); + assertThat(proof.captureAndFence(id)).hasSize(32); + assertThatThrownBy( + () -> + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id))) + .isInstanceOf(IllegalStateException.class); + proof.recreateTransferOwners(); + assertThat(proof.captureAndFence(id)).hasSize(1); + assertThat(proof.captureAndFence(id)).isEmpty(); + + List captured = new ArrayList<>(); + long cursor = -1; + for (int size : List.of(32, 32, 1)) { + long after = cursor; + var page = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.page(id, after)); + assertThat(page).hasSize(size); + captured.addAll(page.stream().map(item -> item.execution().digest()).toList()); + cursor = page.getLast().ordinal(); + } + assertThat(captured) + .containsExactlyInAnyOrderElementsOf( + originals.stream().map(OriginalNewCapacityExecution::digest).toList()); + assertThat(cursor).isEqualTo(64L); + assertThat( + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id))) + .isEqualTo(-1L); + proof.verifyPage(id); + assertThat( + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id))) + .isFalse(); + assertThatThrownBy(() -> proof.install(id)).isInstanceOf(IllegalStateException.class); + proof.recreateTransferOwners(); + assertThat( + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id))) + .isEqualTo(31L); + proof.verifyPage(id); + assertThat( + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id))) + .isFalse(); + proof.recreateTransferOwners(); + proof.verifyPage(id); + assertThat( + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id))) + .isTrue(); + var installed = proof.install(id); + assertThat(installed.executorFence()).isGreaterThan(proof.prior.executorFence()); + assertThat(proof.currentOwner()).isEqualTo(installed); + assertThat(proof.transfers.readCurrent(id, 64).controlState()).isEqualTo("COMPLETED"); + assertThat( + proof.sql.fetchSingle( + "SELECT count(*) FROM game_session_region_owner_transfer_item" + + " WHERE transfer_id=? AND fence_readback IS NOT NULL AND verified_round IS NOT NULL", + id) + .get(0, Long.class)) + .isEqualTo(65L); + assertThat( + proof.sql.fetch("SELECT status FROM game_session_original_new_capacity_execution") + .getValues("status", String.class)) + .containsOnly("INSTALL_DISPATCHED"); + } + } + + @Test + void finalQualificationRechecksLostFenceBeyondTheFirstPageWithoutRecreatingIt() throws Exception { + try (var proof = new TransferSqlProof()) { + for (int index = 0; index < 33; index++) { + proof.seedUndeliveredDispatch(proof.newControlledExecution()); + } + UUID id = proof.begin(); + assertThat(proof.captureAndFence(id)).hasSize(32); + assertThat(proof.captureAndFence(id)).hasSize(1); + proof.verifyPage(id); + proof.recreateTransferOwners(); + proof.verifyPage(id); + assertThat( + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id))) + .isTrue(); + var last = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.page(id, 31).getFirst()); + assertThat(last.ordinal()).isEqualTo(32L); + String receipt = proof.itemImage(id); + proof.losePhysicalExecution(last.execution()); + proof.recreateTransferOwners(); + assertThatThrownBy(() -> proof.install(id)).isInstanceOf(IllegalStateException.class); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + assertThat(proof.transfers.readCurrent(id, 32).controlState()).isEqualTo("FROZEN"); + assertThat(proof.physicalExecutionExists(last.execution())).isFalse(); + assertThat(proof.itemImage(id)).isEqualTo(receipt); + assertThat(proof.begin()).isEqualTo(id); + assertThat(proof.captureAndFence(id)).isEmpty(); + assertThat(proof.physicalExecutionExists(last.execution())).isFalse(); + } + } + + @Test + void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + String original = proof.originalImage(); + assertSqlGuard(() -> proof.rawReplaceOwner("unretained-successor", "e".repeat(64))); + UUID id = proof.begin(); + assertSqlGuard(() -> proof.rawReplaceOwner("frozen-successor", "e".repeat(64))); + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer SET state='COMPLETED'," + + " new_owner_id='forged-successor',new_owner_fence=?,new_lease_correlation=?," + + " incarnation_digest=?,verification_round=?,verification_complete=true WHERE transfer_id=?", + proof.prior.executorFence().longValueExact() + 1, + "e".repeat(64), + "sha256:" + "a".repeat(64), + UUID.randomUUID(), + id)); + assertThat(proof.originalImage()).isEqualTo(original); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + proof.captureAndFence(id); + proof.verifyPage(id); + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + var installed = proof.install(id); + String completed = proof.transferImage(id); + assertSqlGuard(() -> proof.rawReplaceOwner("different-successor", "f".repeat(64))); + assertThat(proof.currentOwner()).isEqualTo(installed); + assertThat(proof.transferImage(id)).isEqualTo(completed); + } + } + + @Test + void recreatedRepositoryRetainsLostFenceReplyAndImmutableOriginalReceiptsAndCompletion() + throws Exception { + try (var proof = new TransferSqlProof()) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var item = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id).getFirst()); + String original = proof.originalImage(); + assertThatThrownBy( + () -> { + proof.fence(item); + // The SQL receipt has committed, but the caller did not receive its result. + throw new IllegalStateException("Controlled lost retained fence reply"); + }) + .hasMessage("Controlled lost retained fence reply"); + String receipt = proof.itemImage(id); + proof.recreateTransferOwners(); + assertThat(proof.begin()).isEqualTo(id); + var replay = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.page(id, -1).getFirst()); + assertThat(replay.execution().canonicalBytes()).containsExactly(item.execution().canonicalBytes()); + proof.fence(replay); + assertThat(proof.itemImage(id)).isEqualTo(receipt); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_original_new_capacity_execution SET selected_owner_id='changed' WHERE execution_digest=?", + proof.execution.digest())); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer SET intent_digest=? WHERE transfer_id=?", + "sha256:" + "f".repeat(64), + id)); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer_item SET canonical_execution=? WHERE transfer_id=?", + "changed-original".getBytes(StandardCharsets.UTF_8), + id)); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer_item SET fence_readback=? WHERE transfer_id=?", + "changed-readback".getBytes(StandardCharsets.UTF_8), + id)); + for (String table : + List.of( + "game_session_original_new_capacity_execution", + "game_session_region_owner_transfer", + "game_session_region_owner_transfer_item")) { + assertSqlGuard(() -> proof.sql.execute("DELETE FROM " + table)); + assertSqlGuard(() -> proof.sql.execute("TRUNCATE TABLE " + table + " CASCADE")); + } + assertThat(proof.originalImage()).isEqualTo(original); + assertThat(proof.itemImage(id)).isEqualTo(receipt); + proof.verifyPage(id); + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + var installed = proof.install(id); + String completion = proof.transferImage(id); + proof.recreateTransferOwners(); + assertThat(proof.transfers.readCurrent(id, 0).controlState()).isEqualTo("COMPLETED"); + assertThat(proof.transfers.readCurrent(id, 0).completionDigest()).isNotBlank(); + assertThatThrownBy( + () -> + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.capture(id))) + .isInstanceOf(IllegalStateException.class); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer SET new_owner_id='changed-successor' WHERE transfer_id=?", + id)); + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_owner_transfer_item SET verified_round=? WHERE transfer_id=?", + UUID.randomUUID(), + id)); + assertThat(proof.transferImage(id)).isEqualTo(completion); + assertThat(proof.originalImage()).isEqualTo(original); + assertThat(proof.currentOwner()).isEqualTo(installed); + } + } + + private static UUID beginAfterBarrier( + TransferSqlProof proof, + CanonicalGameplayRegionOwnerTransferRepository transfers, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + assertThat(start.await(5, TimeUnit.SECONDS)).isTrue(); + return transfers.within( + transferDeadline(), ignored -> transfers.begin(proof.scope, proof.prior)); + } + + private static void assertDatabaseWaitsFor(DSLContext sql, int blockerPid) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + do { + if (Boolean.TRUE.equals( + sql.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity" + + " WHERE datname=current_database() AND wait_event_type='Lock'" + + " AND ? = ANY(pg_blocking_pids(pid)))", + blockerPid) + .get(0, Boolean.class))) return; + Thread.sleep(10); + } while (System.nanoTime() < deadline); + throw new AssertionError("The competing owner did not physically wait on the held region row"); + } + + private static void assertSqlGuard(Runnable action) { + assertThatThrownBy(action::run) + .rootCause() + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + failure -> assertThat(failure.getSQLState()).isEqualTo("23514")); + } + + private static long transferDeadline() { + return System.currentTimeMillis() + 5_000; + } + + /** Holds the actual owner's SELECT FOR UPDATE after PostgreSQL has granted its row lock. */ + private static final class RegionRowLockGate extends DefaultExecuteListener + implements AutoCloseable { + private final AtomicBoolean first = new AtomicBoolean(true); + private final AtomicInteger pid = new AtomicInteger(); + private final CountDownLatch locked = new CountDownLatch(1); + private final CountDownLatch resume = new CountDownLatch(1); + + DSLContext attach(DSLContext sql) { + return DSL.using( + sql.configuration().derive(new DefaultExecuteListenerProvider(this))); + } + + @Override + public void executeEnd(ExecuteContext context) { + String statement = context.sql(); + if (statement == null + || !statement.contains("game_session_region_runtime_status") + || !statement.contains("FOR UPDATE") + || !first.compareAndSet(true, false)) return; + try (var query = context.connection().createStatement(); + var result = query.executeQuery("SELECT pg_backend_pid()")) { + assertThat(result.next()).isTrue(); + pid.set(result.getInt(1)); + locked.countDown(); + if (!resume.await(4, TimeUnit.SECONDS)) { + throw new AssertionError("Region-row test gate was not released"); + } + } catch (java.sql.SQLException failure) { + throw new IllegalStateException("Could not observe actual PostgreSQL lock owner", failure); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Region-row test gate was interrupted", interrupted); + } + } + + void awaitLock() throws InterruptedException { + assertThat(locked.await(3, TimeUnit.SECONDS)).isTrue(); + } + + int backendPid() { + return pid.get(); + } + + void release() { + resume.countDown(); + } + + @Override + public void close() { + release(); + } + } + + /** + * Actual SQL, candidate/issuer/region and capacity/transfer owners over physical PostgreSQL and + * Redis. Account lease/reservation/OPEN, World/Entity RPC content, grant and attestor custody are + * controlled inputs. This proves SQL serialization/retention, not Account issuance or activation. + * The Redis test connection is privileged; ACL qualification belongs to its separate owner proof. + */ + private final class TransferSqlProof implements AutoCloseable { + private final Clock clock = Clock.systemUTC(); + private final RedisClient redis; + private final CanonicalGameplayAdmissionAbortCompositionFixture fixture; + private final CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources upstream; + private final DSLContext sql; + private final CanonicalGameplayTenantGameplayTagRepository tags; + private final RedisScriptCatalog scripts; + private final CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource admission; + private final CanonicalGameplayRegionRuntimeStatusRepository.Source scope; + private final CanonicalGameplayRegionRuntimeStatus prior; + private final OriginalNewCapacityExecution execution; + private CanonicalGameplayRegionOwnerTransferRepository transfers; + private CanonicalGameplayProtectedIncarnationReceiver receiver; + private CanonicalGameplayRegionOwnerTransferCoordinator coordinator; + + private TransferSqlProof() throws Exception { + redis = + RedisClient.create( + RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)) + .withTimeout(Duration.ofSeconds(5)) + .build()); + try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) { + connection.sync().flushdb(); + } + var dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(POSTGRES.getDriverClassName()); + String url = POSTGRES.getJdbcUrl(); + dataSource.setUrl(url + (url.contains("?") ? "&" : "?") + "currentSchema=public"); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + var candidate = + new Candidate( + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), + "SHARED", UUID.randomUUID(), 1L, UUID.randomUUID(), UUID.randomUUID(), + BigInteger.ONE, GameSessionAccountDelegationProfile.ISSUER, BigInteger.ONE, + BigInteger.ONE, BigInteger.ONE, BigInteger.valueOf(64)); + fixture = new CanonicalGameplayAdmissionAbortCompositionFixture(dataSource, candidate, redis); + sql = fixture.dsl(); + tags = new CanonicalGameplayTenantGameplayTagRepository(sql, "test", 1); + scripts = + RedisScriptCatalog.fromContributions( + List.of( + new net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution(), + new net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution(), + new net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution(), + new net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())); + upstream = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources( + sql, fixture.originalPreparedDecisionWithControlledAccountLease(), directory); + var decision = fixture.originalPreparedDecisionWithControlledAccountLease(); + var inventory = new CanonicalGameplayBindingInventoryRepository(sql); + CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create(redis, scripts, inventory, tags) + .installOnce(decision); + fixture.acknowledgeOriginalIssuer(); + new CanonicalGameplayAccountMemberRepairOwner(sql, redis, scripts) + .repair(fixture.transitionId()); + var region = + CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( + sql, redis, fixture.transitionId(), upstream.request, upstream.resolver, upstream.entity); + admission = inventory.readOriginalNewFinalAdmissionSource(decision); + scope = region.installation().source; + prior = new CanonicalGameplayRegionRuntimeStatusRepository(sql).find(scope).orElseThrow(); + execution = newControlledExecution(); + recreateTransferOwners(); + } + + private OriginalNewCapacityExecution newControlledExecution() { + var controlled = + CanonicalGameplayOriginalNewFinalAdmissionTestFixture.controlledCapacity(admission, clock); + return new OriginalNewCapacityExecution( + controlled.request(), controlled.reservation(), controlled.transitionId(), + controlled.candidateDigest(), prior.ownerInstanceId(), prior.executorFence().longValueExact()); + } + + private CanonicalGameplayRegionOwnerTransferRepository transfers(DSLContext context) { + return new CanonicalGameplayRegionOwnerTransferRepository(context, clock, tags); + } + + private CanonicalGameplayOriginalNewCapacityExecutionOwner capacity(DSLContext context) { + return new CanonicalGameplayOriginalNewCapacityExecutionOwner(context, redis, scripts, clock, tags); + } + + private void recreateTransferOwners() throws Exception { + transfers = transfers(sql); + receiver = new CanonicalGameplayControlledRegionTransferObservationFixture(clock).receiver(transfers, tags); + coordinator = new CanonicalGameplayRegionOwnerTransferCoordinator(sql, clock, transfers, capacity(sql), receiver); + } + + private UUID begin() { + return transfers.within(transferDeadline(), ignored -> transfers.begin(scope, prior)); + } + + private void seedUndeliveredDispatch(OriginalNewCapacityExecution original) { + // Controlled crash-window storage seed only. No guard is disabled, no AUTHORIZED result is + // invented, and this is not the real authorize path exercised by the two row-lock races. + sql.execute( + "INSERT INTO game_session_original_new_capacity_execution" + + " (tenant_id,request_id,admission_id,admission_attempt_id,transition_id,capacity_rearm_fence," + + " reservation_id,reservation_fence,mutation_digest,execution_digest,canonical_execution," + + " selected_owner_id,selected_owner_fence,tenant_gameplay_tag,status)" + + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,'INSTALL_DISPATCHED')", + original.request().identity().tenantId(), original.request().identity().requestId(), + original.request().identity().admissionId(), original.request().admissionAttemptId(), + original.transitionId(), original.request().capacityRearmFence(), + original.reservation().reservationId(), original.reservation().reservationFence(), + original.request().mutationDigest(), original.digest(), original.canonicalBytes(), + original.selectedOwnerId(), original.selectedOwnerFence(), + tags.assignmentForTransition(original.transitionId()).tenantGameplayTag()); + } + + private List captureAndFence(UUID id) { + var page = transfers.within(transferDeadline(), ignored -> transfers.capture(id)); + assertThat(page.size()).isLessThanOrEqualTo(32); + for (var item : page) fence(item); + return page; + } + + private void fence(CanonicalGameplayRegionOwnerTransferRepository.Item item) { + var before = receiver.observeForRegionOwnerTransfer(item.transferId(), item.ordinal(), transferDeadline()); + var actual = capacity(sql).fenceForTransfer(item, transferDeadline()); + var after = receiver.observeForRegionOwnerTransfer(item.transferId(), item.ordinal(), transferDeadline()); + transfers.within( + transferDeadline(), + ignored -> { + transfers.retainFence(item, actual, before, after); + return null; + }); + } + + private void verifyPage(UUID id) { + long cursor = transfers.within(transferDeadline(), ignored -> transfers.verificationCursor(id)); + var page = transfers.within(transferDeadline(), ignored -> transfers.page(id, cursor)); + assertThat(page.size()).isLessThanOrEqualTo(32); + for (var item : page) { + var before = receiver.observeForRegionOwnerTransfer(id, item.ordinal(), transferDeadline()); + var actual = capacity(sql).readTransferFence(item, transferDeadline()); + var after = receiver.observeForRegionOwnerTransfer(id, item.ordinal(), transferDeadline()); + transfers.within( + transferDeadline(), + ignored -> { + transfers.retainVerification(item, actual, before, after); + return null; + }); + } + } + + private CanonicalGameplayRegionRuntimeStatus install(UUID id) { + return coordinator.install(id, scope, prior, "e".repeat(64), "game-session-service", "sql-proof-successor", transferDeadline()); + } + + private CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback issuerOpen() { + var repository = new CanonicalGameplayIssuerAdmissionBarrierRepository(sql, tags, fixture.currentIssuerSource()); + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner(redis, scripts, repository, fixture.currentIssuerSource()) + .initializeAndRead(fixture.originalOperationId()); + } + + private CanonicalGameplayAccountInitialOpenProof.CurrentOpen controlledAccountOpen() { + var binding = admission.candidate().bindingIdentity(); + var assignment = tags.assignmentForTransition(fixture.transitionId()); + UUID initializer = UUID.randomUUID(); + String incarnation = "sha256:" + "a".repeat(64); + String key = "session:game:account-admission:{" + assignment.tenantGameplayTag() + "}:" + + binding.accountId() + ":" + binding.playableStateNamespaceId(); + Map fields = Map.of( + "schema", CanonicalGameplayAccountInitialBarrierValue.SCHEMA, "state", "OPEN", + "accountId", binding.accountId().toString(), "tenantId", binding.tenantId().toString(), + "playableStateNamespaceId", binding.playableStateNamespaceId().toString(), + "tenantGameplayTag", assignment.tenantGameplayTag(), "ownerOperationId", initializer.toString(), + "ownerFenceEpoch", "1", "incarnationDigest", incarnation); + try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) { + fields.forEach((field, value) -> connection.sync().hset(ascii(key), ascii(field), ascii(value))); + } + long now = clock.millis(); + return new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + initializer, UUID.randomUUID(), UUID.randomUUID(), 1L, binding.accountId(), binding.tenantId(), + binding.playableStateNamespaceId(), key, BigInteger.ONE, BigInteger.ONE, incarnation, + incarnation, incarnation, now, now + 60_000L, fields); + } + + private CanonicalGameplayRegionRuntimeStatus currentOwner() { + return new CanonicalGameplayRegionRuntimeStatusRepository(sql).find(scope).orElseThrow(); + } + + private String executionState(OriginalNewCapacityExecution original) { + Record row = sql.fetchOne("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", original.digest()); + return row == null ? null : row.get(0, String.class); + } + + private boolean physicalExecutionExists(OriginalNewCapacityExecution original) { + String tag = tags.assignmentForTransition(original.transitionId()).tenantGameplayTag(); + try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) { + return connection.sync().exists(ascii("session:game:capacity-execution:{" + tag + "}:" + original.request().admissionAttemptId())) != 0; + } + } + + private void losePhysicalExecution(OriginalNewCapacityExecution original) { + String tag = tags.assignmentForTransition(original.transitionId()).tenantGameplayTag(); + try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) { + assertThat( + connection.sync().del( + ascii("session:game:capacity-execution:{" + tag + "}:" + + original.request().admissionAttemptId()))) + .isEqualTo(1L); + } + } + + private void rawReplaceOwner(String owner, String correlation) { + sql.execute( + "UPDATE game_session_region_runtime_status SET owner_instance_id=?,executor_fence=nextval('game_session_region_executor_fence_seq'),lease_token_correlation=? WHERE tenant_id=? AND game_instance_id=? AND region_id=?", + owner, correlation, scope.tenantId(), scope.gameInstanceId(), scope.regionId()); + } + + private String originalImage() { + return sql.fetch("SELECT to_jsonb(e)::text FROM game_session_original_new_capacity_execution e ORDER BY execution_digest") + .getValues(0, String.class).toString(); + } + + private String transferImage(UUID id) { + return sql.fetchSingle("SELECT to_jsonb(t)::text FROM game_session_region_owner_transfer t WHERE transfer_id=?", id).get(0, String.class); + } + + private String itemImage(UUID id) { + return sql.fetch("SELECT to_jsonb(i)::text FROM game_session_region_owner_transfer_item i WHERE transfer_id=? ORDER BY target_ordinal", id) + .getValues(0, String.class).toString(); + } + + @Override + public void close() throws Exception { + try { + upstream.close(); + } finally { + try { + fixture.close(); + } finally { + redis.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + } + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + private CanonicalGameplayRegionRuntimeStatus installAfterBarrier( CanonicalGameplayRegionRuntimeStatus prior, String correlation, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 540bd9181e..ca90b468da 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(8); + assertThat(catalog.catalogEpoch()).isEqualTo(9); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -187,7 +187,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1061", "catalog-installation:1062", "catalog-installation:1063", - "catalog-installation:1064") + "catalog-installation:1064", + "catalog-installation:1065") .noneMatch( identity -> identity.contains(":1057:") @@ -197,7 +198,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1061:") || identity.contains(":1062:") || identity.contains(":1063:") - || identity.contains(":1064:")); + || identity.contains(":1064:") + || identity.contains(":1065:")); assertThat( f.dsl .fetchSingle( @@ -740,7 +742,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(8); + assertThat(original.catalog().catalogEpoch()).isEqualTo(9); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -783,7 +785,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow assertThat(f.evidence(original.request())) .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); assertThat(f.count(SNAPSHOTS)).isEqualTo(1); - assertThat(f.count(EPOCHS)).isEqualTo(8); + assertThat(f.count(EPOCHS)).isEqualTo(9); } } } @@ -874,7 +876,7 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } - for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064")) { + for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -897,11 +899,11 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "INSERT INTO " + f.history + "(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" - + " VALUES(10000,'1065','controlled later migration','SQL','V1065__probe.sql',1,current_user,0,true)"); + + " VALUES(10000,'1066','controlled later migration','SQL','V1066__probe.sql',1,current_user,0,true)"); assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } - for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064")) { + for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -974,9 +976,9 @@ void metadataEpochAndSnapshotGuardsRefuseMutationStaleBytesAndChangedExactSqlFra "INSERT INTO " + EPOCHS + "(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 9,catalog_bytes,catalog_digest FROM " + + " SELECT 10,catalog_bytes,catalog_digest FROM " + EPOCHS - + " WHERE catalog_epoch=8")) + + " WHERE catalog_epoch=9")) .hasMessageContaining("exact classified installed schema"); assertThatThrownBy( () -> @@ -1484,6 +1486,38 @@ void genuineV1063ToV1064CompletionRepairRetainsEpochSevenAndSnapshotsBeforeSeali } } + @Test + void genuineV1064ToV1065TransferFenceUpgradeRetainsOriginalRowsSnapshotsAndEpochs() { + try(Fixture f=fixture("1064")) { + f.populatePredecessor(); + var original=f.owner().capture(request()); + assertThat(original.catalog().catalogEpoch()).isEqualTo(8); + Map before=f.rows(f.tables()); + before.remove(f.history);before.remove(EPOCHS);before.remove(CLASSIFICATIONS); + var epochs=f.dsl.fetch("SELECT to_jsonb(e)::text||':'||xmin::text FROM " + EPOCHS + " e ORDER BY catalog_epoch").getValues(0,String.class); + var history=f.historyRows(false); + var classifications=f.classificationRows(); + migration(f.source,f.schema,f.history,"1065").migrate(); + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat(f.classificationRows()).containsAllEntriesOf(classifications).hasSize(classifications.size()+2); + assertThat(f.dsl.fetch("SELECT to_jsonb(e)::text||':'||xmin::text FROM " + EPOCHS + " e WHERE catalog_epoch<=8 ORDER BY catalog_epoch").getValues(0,String.class)).isEqualTo(epochs); + assertThat(f.historyRows(false)).hasSize(history.size()+1); + assertThat(f.historyRows(false).subList(0,history.size())).isEqualTo(history); + assertThat(f.evidence(original.request())).isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + var current=f.owner().capture(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(9); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + assertThat(current.catalog().families()).anyMatch(family -> family.familyId().equals("game_session_region_owner_transfer")) + .anyMatch(family -> family.familyId().equals("game_session_region_owner_transfer_item")); + assertThat(f.dsl.fetchSingle("SELECT catalog_bytes=gs_runtime_family_catalog_bytes(9) FROM " + EPOCHS + " WHERE catalog_epoch=9").get(0,Boolean.class)).isTrue(); + for(String table:List.of("game_session_region_owner_transfer","game_session_region_owner_transfer_item")) { + assertThat(f.count(table)).isZero(); + assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")).isInstanceOf(org.jooq.exception.DataAccessException.class); + } + migration(f.source,f.schema,f.history,"1065").validate(); + } + } + private static Request request() { return new Request(UUID.randomUUID(), "test"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java new file mode 100644 index 0000000000..61b1083963 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java @@ -0,0 +1,699 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Real RSA verification with controlled local signing custody, not deployed attestor proof. */ +class CanonicalGameplayRegionOwnerTransferObservationReceiverTest { + private static final String SCHEMA = "firemud.gs.protected-region-owner-transfer-read/v1"; + private static final String KEY_ID = "controlled-transfer-key"; + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final String OTHER_DIGEST = "sha256:" + "e".repeat(64); + private static final long NOW = 1_794_355_200_000L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final KeyPair KEYS = controlledKeys(); + + @Test + void verifiesExactFrozenItemTwiceWithRealSignatureAndCapsAtOperationDeadline() { + var fixture = new Fixture(); + var proof = fixture.observe(NOW + 500L); + + assertThat(proof.ownerKind()) + .isEqualTo(CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER); + assertThat(proof.regionOwnerTransferContext()).isSameAs(fixture.original); + assertThat(proof.operationId()).isEqualTo(fixture.original.transferId()); + assertThat(proof.requestId()).isEqualTo(fixture.original.requestId()); + assertThat(proof.accountId()).isEqualTo(fixture.original.accountId()); + assertThat(proof.targetOrdinal()).isEqualTo(fixture.original.targetOrdinal()); + assertThat(proof.tenantId()).isEqualTo(fixture.original.tenantId()); + assertThat(proof.playableStateNamespaceId()) + .isEqualTo(fixture.original.playableStateNamespaceId()); + assertThat(proof.tenantGameplayTag()).isEqualTo(fixture.original.tenantGameplayTag()); + assertThat(proof.issuedAtEpochMillis()).isEqualTo(NOW); + assertThat(proof.observedAtEpochMillis()).isEqualTo(NOW); + assertThat(proof.expiresAtEpochMillis()).isEqualTo(NOW + 500L); + assertThat(proof.observationNonce()).matches("[A-Za-z0-9_-]{43}"); + assertThat(proof.payloadDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(proof.incarnationDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(fixture.sourceReads).hasValue(2); + assertThat(fixture.channelCalls).hasValue(1); + assertThat(proof.operationFence()).isNull(); + assertThat(proof.plannedAccountAdmissionFence()).isNull(); + assertThat(proof.originalCallerContextId()).isNull(); + } + + @Test + void longerOperationStillUsesConfiguredObservationTtlAndFreshNonce() { + var fixture = new Fixture(); + var first = fixture.observe(NOW + 60_000L); + var second = fixture.observe(NOW + 60_000L); + assertThat(first.expiresAtEpochMillis()).isEqualTo(NOW + 30_000L); + assertThat(second.observationNonce()).isNotEqualTo(first.observationNonce()); + assertThat(second.incarnationDigest()).isEqualTo(first.incarnationDigest()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "firemud.gs.protected-incarnation-read/v1", + "firemud.gs.protected-initial-account-barrier-read/v1" + }) + void accountAndInitialSignedSchemasCannotBeReplayedAsTransfer(String schema) { + var fixture = new Fixture(); + fixture.mutation = root -> root.put("schema", schema); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(1); + } + + @ParameterizedTest + @ValueSource(strings = {"ACCOUNT_FENCE", "INITIAL_ACCOUNT_BARRIER"}) + void accountAndInitialOwnerProofsCannotBeReplayedAsTransfer(String kind) { + var fixture = new Fixture(); + fixture.mutation = root -> object(root, "owner").put("ownerKind", kind); + assertRejected(fixture); + } + + @Test + void transferSignedPurposeCannotBeReplayedThroughAccountReceiver() { + var fixture = new Fixture(); + var repository = mock(CanonicalGameplayAccountAdmissionBarrierRepository.class); + var intent = mock(CanonicalGameplayAccountAdmissionFenceIntent.class); + var context = fixture.original; + when(repository.readCurrentFenceIntent(context.transferId())).thenReturn(intent); + when(intent.operationId()).thenReturn(context.transferId()); + when(intent.requestId()).thenReturn(context.requestId()); + when(intent.accountId()).thenReturn(context.accountId()); + when(intent.operationFence()).thenReturn(BigInteger.ONE); + when(intent.plannedAccountAdmissionFence()).thenReturn(UUID.randomUUID()); + when(intent.inventorySnapshotRevision()).thenReturn(BigInteger.ONE); + when(intent.cohortDigest()).thenReturn(DIGEST); + when(intent.barrierTargetDigest()).thenReturn(DIGEST); + when(intent.state()) + .thenReturn(CanonicalGameplayAccountAdmissionFenceIntent.State.ACQUISITION_INTENT); + when(intent.barrierTargets()) + .thenReturn( + List.of( + CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( + context.targetOrdinal(), context.tenantId(), context.playableStateNamespaceId()))); + when(fixture.assignment.isBindingTransition()).thenReturn(false); + when(fixture.assignment.admissionFenceIntentOperationId()).thenReturn(context.transferId()); + when(fixture.assignment.barrierTargetOrdinal()).thenReturn(context.targetOrdinal()); + when(fixture.tags.assignmentForBarrierTarget(context.transferId(), context.targetOrdinal())) + .thenReturn(fixture.assignment); + var receiver = + new CanonicalGameplayProtectedIncarnationReceiver( + repository, fixture.tags, fixture::signed, fixture.trust(), fixture.clock); + assertThatThrownBy( + () -> receiver.observeForFenceTarget(context.transferId(), context.targetOrdinal())) + .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + } + + @Test + void transferSignedPurposeCannotBeReplayedThroughInitialReceiver() { + var fixture = new Fixture(); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + var context = fixture.original; + var initial = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitialObservationContext( + UUID.randomUUID(), + context.requestId(), + UUID.randomUUID(), + 1L, + context.accountId(), + context.tenantId(), + context.playableStateNamespaceId(), + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.ZERO, + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST); + when(repository.readCurrentObservationContext(context.requestId())).thenReturn(initial); + when(fixture.assignment.isBindingTransition()).thenReturn(false); + when(fixture.assignment.isInitialBarrierTarget()).thenReturn(true); + when(fixture.assignment.initialBarrierInitializerId()).thenReturn(initial.initializerId()); + when(fixture.assignment.initialBarrierOriginalRequestId()).thenReturn(context.requestId()); + when(fixture.tags.assignmentForInitialBarrierTarget(context.requestId())) + .thenReturn(fixture.assignment); + var receiver = + new CanonicalGameplayProtectedIncarnationReceiver( + repository, fixture.tags, fixture::signed, fixture.trust(), fixture.clock); + assertThatThrownBy(() -> receiver.observeForInitialAccountBarrier(context.requestId())) + .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "transferId", "transferIntentDigest", "frozenSourceDigest", "oldRegionOwnerId", + "oldRegionOwnerFence", "gameInstanceId", "regionId", "regionEpoch", "transitionId", + "requestId", "accountId", "executionDigest", "candidateDigest", "controlState", "completionDigest" + }) + void everySignedTransferOwnerTupleMutationRefuses(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> mutate(object(root, "owner"), field); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = { + "targetOrdinal", "tenantId", "playableStateNamespaceId", "tenantGameplayTag", + "workloadNamespace", "allocationVersion" + }) + void everySignedTargetTupleMutationRefuses(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> mutate(object(root, "target"), field); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = { + "deploymentIdentity", "deploymentGeneration", "canonicalNodeSet", "redisBuildIdentity", + "luaScriptRegistryVersion", "luaScriptRegistryDigest", "startupState", "bootGeneration", + "startupGeneration", "storageGeneration", "aofGeneration" + }) + void everySignedDeploymentIncarnationMutationRefuses(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> mutate(object(root, "targetDeploymentEvidence"), field); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = { + "attestorBinding", "attestorKeyId", "acceptedAttestationDigest", "observationNonce", + "coordOpsRoAclDigest", "coordRedisConfigObservedDigest" + }) + void signedTrustAndCorrelationMutationRefuses(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> mutate(root, field); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource( + strings = { + "isBindingTransition", "transitionId", "accountId", "tenantId", "gameInstanceId", + "playableStateNamespaceId", "tenantGameplayTag", "workloadNamespace", "allocationVersion" + }) + void independentlyResolvedAssignmentMustMatchBeforeRemoteCall(String field) { + var fixture = new Fixture(); + fixture.breakAssignment(field); + assertRejected(fixture); + assertThat(fixture.channelCalls).hasValue(0); + } + + @Test + void assignmentMustStillMatchAfterSignatureVerification() { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.breakAssignment("allocationVersion"); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + assertThat(fixture.channelCalls).hasValue(1); + } + + @ParameterizedTest + @ValueSource( + strings = { + "transferIntentDigest", "frozenSourceDigest", "oldRegionOwnerId", "oldRegionOwnerFence", + "regionEpoch", "executionDigest", "candidateDigest" + }) + void frozenSourceMutationDuringSignedReadRefuses(String field) { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.current.set(changed(fixture.original, field)); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void missingOrNoLongerFrozenSourceAfterSignatureCannotProduceProof() { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.current.set(null); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void unavailableCurrentSourceAfterSignatureCannotProduceProof() { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.sourceUnavailable = true; + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void sealedCompletedContextProducesOnlyItsExactReadOnlyCurrentnessObservation() { + var fixture = new Fixture("game-session-original", "COMPLETED", DIGEST); + var proof = fixture.observe(NOW + 1_000L); + assertThat(proof.regionOwnerTransferContext()).isSameAs(fixture.original); + assertThat(proof.regionOwnerTransferContext().controlState()).isEqualTo("COMPLETED"); + assertThat(proof.regionOwnerTransferContext().completionDigest()).isEqualTo(DIGEST); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void completionRacingSignatureVerificationCannotReuseFrozenContextProof() { + var fixture = new Fixture(); + fixture.afterSign = () -> fixture.current.set(withPhase(fixture.original, "COMPLETED", DIGEST)); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void changedSealedCompletionDuringObservationRefuses() { + var fixture = new Fixture("game-session-original", "COMPLETED", DIGEST); + fixture.afterSign = + () -> fixture.current.set(withPhase(fixture.original, "COMPLETED", OTHER_DIGEST)); + assertRejected(fixture); + assertThat(fixture.sourceReads).hasValue(2); + } + + @ParameterizedTest + @ValueSource(strings = {"FROZEN", "COMPLETED"}) + void signedProofCannotSubstituteTheOtherControlPhase(String currentPhase) { + var fixture = + new Fixture("game-session-original", currentPhase, "COMPLETED".equals(currentPhase) ? DIGEST : null); + fixture.mutation = + root -> { + var owner = object(root, "owner"); + boolean wasFrozen = "FROZEN".equals(currentPhase); + owner.put("controlState", wasFrozen ? "COMPLETED" : "FROZEN"); + owner.put("completionDigest", wasFrozen ? DIGEST : null); + }; + assertRejected(fixture); + } + + @Test + void completedSignedDigestMustMatchExactSealedCompletion() { + var fixture = new Fixture("game-session-original", "COMPLETED", DIGEST); + fixture.mutation = root -> object(root, "owner").put("completionDigest", OTHER_DIGEST); + assertRejected(fixture); + } + + @Test + void phaseAndCompletionFieldsMustBothBePresentEvenForFrozenNullCompletion() { + for (String field : List.of("controlState", "completionDigest")) { + var fixture = new Fixture(); + fixture.mutation = root -> object(root, "owner").remove(field); + assertRejected(fixture); + } + } + + @Test + void sourceContextRejectsUnsupportedOrMismatchedControlPhaseAndCompletion() { + var context = new Fixture().original; + assertThatThrownBy(() -> withPhase(context, "UNKNOWN", null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, null, null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "FROZEN", DIGEST)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "COMPLETED", null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "COMPLETED", "not-a-digest")).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void retainedTrimmedOwnerIdentityNeedsNoAdditionalCharacterGrammar() { + var fixture = new Fixture("game-session/worker α", "FROZEN", null); + var proof = fixture.observe(NOW + 1_000L); + assertThat(proof.regionOwnerTransferContext().oldRegionOwnerId()) + .isEqualTo("game-session/worker α"); + assertThat(fixture.sourceReads).hasValue(2); + } + + @Test + void retainedOwnerLengthUsesThePostgresCharacterBound() { + String ownerId = "\uD83C\uDFAE".repeat(120); + var fixture = new Fixture(ownerId, "FROZEN", null); + assertThat(fixture.observe(NOW + 1_000L).regionOwnerTransferContext().oldRegionOwnerId()) + .isEqualTo(ownerId); + assertThatThrownBy(() -> new Fixture(ownerId + "x", "FROZEN", null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource( + strings = {"issued", "observed-before", "observed-after", "expires", "expired", "clock-back"}) + void timeWindowMismatchOrDeadlineExpiryRefuses(String mode) { + var fixture = new Fixture(); + switch (mode) { + case "issued" -> fixture.mutation = root -> root.put("observationIssuedAtEpochMillis", NOW - 1L); + case "observed-before" -> + fixture.mutation = root -> root.put("observationObservedAtEpochMillis", NOW - 1L); + case "observed-after" -> + fixture.mutation = root -> root.put("observationObservedAtEpochMillis", NOW + 1_001L); + case "expires" -> + fixture.mutation = root -> root.put("observationExpiresAtEpochMillis", NOW + 999L); + case "expired" -> fixture.afterSign = () -> fixture.now.set(NOW + 1_000L); + case "clock-back" -> fixture.afterSign = () -> fixture.now.set(NOW - 1L); + default -> throw new IllegalArgumentException(mode); + } + assertRejected(fixture); + } + + @Test + void expiredOperationNeverReadsSourceOrCallsChannel() { + var fixture = new Fixture(); + assertThatThrownBy(() -> fixture.observe(NOW)) + .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + assertThat(fixture.sourceReads).hasValue(0); + assertThat(fixture.channelCalls).hasValue(0); + } + + @Test + void sourceReadCannotRenewAnOperationThatExpiredBeforeChannelDispatch() { + var fixture = new Fixture(); + fixture.onSourceRead = () -> fixture.now.set(NOW + 1_000L); + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + assertThat(fixture.channelCalls).hasValue(0); + } + + @ParameterizedTest + @ValueSource(strings = {"root", "owner", "target", "targetDeploymentEvidence"}) + void signedUnknownFieldsAreRejectedInEveryClosedObject(String object) { + var fixture = new Fixture(); + fixture.mutation = + root -> ("root".equals(object) ? root : object(root, object)).put("unknown", "value"); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource(strings = {"operationId", "operationFence", "initializerId", "originalAttemptFence", "progressCursor", "completedCount"}) + void accountInitialAndMutableProgressFieldsAreNotTransferOwnerFields(String field) { + var fixture = new Fixture(); + fixture.mutation = root -> object(root, "owner").put(field, "unexpected"); + assertRejected(fixture); + } + + @ParameterizedTest + @ValueSource(strings = {"signature", "unpinned", "noncanonical", "duplicate", "oversized", "utf8"}) + void cryptographicCanonicalParsingAndSizeFailuresRefuse(String mode) { + var fixture = new Fixture(); + fixture.encodingFailure = mode; + assertRejected(fixture); + } + + @Test + void ambientTransactionRefusesBeforeReadingSqlOrCallingChannel() { + var fixture = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clear(); + } + assertThat(fixture.sourceReads).hasValue(0); + assertThat(fixture.channelCalls).hasValue(0); + } + + @Test + void sourceContextRejectsInvalidUuidFenceEpochDigestAndBoundedIdentifiers() { + var context = new Fixture().original; + for (String field : + List.of("nil-transfer", "negative-ordinal", "zero-fence", "zero-epoch", "digest", "owner", "owner-null", "owner-blank", "owner-untrimmed", "workload", "allocation")) { + assertThatThrownBy(() -> invalid(context, field)).isInstanceOf(IllegalArgumentException.class); + } + } + + private static void assertRejected(Fixture fixture) { + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + } + + private static CanonicalGameplayRegionOwnerTransferObservationSource.Context changed( + CanonicalGameplayRegionOwnerTransferObservationSource.Context c, String field) { + return new CanonicalGameplayRegionOwnerTransferObservationSource.Context( + c.transferId(), c.targetOrdinal(), + "transferIntentDigest".equals(field) ? OTHER_DIGEST : c.transferIntentDigest(), + "frozenSourceDigest".equals(field) ? OTHER_DIGEST : c.frozenSourceDigest(), + "oldRegionOwnerId".equals(field) ? "different-owner" : c.oldRegionOwnerId(), + "oldRegionOwnerFence".equals(field) ? c.oldRegionOwnerFence() + 1L : c.oldRegionOwnerFence(), + c.tenantId(), c.gameInstanceId(), c.regionId(), + "regionEpoch".equals(field) ? c.regionEpoch() + 1L : c.regionEpoch(), + c.transitionId(), c.requestId(), c.accountId(), c.playableStateNamespaceId(), + "executionDigest".equals(field) ? OTHER_DIGEST : c.executionDigest(), + "candidateDigest".equals(field) ? OTHER_DIGEST : c.candidateDigest(), + c.tenantGameplayTag(), c.workloadNamespace(), c.allocationVersion(), c.controlState(), c.completionDigest()); + } + + private static CanonicalGameplayRegionOwnerTransferObservationSource.Context withPhase( + CanonicalGameplayRegionOwnerTransferObservationSource.Context c, String phase, String completionDigest) { + return new CanonicalGameplayRegionOwnerTransferObservationSource.Context( + c.transferId(), c.targetOrdinal(), c.transferIntentDigest(), c.frozenSourceDigest(), + c.oldRegionOwnerId(), c.oldRegionOwnerFence(), c.tenantId(), c.gameInstanceId(), c.regionId(), + c.regionEpoch(), c.transitionId(), c.requestId(), c.accountId(), c.playableStateNamespaceId(), + c.executionDigest(), c.candidateDigest(), c.tenantGameplayTag(), c.workloadNamespace(), + c.allocationVersion(), phase, completionDigest); + } + + private static CanonicalGameplayRegionOwnerTransferObservationSource.Context invalid( + CanonicalGameplayRegionOwnerTransferObservationSource.Context c, String field) { + String owner = + switch (field) { + case "owner" -> "x".repeat(121); + case "owner-null" -> null; + case "owner-blank" -> " "; + case "owner-untrimmed" -> " owner "; + default -> c.oldRegionOwnerId(); + }; + return new CanonicalGameplayRegionOwnerTransferObservationSource.Context( + "nil-transfer".equals(field) ? new UUID(0L, 0L) : c.transferId(), + "negative-ordinal".equals(field) ? -1L : c.targetOrdinal(), + "digest".equals(field) ? "sha256:" + "A".repeat(64) : c.transferIntentDigest(), + c.frozenSourceDigest(), owner, + "zero-fence".equals(field) ? 0L : c.oldRegionOwnerFence(), + c.tenantId(), c.gameInstanceId(), c.regionId(), + "zero-epoch".equals(field) ? 0L : c.regionEpoch(), + c.transitionId(), c.requestId(), c.accountId(), c.playableStateNamespaceId(), + c.executionDigest(), c.candidateDigest(), c.tenantGameplayTag(), + "workload".equals(field) ? "INVALID_NAMESPACE" : c.workloadNamespace(), + "allocation".equals(field) ? 0 : c.allocationVersion(), c.controlState(), c.completionDigest()); + } + + @SuppressWarnings("unchecked") + private static Map object(Map root, String field) { + return (Map) root.get(field); + } + + private static void mutate(Map object, String field) { + Object old = object.get(field); + Object replacement; + if (old instanceof Number number) { + replacement = number.longValue() + 1L; + } else if (old instanceof List) { + replacement = List.of("different-node"); + } else if (old instanceof String text && text.startsWith("sha256:")) { + replacement = OTHER_DIGEST; + } else { + replacement = "different-" + old; + } + object.put(field, replacement); + } + + private static KeyPair controlledKeys() { + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } catch (java.security.GeneralSecurityException failure) { + throw new IllegalStateException("Controlled test key generation failed", failure); + } + } + + private static final class Fixture { + private final AtomicLong now = new AtomicLong(NOW); + private final Clock clock = mock(Clock.class); + private final AtomicInteger sourceReads = new AtomicInteger(); + private final AtomicInteger channelCalls = new AtomicInteger(); + private final CanonicalGameplayRegionOwnerTransferObservationSource.Context original; + private final AtomicReference current; + private final CanonicalGameplayTenantGameplayTagRepository tags = + mock(CanonicalGameplayTenantGameplayTagRepository.class); + private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + private Consumer> mutation = root -> {}; + private Runnable afterSign = () -> {}; + private Runnable onSourceRead = () -> {}; + private boolean sourceUnavailable; + private String encodingFailure = ""; + + private Fixture() { + this("game-session-original", "FROZEN", null); + } + + private Fixture(String ownerId, String controlState, String completionDigest) { + UUID tenant = UUID.randomUUID(); + original = + new CanonicalGameplayRegionOwnerTransferObservationSource.Context( + UUID.randomUUID(), 3L, DIGEST, DIGEST, ownerId, 7L, + tenant, UUID.randomUUID(), UUID.randomUUID(), 11L, UUID.randomUUID(), + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), DIGEST, DIGEST, + "g1-" + tenant.toString().replace("-", ""), "test-workload", 1, controlState, completionDigest); + current = new AtomicReference<>(original); + when(clock.millis()).thenAnswer(invocation -> now.get()); + when(tags.assignmentForTransition(original.transitionId())).thenReturn(assignment); + when(assignment.isBindingTransition()).thenReturn(true); + when(assignment.transitionId()).thenReturn(original.transitionId()); + when(assignment.accountId()).thenReturn(original.accountId()); + when(assignment.tenantId()).thenReturn(original.tenantId()); + when(assignment.gameInstanceId()).thenReturn(original.gameInstanceId()); + when(assignment.playableStateNamespaceId()).thenReturn(original.playableStateNamespaceId()); + when(assignment.tenantGameplayTag()).thenReturn(original.tenantGameplayTag()); + when(assignment.workloadNamespace()).thenReturn(original.workloadNamespace()); + when(assignment.allocationVersion()).thenReturn(original.allocationVersion()); + } + + private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observe(long deadline) { + return CanonicalGameplayProtectedIncarnationReceiver.forRegionOwnerTransfer( + (transferId, ordinal) -> { + sourceReads.incrementAndGet(); + onSourceRead.run(); + if (sourceUnavailable) { + throw new CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException( + "Controlled current SQL transfer source became unavailable"); + } + return current.get(); + }, + tags, this::signed, trust(), clock) + .observeForRegionOwnerTransfer(original.transferId(), original.targetOrdinal(), deadline); + } + + private void breakAssignment(String field) { + switch (field) { + case "isBindingTransition" -> when(assignment.isBindingTransition()).thenReturn(false); + case "transitionId" -> when(assignment.transitionId()).thenReturn(UUID.randomUUID()); + case "accountId" -> when(assignment.accountId()).thenReturn(UUID.randomUUID()); + case "tenantId" -> when(assignment.tenantId()).thenReturn(UUID.randomUUID()); + case "gameInstanceId" -> when(assignment.gameInstanceId()).thenReturn(UUID.randomUUID()); + case "playableStateNamespaceId" -> + when(assignment.playableStateNamespaceId()).thenReturn(UUID.randomUUID()); + case "tenantGameplayTag" -> when(assignment.tenantGameplayTag()).thenReturn("g1-" + "f".repeat(32)); + case "workloadNamespace" -> when(assignment.workloadNamespace()).thenReturn("different-workload"); + case "allocationVersion" -> when(assignment.allocationVersion()).thenReturn(2); + default -> throw new IllegalArgumentException(field); + } + } + + private CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration trust() { + var evidence = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-target", "generation-1", List.of("redis-a", "redis-b"), + "redis-build", "registry-1", DIGEST, "READY", "boot-1", "startup-1", + "storage-1", "aof-1"); + return new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + "controlled-transfer-binding", DIGEST, Map.of(KEY_ID, (RSAPublicKey) KEYS.getPublic()), + evidence, DIGEST, DIGEST, 16 * 1024, 2, Duration.ofSeconds(30)); + } + + private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation signed( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + channelCalls.incrementAndGet(); + Map root = payload(request); + mutation.accept(root); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + switch (encodingFailure) { + case "noncanonical" -> bytes = (new String(bytes, StandardCharsets.UTF_8) + " ").getBytes(StandardCharsets.UTF_8); + case "duplicate" -> bytes = ("{\"schema\":\"duplicate\"," + new String(bytes, StandardCharsets.UTF_8).substring(1)).getBytes(StandardCharsets.UTF_8); + case "oversized" -> bytes = new byte[17 * 1024]; + case "utf8" -> bytes = new byte[] {(byte) 0xc3, (byte) 0x28}; + default -> { } + } + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(KEYS.getPrivate()); + signer.update(bytes); + byte[] signature = signer.sign(); + if ("signature".equals(encodingFailure)) signature[0] ^= 1; + afterSign.run(); + return new CanonicalGameplayProtectedIncarnationReceiver.SignedObservation( + "unpinned".equals(encodingFailure) ? "unknown-key" : KEY_ID, bytes, signature); + } catch (java.security.GeneralSecurityException | java.io.IOException failure) { + throw new IllegalStateException("Controlled transfer signing failed", failure); + } + } + + private Map payload( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + var c = original; + Map owner = new LinkedHashMap<>(); + owner.put("ownerKind", "REGION_OWNER_TRANSFER"); + owner.put("transferId", c.transferId().toString()); + owner.put("transferIntentDigest", c.transferIntentDigest()); + owner.put("frozenSourceDigest", c.frozenSourceDigest()); + owner.put("oldRegionOwnerId", c.oldRegionOwnerId()); + owner.put("oldRegionOwnerFence", c.oldRegionOwnerFence()); + owner.put("gameInstanceId", c.gameInstanceId().toString()); + owner.put("regionId", c.regionId().toString()); + owner.put("regionEpoch", c.regionEpoch()); + owner.put("transitionId", c.transitionId().toString()); + owner.put("requestId", c.requestId().toString()); + owner.put("accountId", c.accountId().toString()); + owner.put("executionDigest", c.executionDigest()); + owner.put("candidateDigest", c.candidateDigest()); + owner.put("controlState", c.controlState()); + owner.put("completionDigest", c.completionDigest()); + Map target = new LinkedHashMap<>(); + target.put("targetOrdinal", c.targetOrdinal()); + target.put("tenantId", c.tenantId().toString()); + target.put("playableStateNamespaceId", c.playableStateNamespaceId().toString()); + target.put("tenantGameplayTag", c.tenantGameplayTag()); + target.put("workloadNamespace", c.workloadNamespace()); + target.put("allocationVersion", c.allocationVersion()); + var e = request.expectedEvidence(); + Map evidence = new LinkedHashMap<>(); + evidence.put("deploymentIdentity", e.deploymentIdentity()); + evidence.put("deploymentGeneration", e.deploymentGeneration()); + evidence.put("canonicalNodeSet", e.canonicalNodeSet()); + evidence.put("redisBuildIdentity", e.redisBuildIdentity()); + evidence.put("luaScriptRegistryVersion", e.luaScriptRegistryVersion()); + evidence.put("luaScriptRegistryDigest", e.luaScriptRegistryDigest()); + evidence.put("startupState", e.startupState()); + evidence.put("bootGeneration", e.bootGeneration()); + evidence.put("startupGeneration", e.startupGeneration()); + evidence.put("storageGeneration", e.storageGeneration()); + evidence.put("aofGeneration", e.aofGeneration()); + Map root = new LinkedHashMap<>(); + root.put("schema", SCHEMA); + root.put("attestorBinding", request.attestorBinding()); + root.put("attestorKeyId", KEY_ID); + root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); + root.put("observationNonce", request.nonce()); + root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis()); + root.put("owner", owner); + root.put("target", target); + root.put("targetDeploymentEvidence", evidence); + root.put("coordOpsRoAclDigest", request.coordOpsRoAclDigest()); + root.put("coordRedisConfigObservedDigest", request.coordRedisConfigObservedDigest()); + return root; + } + } +} From db6bcd74f8094a9fcdb83e33db772520af90225d Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 03:11:04 +1300 Subject: [PATCH 21/52] Prepare formatted normal-handoff recovery with focused signed-observation proof 103 focused unit cases, Java compilation, jOOQ generation, formatting and docs pass. New physical PostgreSQL/Redis proof and complete static analysis remain pending; no activation. --- .../player-access-and-session.md | 4 +- ...alAdmissionCompositionIntegrationTest.java | 63 +- ...playOriginalNewCapacityExecutionOwner.java | 58 +- ...ayOriginalNewFinalAdmissionRedisOwner.java | 28 +- ...lGameplayProtectedIncarnationReceiver.java | 15 +- .../CanonicalGameplayRegionLeaseOwner.java | 51 +- ...ameplayRegionOwnerTransferCoordinator.java | 190 ++-- ...yRegionOwnerTransferObservationSource.java | 7 +- ...GameplayRegionOwnerTransferRepository.java | 932 +++++++++++++----- ...GameplayRegionRuntimeStatusRepository.java | 68 +- ...alNewFinalAdmissionCompositionFixture.java | 93 +- ...alNewFinalAdmissionLuaIntegrationTest.java | 10 +- ...NewFinalAdmissionOwnerIntegrationTest.java | 689 +++++++++---- ...GameplayRegionOwnerCompositionFixture.java | 37 +- ...untimeStatusRepositoryIntegrationTest.java | 342 +++++-- ...eFamilyCatalogPostgresIntegrationTest.java | 73 +- ...nOwnerTransferObservationReceiverTest.java | 283 ++++-- 17 files changed, 2106 insertions(+), 837 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 42a998c921..4bc8b35dcc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -50,9 +50,9 @@ Receiving from parent `3cfe7a68`, all seven [original-NEW Account/Game Session c 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. Ordinary replacement remains blocked by unresolved custody; the separately prepared normal-handoff path below excludes future effects without resolving the retained outcome. Five new component regressions cover these crash windows, owner movement and missing-evidence refusal; physical execution of this new batch remains unverified. 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. +Remaining qualification includes these exact-source checks, complete Account rearm/stale-worker concurrency through the final owner, deployed source/PKI/Redis custody, source registration and fresh packaged runtime proof. Positive terminal replay is durable only after independent immutable actual-outcome retention. The owner-local continuation now recovers a positive final effect across both pre-receipt and pre-retention crash windows without the original credential or grant; the existing closure lifecycle calls it before refusing negative closure. Ordinary replacement remains blocked by unresolved custody; the separately prepared normal-handoff path below excludes future effects without resolving the retained outcome. The original crash-window, owner-movement and missing-evidence regressions passed within all 22 physical cases of `CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest` on published `c86fae5627edae298e4bbe081091a6bfb3a515ef`: [Validation run 43014202533](https://github.com/benhook1013/FireMUD/actions/runs/43014202533), Game Session partition 3 job `130501225239`, artifact `13853837619`, with zero failures, errors or skips. The retained manifest and source blobs bind that artifact to synthetic merge `6729f6ec9d93ff3cd2b2c266e54488aa1829f6d3` and its exact `d8a3912268398daeb0e0ac90a3e8e48d1dd04301` / `c86fae5627edae298e4bbe081091a6bfb3a515ef` parents. This is historical component proof, not physical execution of the subsequent normal-handoff batch. Serving retirement must await retained proof, and this does not supply the missing real cleanup or teardown owner. Missing current region-owner/fence evidence also stays indeterminate. A genuine never-admitted cleanup owner for this already-acknowledged PROVISIONAL boundary is missing: the existing owner supports only untouched PREPARED dispatches and must not be forced across that boundary. Complete finalized-usage retirement on actual runtime teardown remains unfinished. No bean, scheduled worker, production route or public admission is enabled, and issuer-partition capacity is not tenant capacity. -The new [normal-handoff source](../../architecture/microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing) prepares V1065 transfer custody, bounded region census/verification, real signed transfer-purpose currentness and deny-only tenant-slot fencing through the actual lease-owner path. New physical definitions cover abrupt process stop after the real SQL authorization commit, native handoff, predecessor Lua rejection, positive-retention refusal, current marker loss, Account hold/quarantine preservation and retained catalog upgrade. This edit batch has not been compiled, formatted or executed; it establishes no new passing proof. The multi-page/concurrency definitions are also authored with controlled reservation envelopes, separate from the actual Account composition; compilation, physical execution and final exact-source qualification remain pending. Production attestor custody, storage continuity, registration, runtime activation and admission remain held. +The new [normal-handoff source](../../architecture/microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing) prepares V1065 transfer custody, bounded region census/verification, real signed transfer-purpose currentness and deny-only tenant-slot fencing through the actual lease-owner path. New physical definitions cover abrupt process stop after the real SQL authorization commit, native handoff, predecessor Lua rejection, positive-retention refusal, current marker loss, Account hold/quarantine preservation and retained catalog upgrade. On the integrated local postimages, canonical V1065 jOOQ generation, production and Game Session integration-source compilation, both service Java format checks and documentation checks pass. The focused signed transfer-observation suite passes 101 cases and the Account workload-identity suite passes two cases, with zero failures, errors or skips. Initial compilation exposed a Jackson 3 checked-exception mismatch and generic AssertJ inference in the concurrency definitions; both were corrected before the passing checks. The multi-page/concurrency definitions use controlled reservation envelopes, separate from actual Account composition. All new physical PostgreSQL/Redis execution, complete affected static analysis and final published-source qualification remain pending. Production attestor custody, storage continuity, registration, runtime activation and admission remain held. The prepared recovery policy `capacity-recovery/1` retains an immutable observation per current fenced claim, with twelve bounded read attempts and the original reconciliation deadline. Unavailable, invalid, late and ambiguous reads never release the hold. Exhaustion durably quarantines the original reservation, fence, exact payload and full held quota; replay performs no further source call. No operator release, automatic expiry, replacement reservation or unaudited quarantine-resolution API is supplied. The physical fixture includes controlled-source exhaustion/quarantine proof definitions; these remain unrun. Genuine audited Account remediation from independent owner evidence remains an activation prerequisite. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 5b11824a87..1387ba3db7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -216,29 +216,56 @@ void retainedActualCasEvidenceStillFinalizesCapacityAfterControlledServingRetire @Test void actualNormalHandoffKeepsUnknownCapacityHeldAndBoundedRecoveryQuarantinesSameReservation() throws Exception { - try(Session session=session()) { - var reservation=session.gs.authorizeThenFenceAndHandoffWithoutFinal( - session.client,session.jwks,session.jwt,session.capacityClient,session.capacityRequest, - System.currentTimeMillis()+5000L); - assertThatThrownBy(() -> session.capacityRead.readExact(session.capacityRequest,reservation,CLOCK.instant().plusSeconds(5))) + try (Session session = session()) { + var reservation = + session.gs.authorizeThenFenceAndHandoffWithoutFinal( + session.client, + session.jwks, + session.jwt, + session.capacityClient, + session.capacityRequest, + System.currentTimeMillis() + 5000L); + assertThatThrownBy( + () -> + session.capacityRead.readExact( + session.capacityRequest, reservation, CLOCK.instant().plusSeconds(5))) .isInstanceOf(RuntimeException.class); - TenantCapacityAdmission.Result result=reservation; - for(int attempt=0;attempt<12;attempt++) { - var recovery=new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( - session.capacityOwner,session.dsl,session.capacityRead, - Clock.offset(CLOCK,Duration.ofSeconds(attempt*20L))); - result=recovery.reconcile(session.capacityRequest, - net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker.NoCommitAction.RELEASE); + TenantCapacityAdmission.Result result = reservation; + for (int attempt = 0; attempt < 12; attempt++) { + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + session.capacityOwner, + session.dsl, + session.capacityRead, + Clock.offset(CLOCK, Duration.ofSeconds(attempt * 20L))); + result = + recovery.reconcile( + session.capacityRequest, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); assertThat(result.reservationId()).isEqualTo(reservation.reservationId()); assertThat(result.reservationFence()).isEqualTo(reservation.reservationFence()); assertThat(result.admissionAttemptId()).isEqualTo(reservation.admissionAttemptId()); } - assertThat(result.state()).isEqualTo(TenantCapacityAdmission.State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); - var usage=session.dsl.fetchSingle("SELECT held_units,used_units FROM account_tenant_capacity_usage WHERE tenant_uuid=? AND owner_service='game-session-service'",reservation.identity().tenantId()); - assertThat(usage.get("held_units",Long.class)).isOne(); - assertThat(usage.get("used_units",Long.class)).isZero(); - assertThat(session.dsl.fetchCount(org.jooq.impl.DSL.table("account_tenant_capacity_reservations"))).isOne(); - assertThat(session.dsl.fetchSingle("SELECT execution_status FROM account_tenant_capacity_reservations WHERE reservation_id=?",reservation.reservationId()).get(0,String.class)) + assertThat(result.state()) + .isEqualTo(TenantCapacityAdmission.State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); + var usage = + session.dsl.fetchSingle( + "SELECT held_units,used_units FROM account_tenant_capacity_usage WHERE tenant_uuid=? AND owner_service='game-session-service'", + reservation.identity().tenantId()); + assertThat(usage.get("held_units", Long.class)).isOne(); + assertThat(usage.get("used_units", Long.class)).isZero(); + assertThat( + session.dsl.fetchCount( + org.jooq.impl.DSL.table("account_tenant_capacity_reservations"))) + .isOne(); + assertThat( + session + .dsl + .fetchSingle( + "SELECT execution_status FROM account_tenant_capacity_reservations WHERE reservation_id=?", + reservation.reservationId()) + .get(0, String.class)) .isEqualTo("OWNER_EXECUTION_PENDING"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index fd446824d0..e15e90f176 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -588,7 +588,8 @@ private static void requireSelectedOwner( .equals(java.math.BigInteger.valueOf(current.get("region_epoch", Long.class))) || !Boolean.FALSE.equals(current.get("paused", Boolean.class)) || CanonicalGameplayRegionOwnerTransferRepository.frozen( - tx, binding.tenantId(), binding.gameInstanceId(), binding.regionId())) throw unavailable(); + tx, binding.tenantId(), binding.gameInstanceId(), binding.regionId())) + throw unavailable(); } CanonicalGameplayOriginalNewCapacityExecutionOwner forTransferBudget( @@ -598,15 +599,18 @@ CanonicalGameplayOriginalNewCapacityExecutionOwner forTransferBudget( } /** Fences future work without resolving the retained original or its Account capacity hold. */ - TransferFence fenceForTransfer(CanonicalGameplayRegionOwnerTransferRepository.Item item, long deadline) { + TransferFence fenceForTransfer( + CanonicalGameplayRegionOwnerTransferRepository.Item item, long deadline) { if (budget == null) return within(deadline, owner -> owner.fenceForTransfer(item, deadline)); budget.check(); var execution = item.execution(); Record row = find(sql(), execution); if (row == null) throw unavailable(); exact(row, execution); - long result = scopedFinalOwner().fenceCapacityExecutionOnce( - execution, item.candidate(), item.assignment(), budget.absoluteDeadlineMillis()); + long result = + scopedFinalOwner() + .fenceCapacityExecutionOnce( + execution, item.candidate(), item.assignment(), budget.absoluteDeadlineMillis()); if (result == 2) { // Merely seeing a COMMITTED hash must not release old-generation custody. retainCommittedBeforeCleanup(execution.request(), execution.reservation(), deadline); @@ -617,31 +621,38 @@ TransferFence fenceForTransfer(CanonicalGameplayRegionOwnerTransferRepository.It } /** Read only. In particular, a lost/reset denying hash is never recreated by verification. */ - TransferFence readTransferFence(CanonicalGameplayRegionOwnerTransferRepository.Item item, long deadline) { + TransferFence readTransferFence( + CanonicalGameplayRegionOwnerTransferRepository.Item item, long deadline) { if (budget == null) return within(deadline, owner -> owner.readTransferFence(item, deadline)); budget.check(); var execution = item.execution(); - Map physical = readExecution(execution, item.assignment().tenantGameplayTag()); + Map physical = readExecution(execution, item.assignment().tenantGameplayTag()); String state = text(physical.get("state")); if ("FENCED_INDETERMINATE".equals(state)) { - if (physical.size() != 3 || !Arrays.equals(execution.canonicalBytes(),physical.get("binding")) + if (physical.size() != 3 + || !Arrays.equals(execution.canonicalBytes(), physical.get("binding")) || !execution.digest().equals(text(physical.get("digest")))) throw unavailable(); } else { if (!"COMMITTED".equals(state) && !"CLOSED".equals(state)) throw unavailable(); exactPhysicalBinding(physical, execution, state); Record retained = find(sql(), execution); - if (retained == null || !state.equals(retained.get("status",String.class))) throw unavailable(); - // The immutable terminal reader independently proves the full retained positive/negative result. + if (retained == null || !state.equals(retained.get("status", String.class))) + throw unavailable(); + // The immutable terminal reader independently proves the full retained positive/negative + // result. readExact(execution.request(), execution.reservation(), false); } var output = new java.io.ByteArrayOutputStream(); - physical.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> { - for (byte[] value : new byte[][] {bytes(entry.getKey()), entry.getValue()}) { - output.writeBytes(bytes(Integer.toString(value.length))); - output.write(':'); - output.writeBytes(value); - } - }); + physical.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .forEach( + entry -> { + for (byte[] value : new byte[][] {bytes(entry.getKey()), entry.getValue()}) { + output.writeBytes(bytes(Integer.toString(value.length))); + output.write(':'); + output.writeBytes(value); + } + }); return new TransferFence(execution.digest(), output.toByteArray()); } @@ -649,12 +660,19 @@ TransferFence readTransferFence(CanonicalGameplayRegionOwnerTransferRepository.I static final class TransferFence { private final String executionDigest; private final byte[] canonicalReadback; + private TransferFence(String executionDigest, byte[] canonicalReadback) { - this.executionDigest=executionDigest; - this.canonicalReadback=canonicalReadback.clone(); + this.executionDigest = executionDigest; + this.canonicalReadback = canonicalReadback.clone(); + } + + String executionDigest() { + return executionDigest; + } + + byte[] canonicalReadback() { + return canonicalReadback.clone(); } - String executionDigest() { return executionDigest; } - byte[] canonicalReadback() { return canonicalReadback.clone(); } } private CurrentOwner currentOwner(CanonicalGameplayOriginalNewCandidate candidate) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index c322060aac..04e89b7dca 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -361,14 +361,32 @@ long fenceCapacityExecutionOnce( long absoluteDeadlineMillis) { requireNoAmbientTransaction(); requireAssignment(assignment, candidate); - String accountKey = ACCOUNT_PREFIX + "{" + assignment.tenantGameplayTag() + "}:" - + assignment.accountId() + ":" + assignment.playableStateNamespaceId(); + String accountKey = + ACCOUNT_PREFIX + + "{" + + assignment.tenantGameplayTag() + + "}:" + + assignment.accountId() + + ":" + + assignment.playableStateNamespaceId(); var keys = requireKeys(candidate, assignment, accountKey, execution); byte[] script = scriptSource(requireDescriptor()); try { - return execute(script, keys, candidate, assignment, candidate.canonicalBytes(), - characterProjection(candidate), ascii("{}"), 1, ascii("{}"), ascii("{}"), - absoluteDeadlineMillis, ascii("transfer-fence"), execution, "FENCE"); + return execute( + script, + keys, + candidate, + assignment, + candidate.canonicalBytes(), + characterProjection(candidate), + ascii("{}"), + 1, + ascii("{}"), + ascii("{}"), + absoluteDeadlineMillis, + ascii("transfer-fence"), + execution, + "FENCE"); } finally { wipe(script); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java index 97b6563493..0828a818ad 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -290,7 +290,8 @@ private VerifiedIncarnation observeCurrentContext( issuedAt, before.ownerKind() == OwnerKind.REGION_OWNER_TRANSFER ? Math.min( - trustedConfiguration.observationTtlMillis(), absoluteDeadlineMillis - issuedAt) + trustedConfiguration.observationTtlMillis(), + absoluteDeadlineMillis - issuedAt) : trustedConfiguration.observationTtlMillis()); } catch (ArithmeticException overflow) { throw new ObservationUnavailableException("Protected observation time window is invalid"); @@ -465,7 +466,8 @@ private CurrentContext loadInitialCurrentContext(UUID originalRequestId) { null); } - private CurrentContext loadRegionOwnerTransferCurrentContext(UUID transferId, long targetOrdinal) { + private CurrentContext loadRegionOwnerTransferCurrentContext( + UUID transferId, long targetOrdinal) { requireNoAmbientTransaction(); CanonicalGameplayRegionOwnerTransferObservationSource.Context context = regionOwnerTransferSource.readCurrent(transferId, targetOrdinal); @@ -1158,7 +1160,8 @@ record CurrentContext( || !accountId.equals(regionOwnerTransferContext.accountId()) || targetOrdinal != regionOwnerTransferContext.targetOrdinal() || !tenantId.equals(regionOwnerTransferContext.tenantId()) - || !playableStateNamespaceId.equals(regionOwnerTransferContext.playableStateNamespaceId()) + || !playableStateNamespaceId.equals( + regionOwnerTransferContext.playableStateNamespaceId()) || !tenantGameplayTag.equals(regionOwnerTransferContext.tenantGameplayTag()) || !workloadNamespace.equals(regionOwnerTransferContext.workloadNamespace()) || allocationVersion != regionOwnerTransferContext.allocationVersion() @@ -1173,7 +1176,8 @@ record CurrentContext( || sourceControlEpoch != null || accountLoginEvidenceDigest != null || sourceControlDigest != null) { - throw new IllegalArgumentException("Transfer context must use its separate typed owner arm"); + throw new IllegalArgumentException( + "Transfer context must use its separate typed owner arm"); } } if (ownerKind != OwnerKind.REGION_OWNER_TRANSFER && regionOwnerTransferContext != null) { @@ -1231,7 +1235,8 @@ OwnerKind ownerKind() { CanonicalGameplayRegionOwnerTransferObservationSource.Context regionOwnerTransferContext() { if (context.ownerKind() != OwnerKind.REGION_OWNER_TRANSFER) { - throw new ObservationRejectedException("Protected observation is not a region-owner transfer"); + throw new ObservationRejectedException( + "Protected observation is not a region-owner transfer"); } return context.regionOwnerTransferContext(); } 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 d6ec1e851f..d049f4df3d 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 @@ -71,14 +71,19 @@ Installation installForTransition( Installation existingRegionInstallation, UUID transitionId, CanonicalInitialPlayerLocationRequest worldRequest) { - return installForTransition(existingRegionInstallation,transitionId,worldRequest,null,Long.MAX_VALUE); + return installForTransition( + existingRegionInstallation, transitionId, worldRequest, null, Long.MAX_VALUE); } - /** Explicit normal handoff, using actual acquire/install/revalidation and transfer-purpose proof. */ + /** + * Explicit normal handoff, using actual acquire/install/revalidation and transfer-purpose proof. + */ Installation installForTransition( - Installation existingRegionInstallation, UUID transitionId, + Installation existingRegionInstallation, + UUID transitionId, CanonicalInitialPlayerLocationRequest worldRequest, - CanonicalGameplayRegionOwnerTransferCoordinator transferOwner,long absoluteDeadlineMillis) { + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long absoluteDeadlineMillis) { requireNoAmbientTransaction(); Objects.requireNonNull(transitionId, "transitionId"); Objects.requireNonNull(worldRequest, "worldRequest"); @@ -93,7 +98,7 @@ Installation installForTransition( CanonicalGameplayRegionRuntimeStatus prior = statusRepository.find(source).orElse(null); if (prior == null && expectedRegionEpoch != 1L) throw unavailable(); if (prior != null && prior.regionEpoch() != expectedRegionEpoch) throw unavailable(); - UUID transferId=null; + UUID transferId = null; CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; @@ -198,12 +203,13 @@ Installation installForTransition( throw unavailable(); } if (existingRegionInstallation == null) { - if(transferOwner!=null) { + if (transferOwner != null) { // Preserve ordinary timeline/incarnation qualification before any transfer effect. // A lost completion reply is not permission to freeze/advance its successor again. - if(transferOwner.alreadyCompleted(prior,runtimeIdentity.serviceInstanceId(),absoluteDeadlineMillis)) + if (transferOwner.alreadyCompleted( + prior, runtimeIdentity.serviceInstanceId(), absoluteDeadlineMillis)) throw unavailable(); - transferId=transferOwner.advance(source,prior,absoluteDeadlineMillis); + transferId = transferOwner.advance(source, prior, absoluteDeadlineMillis); } grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); } else { @@ -228,17 +234,24 @@ Installation installForTransition( redisOwner.verifyInitializedTimeline(grant, preparation); Instant installedAt = clock.instant(); - CanonicalGameplayRegionRuntimeStatus installed = transferId==null - ? statusRepository.installOwner( - source, - expectedRegionEpoch, - prior, - grant.tokenCorrelation(), - grant.ownerService(), - grant.ownerInstanceId(), - installedAt) - : transferOwner.install(transferId,source,prior,grant.tokenCorrelation(), - grant.ownerService(),grant.ownerInstanceId(),absoluteDeadlineMillis); + CanonicalGameplayRegionRuntimeStatus installed = + transferId == null + ? statusRepository.installOwner( + source, + expectedRegionEpoch, + prior, + grant.tokenCorrelation(), + grant.ownerService(), + grant.ownerInstanceId(), + installedAt) + : transferOwner.install( + transferId, + source, + prior, + grant.tokenCorrelation(), + grant.ownerService(), + grant.ownerInstanceId(), + absoluteDeadlineMillis); redisOwner.requireCurrent(grant); redisOwner.verifyInitializedTimeline(grant, preparation); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java index 7e4fa3495a..ce3eaca3df 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java @@ -16,98 +16,136 @@ final class CanonicalGameplayRegionOwnerTransferCoordinator { private final CanonicalGameplayProtectedIncarnationReceiver observations; CanonicalGameplayRegionOwnerTransferCoordinator( - DSLContext dsl, Clock clock, CanonicalGameplayRegionOwnerTransferRepository repository, + DSLContext dsl, + Clock clock, + CanonicalGameplayRegionOwnerTransferRepository repository, CanonicalGameplayOriginalNewCapacityExecutionOwner capacity, CanonicalGameplayProtectedIncarnationReceiver observations) { - this.dsl=Objects.requireNonNull(dsl); - this.clock=Objects.requireNonNull(clock); - this.repository=Objects.requireNonNull(repository); - this.capacity=Objects.requireNonNull(capacity); - this.observations=Objects.requireNonNull(observations); + this.dsl = Objects.requireNonNull(dsl); + this.clock = Objects.requireNonNull(clock); + this.repository = Objects.requireNonNull(repository); + this.capacity = Objects.requireNonNull(capacity); + this.observations = Objects.requireNonNull(observations); } - /** Read-only lost-completion gate; it never authorizes another generation or recreates a grant. */ - boolean alreadyCompleted(CanonicalGameplayRegionRuntimeStatus prior,String requestingOwner,long deadline) { - return repository.completedForCurrent(prior,requestingOwner,deadline); + /** + * Read-only lost-completion gate; it never authorizes another generation or recreates a grant. + */ + boolean alreadyCompleted( + CanonicalGameplayRegionRuntimeStatus prior, String requestingOwner, long deadline) { + return repository.completedForCurrent(prior, requestingOwner, deadline); } /** A bounded step; incomplete progress remains durable and the caller must resume this intent. */ - UUID advance(CanonicalGameplayRegionRuntimeStatusRepository.Source source, - CanonicalGameplayRegionRuntimeStatus prior, long deadline) { - return repository.within(deadline, budget -> { - UUID transfer=repository.begin(source,prior); - if(transfer==null) return null; - var owner=capacity.forTransferBudget(budget); - for (var item:repository.capture(transfer)) { - var before=observe(item,budget.absoluteDeadlineMillis()); - var physical=owner.fenceForTransfer(item,budget.absoluteDeadlineMillis()); - var after=observe(item,budget.absoluteDeadlineMillis()); - repository.retainFence(item,physical,before,after); - } - // A verification round re-reads every retained marker, including older generations, - // through bounded restartable pages. It never reinstalls a missing retained fence. - long cursor=repository.verificationCursor(transfer); - List page=repository.page(transfer,cursor); - for (var item:page) { - var before=observe(item,budget.absoluteDeadlineMillis()); - var actual=owner.readTransferFence(item,budget.absoluteDeadlineMillis()); - var after=observe(item,budget.absoluteDeadlineMillis()); - repository.retainVerification(item,actual,before,after); - } - if (!repository.finishVerification(transfer)) throw held(); - return transfer; - }); + UUID advance( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + long deadline) { + return repository.within( + deadline, + budget -> { + UUID transfer = repository.begin(source, prior); + if (transfer == null) return null; + var owner = capacity.forTransferBudget(budget); + for (var item : repository.capture(transfer)) { + var before = observe(item, budget.absoluteDeadlineMillis()); + var physical = owner.fenceForTransfer(item, budget.absoluteDeadlineMillis()); + var after = observe(item, budget.absoluteDeadlineMillis()); + repository.retainFence(item, physical, before, after); + } + // A verification round re-reads every retained marker, including older generations, + // through bounded restartable pages. It never reinstalls a missing retained fence. + long cursor = repository.verificationCursor(transfer); + List page = + repository.page(transfer, cursor); + for (var item : page) { + var before = observe(item, budget.absoluteDeadlineMillis()); + var actual = owner.readTransferFence(item, budget.absoluteDeadlineMillis()); + var after = observe(item, budget.absoluteDeadlineMillis()); + repository.retainVerification(item, actual, before, after); + } + if (!repository.finishVerification(transfer)) throw held(); + return transfer; + }); } CanonicalGameplayRegionRuntimeStatus install( - UUID transferId, CanonicalGameplayRegionRuntimeStatusRepository.Source source, - CanonicalGameplayRegionRuntimeStatus prior, String leaseCorrelation, - String ownerService,String ownerInstanceId,long deadline) { - return repository.within(deadline,budget -> { - var first=repository.page(transferId,-1); - if (first.isEmpty()) { - return new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) - .installOwner(source,prior.regionEpoch(),prior,leaseCorrelation,ownerService, - ownerInstanceId,clock.instant()); - } - var before=observe(first.getFirst(),budget.absoluteDeadlineMillis()); - var owner=capacity.forTransferBudget(budget); - // Stream the entire frozen inventory through bounded pages under this one absolute - // operation budget. Earlier page receipts cannot hide a subsequently lost marker. - // An inventory that cannot be currently proved inside the deadline stays frozen. - var page=first; - while(!page.isEmpty()) { - budget.check(); - for(var item:page) { - var actual=owner.readTransferFence(item,budget.absoluteDeadlineMillis()); - repository.requireRetainedPhysical(item,actual); - } - page=repository.page(transferId,page.getLast().ordinal()); - } - var after=observe(first.getFirst(),budget.absoluteDeadlineMillis()); - var proof=repository.qualify(transferId,before,after,budget.absoluteDeadlineMillis()); - var installed=new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) - .installOwner(source,prior.regionEpoch(),prior,leaseCorrelation,ownerService, - ownerInstanceId,clock.instant(),proof); - // Completion grants no historical-fence exemption. The source now independently checks - // the immutable completed successor against the actual current region owner. - var completed=observations.observeForRegionOwnerTransfer( - transferId,first.getFirst().ordinal(),budget.absoluteDeadlineMillis()); - if(!after.incarnationDigest().equals(completed.incarnationDigest())) throw held(); - owner.readTransferFence(first.getFirst(),budget.absoluteDeadlineMillis()); - return installed; - }); + UUID transferId, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + String leaseCorrelation, + String ownerService, + String ownerInstanceId, + long deadline) { + return repository.within( + deadline, + budget -> { + var first = repository.page(transferId, -1); + if (first.isEmpty()) { + return new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) + .installOwner( + source, + prior.regionEpoch(), + prior, + leaseCorrelation, + ownerService, + ownerInstanceId, + clock.instant()); + } + var before = observe(first.getFirst(), budget.absoluteDeadlineMillis()); + var owner = capacity.forTransferBudget(budget); + // Stream the entire frozen inventory through bounded pages under this one absolute + // operation budget. Earlier page receipts cannot hide a subsequently lost marker. + // An inventory that cannot be currently proved inside the deadline stays frozen. + var page = first; + while (!page.isEmpty()) { + budget.check(); + for (var item : page) { + var actual = owner.readTransferFence(item, budget.absoluteDeadlineMillis()); + repository.requireRetainedPhysical(item, actual); + } + page = repository.page(transferId, page.getLast().ordinal()); + } + var after = observe(first.getFirst(), budget.absoluteDeadlineMillis()); + var proof = + repository.qualify(transferId, before, after, budget.absoluteDeadlineMillis()); + var installed = + new CanonicalGameplayRegionRuntimeStatusRepository(budget.sql(dsl)) + .installOwner( + source, + prior.regionEpoch(), + prior, + leaseCorrelation, + ownerService, + ownerInstanceId, + clock.instant(), + proof); + // Completion grants no historical-fence exemption. The source now independently checks + // the immutable completed successor against the actual current region owner. + var completed = + observations.observeForRegionOwnerTransfer( + transferId, first.getFirst().ordinal(), budget.absoluteDeadlineMillis()); + if (!after.incarnationDigest().equals(completed.incarnationDigest())) throw held(); + owner.readTransferFence(first.getFirst(), budget.absoluteDeadlineMillis()); + return installed; + }); } private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observe( - CanonicalGameplayRegionOwnerTransferRepository.Item item,long deadline) { - var value=observations.observeForRegionOwnerTransfer(item.transferId(),item.ordinal(),deadline); - if(!repository.readCurrent(item.transferId(),item.ordinal()).equals(value.regionOwnerTransferContext()) - || value.ownerKind()!=CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER) throw held(); + CanonicalGameplayRegionOwnerTransferRepository.Item item, long deadline) { + var value = + observations.observeForRegionOwnerTransfer(item.transferId(), item.ordinal(), deadline); + if (!repository + .readCurrent(item.transferId(), item.ordinal()) + .equals(value.regionOwnerTransferContext()) + || value.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER) + throw held(); return value; } private static IllegalStateException held() { - return new IllegalStateException("Normal region handoff requires complete current transfer evidence"); + return new IllegalStateException( + "Normal region handoff requires complete current transfer evidence"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java index bbf846b543..4d9c6bd96b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java @@ -18,8 +18,8 @@ default CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( /** * One frozen item and its original owner, with its exact current control phase. A COMPLETED * context requires independently current sealed successor evidence and is read-only currentness, - * never permission for mutation. Mutable per-item progress is deliberately excluded: completing - * a different item must not change this item's observation identity. + * never permission for mutation. Mutable per-item progress is deliberately excluded: completing a + * different item must not change this item's observation identity. */ record Context( UUID transferId, @@ -57,7 +57,8 @@ record Context( requireDigest(executionDigest, "executionDigest"); requireDigest(candidateDigest, "candidateDigest"); if (targetOrdinal < 0L || oldRegionOwnerFence <= 0L || regionEpoch <= 0L) { - throw new IllegalArgumentException("Transfer ordinal, owner fence or region epoch is invalid"); + throw new IllegalArgumentException( + "Transfer ordinal, owner fence or region epoch is invalid"); } if (oldRegionOwnerId == null || oldRegionOwnerId.isBlank() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index ce0d4551ab..d238fcf447 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -25,7 +25,9 @@ import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; -/** Retained normal-handoff custody. It supplies neither an execution outcome nor Account authority. */ +/** + * Retained normal-handoff custody. It supplies neither an execution outcome nor Account authority. + */ final class CanonicalGameplayRegionOwnerTransferRepository implements CanonicalGameplayRegionOwnerTransferObservationSource { static final int PAGE_SIZE = 32; @@ -54,7 +56,8 @@ final class CanonicalGameplayRegionOwnerTransferRepository this.tags = Objects.requireNonNull(tags); } - T within(long deadline, Function work) { + T within( + long deadline, Function work) { noSql(); if (admitted.get() != null) return work.apply(admitted.get()); return CanonicalGameplayOriginalNewCapacityExecutionBudget.run( @@ -81,65 +84,138 @@ UUID begin( CanonicalGameplayRegionRuntimeStatus prior) { noSql(); String sourceDigest = sourceDigest(source, prior); - return sql().transactionResult( - configuration -> { - var tx = DSL.using(configuration); - requireOldOwner(tx, source, prior); - Record old = tx.fetchOne("SELECT * FROM " + TRANSFER + " WHERE old_owner_fence=?", prior.executorFence().longValueExact()); - if (old != null) { - if (!sourceDigest.equals(old.get("source_digest", String.class)) - || !"FROZEN".equals(old.get("state", String.class))) throw unavailable(); - return old.get("transfer_id", UUID.class); - } - if (!exists(tx,"SELECT 1" + PENDING, source.tenantId(),source.gameInstanceId(),source.regionId())) return null; - UUID id = UUID.randomUUID(); - String intentDigest = digest(bytes("region-owner-transfer/v1/" + id + "/" + sourceDigest)); - if (tx.execute( - "INSERT INTO " + TRANSFER - + " (transfer_id,tenant_id,game_instance_id,region_id,region_epoch,old_owner_id,old_owner_fence,old_lease_correlation,source_digest,intent_digest,state) VALUES (?,?,?,?,?,?,?,?,?,?,'FROZEN')", - id, source.tenantId(), source.gameInstanceId(), source.regionId(), prior.regionEpoch(), - prior.ownerInstanceId(), prior.executorFence().longValueExact(), prior.leaseTokenCorrelation(), sourceDigest, intentDigest) - != 1) throw unavailable(); - return id; - }); + return sql() + .transactionResult( + configuration -> { + var tx = DSL.using(configuration); + requireOldOwner(tx, source, prior); + Record old = + tx.fetchOne( + "SELECT * FROM " + TRANSFER + " WHERE old_owner_fence=?", + prior.executorFence().longValueExact()); + if (old != null) { + if (!sourceDigest.equals(old.get("source_digest", String.class)) + || !"FROZEN".equals(old.get("state", String.class))) throw unavailable(); + return old.get("transfer_id", UUID.class); + } + if (!exists( + tx, + "SELECT 1" + PENDING, + source.tenantId(), + source.gameInstanceId(), + source.regionId())) return null; + UUID id = UUID.randomUUID(); + String intentDigest = + digest(bytes("region-owner-transfer/v1/" + id + "/" + sourceDigest)); + if (tx.execute( + "INSERT INTO " + + TRANSFER + + " (transfer_id,tenant_id,game_instance_id,region_id,region_epoch,old_owner_id,old_owner_fence,old_lease_correlation,source_digest,intent_digest,state) VALUES (?,?,?,?,?,?,?,?,?,?,'FROZEN')", + id, + source.tenantId(), + source.gameInstanceId(), + source.regionId(), + prior.regionEpoch(), + prior.ownerInstanceId(), + prior.executorFence().longValueExact(), + prior.leaseTokenCorrelation(), + sourceDigest, + intentDigest) + != 1) throw unavailable(); + return id; + }); } - boolean completedForCurrent(CanonicalGameplayRegionRuntimeStatus prior,String requestingOwner,long deadline) { - return within(deadline,ignored -> exists(sql(),"SELECT 1 FROM " + TRANSFER + " WHERE tenant_id=? AND game_instance_id=? AND region_id=? AND state='COMPLETED' AND new_owner_id=? AND new_owner_id=? AND new_owner_fence=? AND new_lease_correlation=?", - prior.tenantId(),prior.gameInstanceId(),prior.regionId(),prior.ownerInstanceId(),requestingOwner, - prior.executorFence().longValueExact(),prior.leaseTokenCorrelation())); + boolean completedForCurrent( + CanonicalGameplayRegionRuntimeStatus prior, String requestingOwner, long deadline) { + return within( + deadline, + ignored -> + exists( + sql(), + "SELECT 1 FROM " + + TRANSFER + + " WHERE tenant_id=? AND game_instance_id=? AND region_id=? AND state='COMPLETED' AND new_owner_id=? AND new_owner_id=? AND new_owner_fence=? AND new_lease_correlation=?", + prior.tenantId(), + prior.gameInstanceId(), + prior.regionId(), + prior.ownerInstanceId(), + requestingOwner, + prior.executorFence().longValueExact(), + prior.leaseTokenCorrelation())); } - /** One bounded enrollment step. The final anti-join, not a cursor or page size, proves completeness. */ + /** + * One bounded enrollment step. The final anti-join, not a cursor or page size, proves + * completeness. + */ List capture(UUID transferId) { noSql(); - sql().transaction( - configuration -> { - var tx = DSL.using(configuration); - Record transfer = current(tx, transferId, true); - var rows = tx.fetch( - "SELECT DISTINCT e.execution_digest" + PENDING - + " AND NOT EXISTS (SELECT 1 FROM " + ITEM + " i WHERE i.transfer_id=? AND i.execution_digest=e.execution_digest)" - + " ORDER BY e.execution_digest LIMIT ?", - transfer.get("tenant_id", UUID.class), transfer.get("game_instance_id", UUID.class), - transfer.get("region_id", UUID.class), transferId, PAGE_SIZE); - long ordinal = tx.fetchSingle("SELECT coalesce(max(target_ordinal),-1) FROM " + ITEM + " WHERE transfer_id=?", transferId).get(0, Long.class); - for (Record row : rows) { - String executionDigest = row.get("execution_digest", String.class); - // The actual retained execution and original candidate, never a caller selector. - Record retained = tx.fetchSingle("SELECT canonical_execution,tenant_gameplay_tag FROM game_session_original_new_capacity_execution WHERE execution_digest=?", executionDigest); - var execution = decode(retained.get("canonical_execution", byte[].class)); - ordinal = Math.incrementExact(ordinal); - String tag = retained.get("tenant_gameplay_tag", String.class); - int allocation = Integer.parseInt(tag.substring(1, tag.indexOf('-'))); - tx.execute("INSERT INTO " + ITEM + " (transfer_id,target_ordinal,execution_digest,canonical_execution,candidate_digest,tenant_gameplay_tag,workload_namespace,allocation_version) VALUES (?,?,?,?,?,?,?,?)", - transferId, ordinal, executionDigest, execution.canonicalBytes(), - execution.candidateDigest(), tag, execution.request().targetNamespace(), allocation); - } - }); + sql() + .transaction( + configuration -> { + var tx = DSL.using(configuration); + Record transfer = current(tx, transferId, true); + var rows = + tx.fetch( + "SELECT DISTINCT e.execution_digest" + + PENDING + + " AND NOT EXISTS (SELECT 1 FROM " + + ITEM + + " i WHERE i.transfer_id=? AND i.execution_digest=e.execution_digest)" + + " ORDER BY e.execution_digest LIMIT ?", + transfer.get("tenant_id", UUID.class), + transfer.get("game_instance_id", UUID.class), + transfer.get("region_id", UUID.class), + transferId, + PAGE_SIZE); + long ordinal = + tx.fetchSingle( + "SELECT coalesce(max(target_ordinal),-1) FROM " + + ITEM + + " WHERE transfer_id=?", + transferId) + .get(0, Long.class); + for (Record row : rows) { + String executionDigest = row.get("execution_digest", String.class); + // The actual retained execution and original candidate, never a caller selector. + Record retained = + tx.fetchSingle( + "SELECT canonical_execution,tenant_gameplay_tag FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + executionDigest); + var execution = decode(retained.get("canonical_execution", byte[].class)); + ordinal = Math.incrementExact(ordinal); + String tag = retained.get("tenant_gameplay_tag", String.class); + int allocation = Integer.parseInt(tag.substring(1, tag.indexOf('-'))); + tx.execute( + "INSERT INTO " + + ITEM + + " (transfer_id,target_ordinal,execution_digest,canonical_execution,candidate_digest,tenant_gameplay_tag,workload_namespace,allocation_version) VALUES (?,?,?,?,?,?,?,?)", + transferId, + ordinal, + executionDigest, + execution.canonicalBytes(), + execution.candidateDigest(), + tag, + execution.request().targetNamespace(), + allocation); + } + }); List result = new ArrayList<>(); - for (Record row : sql().fetch("SELECT target_ordinal,execution_digest FROM " + ITEM + " WHERE transfer_id=? AND fence_readback IS NULL ORDER BY target_ordinal LIMIT ?", transferId, PAGE_SIZE)) { - result.add(loadItem(sql(), transferId, row.get("target_ordinal", Long.class), row.get("execution_digest", String.class))); + for (Record row : + sql() + .fetch( + "SELECT target_ordinal,execution_digest FROM " + + ITEM + + " WHERE transfer_id=? AND fence_readback IS NULL ORDER BY target_ordinal LIMIT ?", + transferId, + PAGE_SIZE)) { + result.add( + loadItem( + sql(), + transferId, + row.get("target_ordinal", Long.class), + row.get("execution_digest", String.class))); } return List.copyOf(result); } @@ -147,13 +223,28 @@ List capture(UUID transferId) { List page(UUID transferId, long afterOrdinal) { current(sql(), transferId, false); List result = new ArrayList<>(); - for (Record row : sql().fetch("SELECT target_ordinal,execution_digest FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal>? ORDER BY target_ordinal LIMIT ?", transferId, afterOrdinal, PAGE_SIZE)) { - result.add(loadItem(sql(), transferId, row.get("target_ordinal", Long.class), row.get("execution_digest", String.class))); + for (Record row : + sql() + .fetch( + "SELECT target_ordinal,execution_digest FROM " + + ITEM + + " WHERE transfer_id=? AND target_ordinal>? ORDER BY target_ordinal LIMIT ?", + transferId, + afterOrdinal, + PAGE_SIZE)) { + result.add( + loadItem( + sql(), + transferId, + row.get("target_ordinal", Long.class), + row.get("execution_digest", String.class))); } return List.copyOf(result); } - void retainFence(Item item, CanonicalGameplayOriginalNewCapacityExecutionOwner.TransferFence actual, + void retainFence( + Item item, + CanonicalGameplayOriginalNewCapacityExecutionOwner.TransferFence actual, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after) { var context = readCurrent(item.transferId(), item.ordinal()); @@ -161,36 +252,73 @@ void retainFence(Item item, CanonicalGameplayOriginalNewCapacityExecutionOwner.T requireObservation(context, after); if (!before.incarnationDigest().equals(after.incarnationDigest()) || !item.execution().digest().equals(actual.executionDigest())) throw unavailable(); - sql().transaction(configuration -> { - var tx = DSL.using(configuration); - Record transfer = current(tx, item.transferId(), true); - String retained = transfer.get("incarnation_digest", String.class); - if (retained != null && !retained.equals(after.incarnationDigest())) throw unavailable(); - tx.execute("UPDATE " + TRANSFER + " SET incarnation_digest=? WHERE transfer_id=? AND incarnation_digest IS NULL", after.incarnationDigest(), item.transferId()); - Record row = tx.fetchSingle("SELECT * FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=? FOR UPDATE", item.transferId(), item.ordinal()); - byte[] prior = row.get("fence_readback", byte[].class); - if (prior != null && !Arrays.equals(prior, actual.canonicalReadback())) throw unavailable(); - tx.execute("UPDATE " + ITEM + " SET fence_readback=?,incarnation_digest=?,before_payload_digest=?,after_payload_digest=? WHERE transfer_id=? AND target_ordinal=? AND fence_readback IS NULL", - actual.canonicalReadback(), after.incarnationDigest(), before.payloadDigest(), after.payloadDigest(), item.transferId(), item.ordinal()); - }); + sql() + .transaction( + configuration -> { + var tx = DSL.using(configuration); + Record transfer = current(tx, item.transferId(), true); + String retained = transfer.get("incarnation_digest", String.class); + if (retained != null && !retained.equals(after.incarnationDigest())) + throw unavailable(); + tx.execute( + "UPDATE " + + TRANSFER + + " SET incarnation_digest=? WHERE transfer_id=? AND incarnation_digest IS NULL", + after.incarnationDigest(), + item.transferId()); + Record row = + tx.fetchSingle( + "SELECT * FROM " + + ITEM + + " WHERE transfer_id=? AND target_ordinal=? FOR UPDATE", + item.transferId(), + item.ordinal()); + byte[] prior = row.get("fence_readback", byte[].class); + if (prior != null && !Arrays.equals(prior, actual.canonicalReadback())) + throw unavailable(); + tx.execute( + "UPDATE " + + ITEM + + " SET fence_readback=?,incarnation_digest=?,before_payload_digest=?,after_payload_digest=? WHERE transfer_id=? AND target_ordinal=? AND fence_readback IS NULL", + actual.canonicalReadback(), + after.incarnationDigest(), + before.payloadDigest(), + after.payloadDigest(), + item.transferId(), + item.ordinal()); + }); } /** Private capability is minted only after a complete current physical verification pass. */ - Completion qualify(UUID transferId, + Completion qualify( + UUID transferId, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, - CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after, long deadline) { - if (clock.millis() >= deadline || !before.incarnationDigest().equals(after.incarnationDigest()) + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after, + long deadline) { + if (clock.millis() >= deadline + || !before.incarnationDigest().equals(after.incarnationDigest()) || !"FROZEN".equals(before.regionOwnerTransferContext().controlState()) || !"FROZEN".equals(after.regionOwnerTransferContext().controlState())) throw unavailable(); requireObservation(readCurrent(transferId, before.targetOrdinal()), before); requireObservation(readCurrent(transferId, after.targetOrdinal()), after); Record transfer = current(sql(), transferId, false); - if (!before.incarnationDigest().equals(transfer.get("incarnation_digest", String.class))) throw unavailable(); + if (!before.incarnationDigest().equals(transfer.get("incarnation_digest", String.class))) + throw unavailable(); UUID round = transfer.get("verification_round", UUID.class); - if (round == null || !Boolean.TRUE.equals(transfer.get("verification_complete", Boolean.class)) - || exists(sql(),"SELECT 1 FROM " + ITEM + " WHERE transfer_id=? AND verified_round IS DISTINCT FROM ?", transferId, round)) throw unavailable(); + if (round == null + || !Boolean.TRUE.equals(transfer.get("verification_complete", Boolean.class)) + || exists( + sql(), + "SELECT 1 FROM " + ITEM + " WHERE transfer_id=? AND verified_round IS DISTINCT FROM ?", + transferId, + round)) throw unavailable(); requireComplete(sql(), transferId); - return new Completion(transferId, transfer.get("source_digest", String.class), after.incarnationDigest(), round, deadline); + return new Completion( + transferId, + transfer.get("source_digest", String.class), + after.incarnationDigest(), + round, + deadline); } long verificationCursor(UUID transferId) { @@ -198,254 +326,608 @@ long verificationCursor(UUID transferId) { requireComplete(sql(), transferId); if (transfer.get("verification_round") == null) { UUID round = UUID.randomUUID(); - sql().execute("UPDATE " + TRANSFER + " SET verification_round=?,verification_cursor=-1,verification_complete=false WHERE transfer_id=? AND verification_round IS NULL", round, transferId); + sql() + .execute( + "UPDATE " + + TRANSFER + + " SET verification_round=?,verification_cursor=-1,verification_complete=false WHERE transfer_id=? AND verification_round IS NULL", + round, + transferId); return -1; } return transfer.get("verification_cursor", Long.class); } - void retainVerification(Item item, CanonicalGameplayOriginalNewCapacityExecutionOwner.TransferFence actual, + void retainVerification( + Item item, + CanonicalGameplayOriginalNewCapacityExecutionOwner.TransferFence actual, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after) { requireObservation(readCurrent(item.transferId(), item.ordinal()), before); requireObservation(readCurrent(item.transferId(), item.ordinal()), after); if (!before.incarnationDigest().equals(after.incarnationDigest())) throw unavailable(); - sql().transaction(configuration -> { - var tx=DSL.using(configuration); - Record transfer=current(tx,item.transferId(),true); - if (!after.incarnationDigest().equals(transfer.get("incarnation_digest",String.class))) throw unavailable(); - Record row=tx.fetchSingle("SELECT fence_readback FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=?",item.transferId(),item.ordinal()); - if (!Arrays.equals(actual.canonicalReadback(),row.get("fence_readback",byte[].class))) throw unavailable(); - tx.execute("UPDATE " + ITEM + " SET verified_round=? WHERE transfer_id=? AND target_ordinal=?",transfer.get("verification_round",UUID.class),item.transferId(),item.ordinal()); - tx.execute("UPDATE " + TRANSFER + " SET verification_cursor=? WHERE transfer_id=? AND verification_cursor { + var tx = DSL.using(configuration); + Record transfer = current(tx, item.transferId(), true); + if (!after + .incarnationDigest() + .equals(transfer.get("incarnation_digest", String.class))) throw unavailable(); + Record row = + tx.fetchSingle( + "SELECT fence_readback FROM " + + ITEM + + " WHERE transfer_id=? AND target_ordinal=?", + item.transferId(), + item.ordinal()); + if (!Arrays.equals( + actual.canonicalReadback(), row.get("fence_readback", byte[].class))) + throw unavailable(); + tx.execute( + "UPDATE " + + ITEM + + " SET verified_round=? WHERE transfer_id=? AND target_ordinal=?", + transfer.get("verification_round", UUID.class), + item.transferId(), + item.ordinal()); + tx.execute( + "UPDATE " + + TRANSFER + + " SET verification_cursor=? WHERE transfer_id=? AND verification_cursor= proof.deadline || !sourceDigest(source, prior).equals(proof.sourceDigest)) throw unavailable(); + CanonicalGameplayRegionRuntimeStatus prior, + String newOwner, + long newFence, + String newLease, + Instant now) { + if (proof == null + || now.toEpochMilli() >= proof.deadline + || !sourceDigest(source, prior).equals(proof.sourceDigest)) throw unavailable(); Record transfer = current(tx, proof.transferId, true); if (!proof.incarnationDigest.equals(transfer.get("incarnation_digest", String.class)) - || !proof.round.equals(transfer.get("verification_round",UUID.class)) - || !Boolean.TRUE.equals(transfer.get("verification_complete",Boolean.class))) throw unavailable(); + || !proof.round.equals(transfer.get("verification_round", UUID.class)) + || !Boolean.TRUE.equals(transfer.get("verification_complete", Boolean.class))) + throw unavailable(); requireComplete(tx, proof.transferId); - if (tx.execute("UPDATE " + TRANSFER + " SET state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=? WHERE transfer_id=? AND state='FROZEN'", newOwner, newFence, newLease, proof.transferId) != 1) throw unavailable(); + if (tx.execute( + "UPDATE " + + TRANSFER + + " SET state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=? WHERE transfer_id=? AND state='FROZEN'", + newOwner, + newFence, + newLease, + proof.transferId) + != 1) throw unavailable(); } static boolean frozen(DSLContext tx, UUID tenant, UUID game, UUID region) { - return tx.fetchExists(DSL.selectOne().from(DSL.table(TRANSFER)).where(DSL.field("tenant_id").eq(tenant)) - .and(DSL.field("game_instance_id").eq(game)).and(DSL.field("region_id").eq(region)).and(DSL.field("state").eq("FROZEN"))); + return tx.fetchExists( + DSL.selectOne() + .from(DSL.table(TRANSFER)) + .where(DSL.field("tenant_id").eq(tenant)) + .and(DSL.field("game_instance_id").eq(game)) + .and(DSL.field("region_id").eq(region)) + .and(DSL.field("state").eq("FROZEN"))); } /** Terminal originals need no new denial; close only the now-empty control intent atomically. */ - static void completeTerminalOnly(DSLContext tx,CanonicalGameplayRegionRuntimeStatus prior, - String newOwner,long newFence,String newLease) { - if(exists(tx,"SELECT 1"+PENDING,prior.tenantId(),prior.gameInstanceId(),prior.regionId())) throw unavailable(); - tx.execute("UPDATE " + TRANSFER + " SET state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=? WHERE tenant_id=? AND game_instance_id=? AND region_id=? AND old_owner_fence=? AND state='FROZEN'", - newOwner,newFence,newLease,prior.tenantId(),prior.gameInstanceId(),prior.regionId(),prior.executorFence().longValueExact()); + static void completeTerminalOnly( + DSLContext tx, + CanonicalGameplayRegionRuntimeStatus prior, + String newOwner, + long newFence, + String newLease) { + if (exists( + tx, "SELECT 1" + PENDING, prior.tenantId(), prior.gameInstanceId(), prior.regionId())) + throw unavailable(); + tx.execute( + "UPDATE " + + TRANSFER + + " SET state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=? WHERE tenant_id=? AND game_instance_id=? AND region_id=? AND old_owner_fence=? AND state='FROZEN'", + newOwner, + newFence, + newLease, + prior.tenantId(), + prior.gameInstanceId(), + prior.regionId(), + prior.executorFence().longValueExact()); } - @Override public Context readCurrent(UUID transferId, long targetOrdinal) { - if (admitted.get() == null) return within(Long.MAX_VALUE, ignored -> readCurrent(transferId, targetOrdinal)); + @Override + public Context readCurrent(UUID transferId, long targetOrdinal) { + if (admitted.get() == null) + return within(Long.MAX_VALUE, ignored -> readCurrent(transferId, targetOrdinal)); Record transfer = observationCurrent(sql(), transferId); - Record row = sql().fetchOne("SELECT execution_digest FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=?", transferId, targetOrdinal); + Record row = + sql() + .fetchOne( + "SELECT execution_digest FROM " + + ITEM + + " WHERE transfer_id=? AND target_ordinal=?", + transferId, + targetOrdinal); if (row == null) throw unavailable(); - Item item = loadItem(sql(), transferId, targetOrdinal, row.get("execution_digest", String.class)); + Item item = + loadItem(sql(), transferId, targetOrdinal, row.get("execution_digest", String.class)); var binding = item.candidate().bindingIdentity(); - return new Context(transferId, targetOrdinal, transfer.get("intent_digest", String.class), transfer.get("source_digest", String.class), - transfer.get("old_owner_id", String.class), transfer.get("old_owner_fence", Long.class), binding.tenantId(), binding.gameInstanceId(), binding.regionId(), - transfer.get("region_epoch", Long.class), item.execution().transitionId(), item.execution().request().identity().requestId(), binding.accountId(), - binding.playableStateNamespaceId(), item.execution().digest(), item.execution().candidateDigest(), item.assignment().tenantGameplayTag(), item.assignment().workloadNamespace(), item.assignment().allocationVersion(), - transfer.get("state",String.class), completionDigest(transfer)); + return new Context( + transferId, + targetOrdinal, + transfer.get("intent_digest", String.class), + transfer.get("source_digest", String.class), + transfer.get("old_owner_id", String.class), + transfer.get("old_owner_fence", Long.class), + binding.tenantId(), + binding.gameInstanceId(), + binding.regionId(), + transfer.get("region_epoch", Long.class), + item.execution().transitionId(), + item.execution().request().identity().requestId(), + binding.accountId(), + binding.playableStateNamespaceId(), + item.execution().digest(), + item.execution().candidateDigest(), + item.assignment().tenantGameplayTag(), + item.assignment().workloadNamespace(), + item.assignment().allocationVersion(), + transfer.get("state", String.class), + completionDigest(transfer)); } - @Override public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( - UUID transitionId,CanonicalGameplayTenantGameplayTagRepository sourceTags) { - if(admitted.get()==null) return within(Long.MAX_VALUE,ignored -> readAssignment(transitionId,sourceTags)); + @Override + public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository sourceTags) { + if (admitted.get() == null) + return within(Long.MAX_VALUE, ignored -> readAssignment(transitionId, sourceTags)); return sourceTags.withCapacityExecutionDsl(sql()).assignmentForTransition(transitionId); } - private static Record observationCurrent(DSLContext tx,UUID id) { - Record row=tx.fetchOne("SELECT t.*,r.* FROM " + TRANSFER + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND r.region_epoch=t.region_epoch AND ((t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence) OR (t.state='COMPLETED' AND r.owner_instance_id=t.new_owner_id AND r.executor_fence=t.new_owner_fence AND r.lease_token_correlation=t.new_lease_correlation))",id); - if(row==null) throw unavailable(); - var actual=CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row); - if(!"game-session-service".equals(actual.ownerService())) throw unavailable(); - String observed=sourceDigest(actual,row.get("old_owner_id",String.class),row.get("old_owner_fence",Long.class),row.get("old_lease_correlation",String.class)); - if(!observed.equals(row.get("source_digest",String.class))) throw unavailable(); + private static Record observationCurrent(DSLContext tx, UUID id) { + Record row = + tx.fetchOne( + "SELECT t.*,r.* FROM " + + TRANSFER + + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND r.region_epoch=t.region_epoch AND ((t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence) OR (t.state='COMPLETED' AND r.owner_instance_id=t.new_owner_id AND r.executor_fence=t.new_owner_fence AND r.lease_token_correlation=t.new_lease_correlation))", + id); + if (row == null) throw unavailable(); + var actual = CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row); + if (!"game-session-service".equals(actual.ownerService())) throw unavailable(); + String observed = + sourceDigest( + actual, + row.get("old_owner_id", String.class), + row.get("old_owner_fence", Long.class), + row.get("old_lease_correlation", String.class)); + if (!observed.equals(row.get("source_digest", String.class))) throw unavailable(); return row; } private static String completionDigest(Record transfer) { - if(!"COMPLETED".equals(transfer.get("state",String.class))) return null; - return digest(bytes(transfer.get("transfer_id",UUID.class) + "/" + transfer.get("new_owner_id",String.class) - + "/" + transfer.get("new_owner_fence",Long.class) + "/" + transfer.get("new_lease_correlation",String.class))); + if (!"COMPLETED".equals(transfer.get("state", String.class))) return null; + return digest( + bytes( + transfer.get("transfer_id", UUID.class) + + "/" + + transfer.get("new_owner_id", String.class) + + "/" + + transfer.get("new_owner_fence", Long.class) + + "/" + + transfer.get("new_lease_correlation", String.class))); } private Item loadItem(DSLContext tx, UUID transferId, long ordinal, String executionDigest) { - Record row = tx.fetchOne("SELECT e.*,t.original_new_candidate_bytes FROM game_session_original_new_capacity_execution e JOIN game_session_canonical_binding_transition t ON t.transition_id=e.transition_id WHERE e.execution_digest=?", executionDigest); + Record row = + tx.fetchOne( + "SELECT e.*,t.original_new_candidate_bytes FROM game_session_original_new_capacity_execution e JOIN game_session_canonical_binding_transition t ON t.transition_id=e.transition_id WHERE e.execution_digest=?", + executionDigest); if (row == null) throw unavailable(); - var candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical(row.get("original_new_candidate_bytes", byte[].class)); + var candidate = + CanonicalGameplayOriginalNewCandidate.parseCanonical( + row.get("original_new_candidate_bytes", byte[].class)); var execution = decode(row.get("canonical_execution", byte[].class)); - if (!execution.digest().equals(executionDigest) || !execution.transitionId().equals(candidate.bindingDecisionId()) + if (!execution.digest().equals(executionDigest) + || !execution.transitionId().equals(candidate.bindingDecisionId()) || !execution.candidateDigest().equals(digest(candidate.canonicalBytes())) - || !execution.selectedOwnerId().equals(row.get("selected_owner_id",String.class)) - || execution.selectedOwnerFence()!=row.get("selected_owner_fence",Long.class) - || !execution.request().identity().requestId().equals(row.get("request_id",UUID.class)) - || !execution.request().admissionAttemptId().equals(row.get("admission_attempt_id",UUID.class))) throw unavailable(); - var assignment = tags.withCapacityExecutionDsl(sql()).assignmentForTransition(execution.transitionId()); - if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class))) throw unavailable(); + || !execution.selectedOwnerId().equals(row.get("selected_owner_id", String.class)) + || execution.selectedOwnerFence() != row.get("selected_owner_fence", Long.class) + || !execution.request().identity().requestId().equals(row.get("request_id", UUID.class)) + || !execution + .request() + .admissionAttemptId() + .equals(row.get("admission_attempt_id", UUID.class))) throw unavailable(); + var assignment = + tags.withCapacityExecutionDsl(sql()).assignmentForTransition(execution.transitionId()); + if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class))) + throw unavailable(); var binding = candidate.bindingIdentity(); - Record transfer=observationCurrent(tx,transferId); - if(!binding.tenantId().equals(transfer.get("tenant_id",UUID.class)) - || !binding.gameInstanceId().equals(transfer.get("game_instance_id",UUID.class)) - || !binding.regionId().equals(transfer.get("region_id",UUID.class)) - || binding.regionEpoch().longValueExact()!=transfer.get("region_epoch",Long.class) - || execution.selectedOwnerFence()>transfer.get("old_owner_fence",Long.class)) throw unavailable(); - Record retained=tx.fetchOne("SELECT * FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=?",transferId,ordinal); - if(retained==null || !executionDigest.equals(retained.get("execution_digest",String.class)) - || !Arrays.equals(execution.canonicalBytes(),retained.get("canonical_execution",byte[].class)) - || !execution.candidateDigest().equals(retained.get("candidate_digest",String.class)) - || !assignment.tenantGameplayTag().equals(retained.get("tenant_gameplay_tag",String.class)) - || !assignment.workloadNamespace().equals(retained.get("workload_namespace",String.class)) - || assignment.allocationVersion()!=retained.get("allocation_version",Integer.class)) throw unavailable(); + Record transfer = observationCurrent(tx, transferId); + if (!binding.tenantId().equals(transfer.get("tenant_id", UUID.class)) + || !binding.gameInstanceId().equals(transfer.get("game_instance_id", UUID.class)) + || !binding.regionId().equals(transfer.get("region_id", UUID.class)) + || binding.regionEpoch().longValueExact() != transfer.get("region_epoch", Long.class) + || execution.selectedOwnerFence() > transfer.get("old_owner_fence", Long.class)) + throw unavailable(); + Record retained = + tx.fetchOne( + "SELECT * FROM " + ITEM + " WHERE transfer_id=? AND target_ordinal=?", + transferId, + ordinal); + if (retained == null + || !executionDigest.equals(retained.get("execution_digest", String.class)) + || !Arrays.equals( + execution.canonicalBytes(), retained.get("canonical_execution", byte[].class)) + || !execution.candidateDigest().equals(retained.get("candidate_digest", String.class)) + || !assignment.tenantGameplayTag().equals(retained.get("tenant_gameplay_tag", String.class)) + || !assignment.workloadNamespace().equals(retained.get("workload_namespace", String.class)) + || assignment.allocationVersion() != retained.get("allocation_version", Integer.class)) + throw unavailable(); var player = (TenantCapacityAdmission.PlayerContext) execution.request().context(); - if (!binding.accountId().equals(player.accountId()) || !binding.tenantId().equals(player.tenantId()) - || !binding.gameInstanceId().equals(player.gameInstanceId()) || !binding.playableStateNamespaceId().equals(player.playableStateNamespaceId()) - || !binding.characterId().equals(player.characterId()) || !binding.sessionId().equals(player.sessionId().toString())) throw unavailable(); + if (!binding.accountId().equals(player.accountId()) + || !binding.tenantId().equals(player.tenantId()) + || !binding.gameInstanceId().equals(player.gameInstanceId()) + || !binding.playableStateNamespaceId().equals(player.playableStateNamespaceId()) + || !binding.characterId().equals(player.characterId()) + || !binding.sessionId().equals(player.sessionId().toString())) throw unavailable(); return new Item(transferId, ordinal, execution, candidate, assignment); } private static Record current(DSLContext tx, UUID id, boolean lock) { - Record row = tx.fetchOne("SELECT t.*,r.* FROM " + TRANSFER + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence AND r.region_epoch=t.region_epoch" + (lock ? " FOR UPDATE OF r,t" : ""), id); + Record row = + tx.fetchOne( + "SELECT t.*,r.* FROM " + + TRANSFER + + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence AND r.region_epoch=t.region_epoch" + + (lock ? " FOR UPDATE OF r,t" : ""), + id); if (row == null) throw unavailable(); - if (!sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row)).equals(row.get("source_digest",String.class))) throw unavailable(); + if (!sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row)) + .equals(row.get("source_digest", String.class))) throw unavailable(); return row; } private static void requireComplete(DSLContext tx, UUID id) { Record transfer = current(tx, id, false); - boolean missing = exists(tx,"SELECT 1" + PENDING - + " AND NOT EXISTS (SELECT 1 FROM " + ITEM + " i WHERE i.transfer_id=? AND i.execution_digest=e.execution_digest AND i.canonical_execution=e.canonical_execution AND i.fence_readback IS NOT NULL AND i.incarnation_digest=?)", - transfer.get("tenant_id", UUID.class), transfer.get("game_instance_id", UUID.class), transfer.get("region_id", UUID.class), id, transfer.get("incarnation_digest", String.class)); + boolean missing = + exists( + tx, + "SELECT 1" + + PENDING + + " AND NOT EXISTS (SELECT 1 FROM " + + ITEM + + " i WHERE i.transfer_id=? AND i.execution_digest=e.execution_digest AND i.canonical_execution=e.canonical_execution AND i.fence_readback IS NOT NULL AND i.incarnation_digest=?)", + transfer.get("tenant_id", UUID.class), + transfer.get("game_instance_id", UUID.class), + transfer.get("region_id", UUID.class), + id, + transfer.get("incarnation_digest", String.class)); if (missing) throw unavailable(); } - private static void requireOldOwner(DSLContext tx, CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior) { - Record row = tx.fetchOne("SELECT * FROM game_session_region_runtime_status WHERE tenant_id=? AND game_instance_id=? AND region_id=? FOR UPDATE", source.tenantId(), source.gameInstanceId(), source.regionId()); - if (row == null || !prior.ownerInstanceId().equals(row.get("owner_instance_id", String.class)) + private static void requireOldOwner( + DSLContext tx, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior) { + Record row = + tx.fetchOne( + "SELECT * FROM game_session_region_runtime_status WHERE tenant_id=? AND game_instance_id=? AND region_id=? FOR UPDATE", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + if (row == null + || !prior.ownerInstanceId().equals(row.get("owner_instance_id", String.class)) || prior.executorFence().longValueExact() != row.get("executor_fence", Long.class) || prior.regionEpoch() != row.get("region_epoch", Long.class) - || !Arrays.equals(prior.lifecycleRequest().canonicalBytes(), row.get("lifecycle_request_bytes", byte[].class)) - || !sourceDigest(source,prior).equals(sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row)))) throw unavailable(); + || !Arrays.equals( + prior.lifecycleRequest().canonicalBytes(), + row.get("lifecycle_request_bytes", byte[].class)) + || !sourceDigest(source, prior) + .equals(sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(row)))) + throw unavailable(); } - static String sourceDigest(CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior) { - if (!source.tenantId().equals(prior.tenantId()) || !source.gameInstanceId().equals(prior.gameInstanceId()) - || !source.regionId().equals(prior.regionId()) || !source.canonicalRegionId().equals(prior.canonicalRegionId()) - || source.lifecycleEpoch() != prior.lifecycleEpoch() || source.lifecycleRowVersion() != prior.lifecycleRowVersion() - || !source.captureId().equals(prior.captureId()) || !source.graphSha256().equals(prior.graphSha256()) + static String sourceDigest( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior) { + if (!source.tenantId().equals(prior.tenantId()) + || !source.gameInstanceId().equals(prior.gameInstanceId()) + || !source.regionId().equals(prior.regionId()) + || !source.canonicalRegionId().equals(prior.canonicalRegionId()) + || source.lifecycleEpoch() != prior.lifecycleEpoch() + || source.lifecycleRowVersion() != prior.lifecycleRowVersion() + || !source.captureId().equals(prior.captureId()) + || !source.graphSha256().equals(prior.graphSha256()) || !source.preparationInputDigest().equals(prior.preparationInputDigest()) - || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId(source.lifecycleRequest(), prior.lifecycleRequest())) throw unavailable(); + || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( + source.lifecycleRequest(), prior.lifecycleRequest())) throw unavailable(); return sourceDigest(prior); } private static String sourceDigest(CanonicalGameplayRegionRuntimeStatus prior) { - return sourceDigest(prior,prior.ownerInstanceId(),prior.executorFence().longValueExact(),prior.leaseTokenCorrelation()); + return sourceDigest( + prior, + prior.ownerInstanceId(), + prior.executorFence().longValueExact(), + prior.leaseTokenCorrelation()); } - private static String sourceDigest(CanonicalGameplayRegionRuntimeStatus prior,String owner,long fence,String lease) { - return digest(bytes(prior.tenantId() + "/" + prior.gameInstanceId() + "/" + prior.regionId() + "/" + prior.canonicalRegionId() - + "/" + prior.lifecycleEpoch() + "/" + prior.lifecycleRowVersion() + "/" + Base64.getEncoder().encodeToString(prior.lifecycleRequest().canonicalBytes()) - + "/" + prior.captureId() + "/" + prior.graphSha256() + "/" + prior.preparationInputDigest() + "/" + prior.regionEpoch() - + "/" + prior.ownerService() + "/" + owner + "/" + fence + "/" + lease)); + private static String sourceDigest( + CanonicalGameplayRegionRuntimeStatus prior, String owner, long fence, String lease) { + return digest( + bytes( + prior.tenantId() + + "/" + + prior.gameInstanceId() + + "/" + + prior.regionId() + + "/" + + prior.canonicalRegionId() + + "/" + + prior.lifecycleEpoch() + + "/" + + prior.lifecycleRowVersion() + + "/" + + Base64.getEncoder().encodeToString(prior.lifecycleRequest().canonicalBytes()) + + "/" + + prior.captureId() + + "/" + + prior.graphSha256() + + "/" + + prior.preparationInputDigest() + + "/" + + prior.regionEpoch() + + "/" + + prior.ownerService() + + "/" + + owner + + "/" + + fence + + "/" + + lease)); } - private void requireObservation(Context context, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation value) { - if (value.ownerKind() != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER - || !context.equals(value.regionOwnerTransferContext()) || clock.millis() >= value.expiresAtEpochMillis()) throw unavailable(); + private void requireObservation( + Context context, CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation value) { + if (value.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER + || !context.equals(value.regionOwnerTransferContext()) + || clock.millis() >= value.expiresAtEpochMillis()) throw unavailable(); } - /** Strictly reconstruct the existing retained envelope; canonical re-encoding excludes alternate grammars. */ + /** + * Strictly reconstruct the existing retained envelope; canonical re-encoding excludes alternate + * grammars. + */ static OriginalNewCapacityExecution decode(byte[] canonical) { try { - if (canonical == null || canonical.length == 0 || canonical.length > 1048576) throw unavailable(); + if (canonical == null || canonical.length == 0 || canonical.length > 1048576) + throw unavailable(); JsonNode node = JSON.readTree(canonical); byte[] payload = Base64.getDecoder().decode(node.get("canonicalAttemptPayload").textValue()); var parser = new Frame(payload); if (!"mutationDigest/v1".equals(parser.segment())) throw unavailable(); - Map fields = parser.fields(7, 0); - var scope = object(fields, "scope"); var target = object(fields, "target"); - var player = object(target, "ownerContext"); var expected = object(fields, "expectedVersion"); + Map fields = parser.fields(7, 0); + var scope = object(fields, "scope"); + var target = object(fields, "target"); + var player = object(target, "ownerContext"); + var expected = object(fields, "expectedVersion"); var mutation = object(fields, "mutation"); - var identity = new TenantCapacityAdmission.Identity(uuid(scope,"tenantId"), uuid(scope,"requestId"), uuid(scope,"admissionId")); - var request = new TenantCapacityAdmission.Request(identity, uuid(expected,"admissionAttemptId"), number(expected,"capacityRearmFence"), text(target,"targetNamespace"), - new TenantCapacityAdmission.PlayerContext(uuid(player,"accountId"), uuid(player,"tenantId"), uuid(player,"playableStateNamespaceId"), uuid(player,"gameInstanceId"), uuid(player,"characterId"), uuid(player,"sessionId"), uuid(player,"realmId"), uuid(player,"requestId"), text(player,"playableStateScope")), - TenantCapacityAdmission.Operation.valueOf(text(mutation,"operation")), shape(object(mutation,"priorShape")), shape(object(mutation,"requestedShape")), - TenantCapacityAdmission.Evidence.parse(Base64.getDecoder().decode(text(mutation,"accountEvidence")), TenantCapacityAdmission.Owner.GAME_SESSION), number(mutation,"capacityDelta"), node.get("mutationDigest").textValue()); - if (!parser.done() || !Arrays.equals(payload, CapacityAdmissionDigest.preimage(request))) throw unavailable(); - var reservation = new TenantCapacityAdmission.Result(identity, request.admissionAttemptId(), request.capacityRearmFence(), request.mutationDigest(), UUID.fromString(node.get("reservationId").textValue()), Long.parseLong(node.get("reservationFence").textValue()), Instant.parse(node.get("expiresAt").textValue()), TenantCapacityAdmission.State.RESERVED, node.get("snapshotIdentity").textValue(), node.get("evaluationIdentity").textValue()); - var result = new OriginalNewCapacityExecution(request, reservation, UUID.fromString(node.get("transitionId").textValue()), node.get("candidateDigest").textValue(), node.get("selectedOwnerId").textValue(), Long.parseLong(node.get("selectedOwnerFence").textValue())); + var identity = + new TenantCapacityAdmission.Identity( + uuid(scope, "tenantId"), uuid(scope, "requestId"), uuid(scope, "admissionId")); + var request = + new TenantCapacityAdmission.Request( + identity, + uuid(expected, "admissionAttemptId"), + number(expected, "capacityRearmFence"), + text(target, "targetNamespace"), + new TenantCapacityAdmission.PlayerContext( + uuid(player, "accountId"), + uuid(player, "tenantId"), + uuid(player, "playableStateNamespaceId"), + uuid(player, "gameInstanceId"), + uuid(player, "characterId"), + uuid(player, "sessionId"), + uuid(player, "realmId"), + uuid(player, "requestId"), + text(player, "playableStateScope")), + TenantCapacityAdmission.Operation.valueOf(text(mutation, "operation")), + shape(object(mutation, "priorShape")), + shape(object(mutation, "requestedShape")), + TenantCapacityAdmission.Evidence.parse( + Base64.getDecoder().decode(text(mutation, "accountEvidence")), + TenantCapacityAdmission.Owner.GAME_SESSION), + number(mutation, "capacityDelta"), + node.get("mutationDigest").textValue()); + if (!parser.done() || !Arrays.equals(payload, CapacityAdmissionDigest.preimage(request))) + throw unavailable(); + var reservation = + new TenantCapacityAdmission.Result( + identity, + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.fromString(node.get("reservationId").textValue()), + Long.parseLong(node.get("reservationFence").textValue()), + Instant.parse(node.get("expiresAt").textValue()), + TenantCapacityAdmission.State.RESERVED, + node.get("snapshotIdentity").textValue(), + node.get("evaluationIdentity").textValue()); + var result = + new OriginalNewCapacityExecution( + request, + reservation, + UUID.fromString(node.get("transitionId").textValue()), + node.get("candidateDigest").textValue(), + node.get("selectedOwnerId").textValue(), + Long.parseLong(node.get("selectedOwnerFence").textValue())); if (!Arrays.equals(canonical, result.canonicalBytes())) throw unavailable(); return result; - } catch (java.io.IOException | RuntimeException invalid) { throw unavailable(); } + } catch (RuntimeException invalid) { + throw unavailable(); + } + } + + private static TenantCapacityAdmission.Shape shape(Map value) { + return new TenantCapacityAdmission.Shape( + number(value, "activeSessions"), + number(value, "concurrentGameInstances"), + number(value, "storageBytes")); + } + + @SuppressWarnings("unchecked") + private static Map object(Map value, String key) { + if (!(value.get(key) instanceof Map)) throw unavailable(); + return (Map) value.get(key); } - private static TenantCapacityAdmission.Shape shape(Map value) { return new TenantCapacityAdmission.Shape(number(value,"activeSessions"), number(value,"concurrentGameInstances"), number(value,"storageBytes")); } - @SuppressWarnings("unchecked") private static Map object(Map value,String key) { if (!(value.get(key) instanceof Map)) throw unavailable(); return (Map)value.get(key); } - private static String text(Map value,String key) { if (!(value.get(key) instanceof String text)) throw unavailable(); return text; } - private static long number(Map value,String key) { if (!(value.get(key) instanceof Long number)) throw unavailable(); return number; } - private static UUID uuid(Map value,String key) { return UUID.fromString(text(value,key)); } - private static byte[] bytes(String text) { return text.getBytes(StandardCharsets.UTF_8); } - private static String digest(byte[] value) { return "sha256:" + OriginalNewCapacityExecution.sha256(value); } - private static boolean exists(DSLContext tx,String query,Object... bindings) { return Boolean.TRUE.equals(tx.fetchSingle("SELECT EXISTS (" + query + ")",bindings).get(0,Boolean.class)); } - private static void noSql() { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); } - private static IllegalStateException unavailable() { return new IllegalStateException("Normal region owner transfer is held"); } + private static String text(Map value, String key) { + if (!(value.get(key) instanceof String text)) throw unavailable(); + return text; + } + + private static long number(Map value, String key) { + if (!(value.get(key) instanceof Long number)) throw unavailable(); + return number; + } + + private static UUID uuid(Map value, String key) { + return UUID.fromString(text(value, key)); + } + + private static byte[] bytes(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + private static String digest(byte[] value) { + return "sha256:" + OriginalNewCapacityExecution.sha256(value); + } + + private static boolean exists(DSLContext tx, String query, Object... bindings) { + return Boolean.TRUE.equals( + tx.fetchSingle("SELECT EXISTS (" + query + ")", bindings).get(0, Boolean.class)); + } + + private static void noSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Normal region owner transfer is held"); + } private static final class Frame { - private final byte[] data; private int offset; - private Frame(byte[] data) { if (data.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES) throw unavailable(); this.data=data; } + private final byte[] data; + private int offset; + + private Frame(byte[] data) { + if (data.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES) throw unavailable(); + this.data = data; + } + private String segment() { - int start=offset; while (offset='0' && data[offset]<='9') offset++; - if (offset==start || offset>=data.length || data[offset++]!=':' || offset-start>8) throw unavailable(); - int size=Integer.parseInt(new String(data,start,offset-start-1,StandardCharsets.US_ASCII)); - if (size<0 || size>CapacityAdmissionDigest.MAX_SEGMENT_BYTES || size>data.length-offset) throw unavailable(); - String result=new String(data,offset,size,StandardCharsets.UTF_8); offset+=size; return result; + int start = offset; + while (offset < data.length && data[offset] >= '0' && data[offset] <= '9') offset++; + if (offset == start || offset >= data.length || data[offset++] != ':' || offset - start > 8) + throw unavailable(); + int size = + Integer.parseInt(new String(data, start, offset - start - 1, StandardCharsets.US_ASCII)); + if (size < 0 + || size > CapacityAdmissionDigest.MAX_SEGMENT_BYTES + || size > data.length - offset) throw unavailable(); + String result = new String(data, offset, size, StandardCharsets.UTF_8); + offset += size; + return result; } - private Map fields(int count,int depth) { - if (count<0 || count>16 || depth>8) throw unavailable(); - Map result=new LinkedHashMap<>(); - for(int index=0;index=data.length || data[offset++]!='1') throw unavailable(); - String payload=segment(); Object value; - if (type.equals("object")) { Frame nested=new Frame(bytes(payload)); value=nested.fields(Integer.parseInt(nested.segment()),depth+1); if(!nested.done()) throw unavailable(); } - else if(type.equals("string")) value=payload; - else if(type.equals("number") && payload.matches("0|[1-9][0-9]{0,18}")) value=Long.parseLong(payload); + + private Map fields(int count, int depth) { + if (count < 0 || count > 16 || depth > 8) throw unavailable(); + Map result = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String name = segment(), type = segment(); + if (offset >= data.length || data[offset++] != '1') throw unavailable(); + String payload = segment(); + Object value; + if (type.equals("object")) { + Frame nested = new Frame(bytes(payload)); + value = nested.fields(Integer.parseInt(nested.segment()), depth + 1); + if (!nested.done()) throw unavailable(); + } else if (type.equals("string")) value = payload; + else if (type.equals("number") && payload.matches("0|[1-9][0-9]{0,18}")) + value = Long.parseLong(payload); else throw unavailable(); - if(result.put(name,value)!=null) throw unavailable(); + if (result.put(name, value) != null) throw unavailable(); } return result; } - private boolean done() { return offset==data.length; } + + private boolean done() { + return offset == data.length; + } } - record Item(UUID transferId,long ordinal,OriginalNewCapacityExecution execution,CanonicalGameplayOriginalNewCandidate candidate,CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) {} + record Item( + UUID transferId, + long ordinal, + OriginalNewCapacityExecution execution, + CanonicalGameplayOriginalNewCandidate candidate, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) {} + static final class Completion { - private final UUID transferId; private final String sourceDigest; private final String incarnationDigest; private final UUID round; private final long deadline; - private Completion(UUID transferId,String sourceDigest,String incarnationDigest,UUID round,long deadline) { this.transferId=transferId;this.sourceDigest=sourceDigest;this.incarnationDigest=incarnationDigest;this.round=round;this.deadline=deadline; } + private final UUID transferId; + private final String sourceDigest; + private final String incarnationDigest; + private final UUID round; + private final long deadline; + + private Completion( + UUID transferId, String sourceDigest, String incarnationDigest, UUID round, long deadline) { + this.transferId = transferId; + this.sourceDigest = sourceDigest; + this.incarnationDigest = incarnationDigest; + this.round = round; + this.deadline = deadline; + } } } 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 d423fbfd21..decf04fdc3 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 @@ -678,13 +678,25 @@ CanonicalGameplayRegionRuntimeStatus installOwner( String ownerService, String ownerInstanceId, Instant now) { - return installOwner(source, expectedRegionEpoch, prior, leaseTokenCorrelation, - ownerService, ownerInstanceId, now, null); + return installOwner( + source, + expectedRegionEpoch, + prior, + leaseTokenCorrelation, + ownerService, + ownerInstanceId, + now, + null); } CanonicalGameplayRegionRuntimeStatus installOwner( - Source source, long expectedRegionEpoch, CanonicalGameplayRegionRuntimeStatus prior, - String leaseTokenCorrelation, String ownerService, String ownerInstanceId, Instant now, + Source source, + long expectedRegionEpoch, + CanonicalGameplayRegionRuntimeStatus prior, + String leaseTokenCorrelation, + String ownerService, + String ownerInstanceId, + Instant now, CanonicalGameplayRegionOwnerTransferRepository.Completion transferProof) { requireNoAmbientTransaction(); Objects.requireNonNull(source, "source"); @@ -740,19 +752,21 @@ CanonicalGameplayRegionRuntimeStatus installOwner( // Lease expiry alone cannot satisfy either condition. // Capacity authorization takes this same row lock before creating that custody. if (transaction.fetchExists( - DSL.selectOne() - .from( - DSL.table("game_session_original_new_capacity_execution").as("execution")) - .join( - DSL.table("game_session_canonical_binding_region_bridge_obligation") - .as("binding")) - .on( - DSL.field("binding.transition_id") - .eq(DSL.field("execution.transition_id"))) - .where(DSL.field("binding.tenant_id").eq(source.tenantId())) - .and(DSL.field("binding.game_instance_id").eq(source.gameInstanceId())) - .and(DSL.field("binding.region_id").eq(source.regionId())) - .and(DSL.field("execution.status").in("INSTALL_DISPATCHED", "AUTHORIZED"))) + DSL.selectOne() + .from( + DSL.table("game_session_original_new_capacity_execution") + .as("execution")) + .join( + DSL.table("game_session_canonical_binding_region_bridge_obligation") + .as("binding")) + .on( + DSL.field("binding.transition_id") + .eq(DSL.field("execution.transition_id"))) + .where(DSL.field("binding.tenant_id").eq(source.tenantId())) + .and(DSL.field("binding.game_instance_id").eq(source.gameInstanceId())) + .and(DSL.field("binding.region_id").eq(source.regionId())) + .and( + DSL.field("execution.status").in("INSTALL_DISPATCHED", "AUTHORIZED"))) && transferProof == null) { throw unavailable(); } @@ -767,12 +781,22 @@ CanonicalGameplayRegionRuntimeStatus installOwner( if (transferProof != null) { if (current == null) throw unavailable(); CanonicalGameplayRegionOwnerTransferRepository.requireAndComplete( - transaction, transferProof, source, current, ownerInstanceId, fence, - leaseTokenCorrelation, now); - } else if(current!=null && CanonicalGameplayRegionOwnerTransferRepository.frozen( - transaction,current.tenantId(),current.gameInstanceId(),current.regionId())) { + transaction, + transferProof, + source, + current, + ownerInstanceId, + fence, + leaseTokenCorrelation, + now); + } else if (current != null + && CanonicalGameplayRegionOwnerTransferRepository.frozen( + transaction, + current.tenantId(), + current.gameInstanceId(), + current.regionId())) { CanonicalGameplayRegionOwnerTransferRepository.completeTerminalOnly( - transaction,current,ownerInstanceId,fence,leaseTokenCorrelation); + transaction, current, ownerInstanceId, fence, leaseTokenCorrelation); } Record installed; if (current == 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 79a1bd1f52..c78787d4a7 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 @@ -670,37 +670,78 @@ public Candidate candidate() { /** Real Account hold/credential and GS authorization, intentionally stopped before FINAL. */ public net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result authorizeThenFenceAndHandoffWithoutFinal( - AccountGameplayAdmissionLeaseClient account,AccountPublicJwksCache jwks, + AccountGameplayAdmissionLeaseClient account, + AccountPublicJwksCache jwks, String originalLoginJwt, net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient capacityClient, net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, - long deadline) throws Exception { - var inventory=new CanonicalGameplayBindingInventoryRepository(binding.dsl()); - var source=inventory.readOriginalNewFinalAdmissionSource(decision); - var executionOwner=new CanonicalGameplayOriginalNewCapacityExecutionOwner( - binding.dsl(),coordination,scripts,CLOCK,tags); - var reservation=capacityClient.commit(request,deadline); - var execution=executionOwner.bind(source,request,reservation,deadline); - var issuerSource=binding.currentIssuerSource(); - var issuer=new CanonicalGameplayIssuerAdmissionBarrierRedisOwner(coordination,scripts, - new CanonicalGameplayIssuerAdmissionBarrierRepository(binding.dsl(),tags,issuerSource),issuerSource); - try(var credential=account.issueOriginalNewBoundGameplayCredential(originalLoginJwt, - decision.leaseEvidence().canonicalJson().getBytes(StandardCharsets.UTF_8)); - var raw=CanonicalGameplayOriginalNewAuthenticatedSession.template(source.candidate(),credential, - new CanonicalGameplayOriginalNewBoundCredentialVerifier(jwks,CLOCK),120_000L); - var template=raw.bindCapacityExecution(execution)) { - var current=initialOwner().verifyCurrentOpenForTarget(request.context() instanceof net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext player ? player.accountId() : null, - request.identity().tenantId(),source.candidate().bindingIdentity().playableStateNamespaceId()); - if(!(current instanceof CanonicalGameplayAccountInitialOpenProof.CurrentOpen open)) + long deadline) + throws Exception { + var inventory = new CanonicalGameplayBindingInventoryRepository(binding.dsl()); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var executionOwner = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + binding.dsl(), coordination, scripts, CLOCK, tags); + var reservation = capacityClient.commit(request, deadline); + var execution = executionOwner.bind(source, request, reservation, deadline); + var issuerSource = binding.currentIssuerSource(); + var issuer = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + coordination, + scripts, + new CanonicalGameplayIssuerAdmissionBarrierRepository( + binding.dsl(), tags, issuerSource), + issuerSource); + try (var credential = + account.issueOriginalNewBoundGameplayCredential( + originalLoginJwt, + decision.leaseEvidence().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var raw = + CanonicalGameplayOriginalNewAuthenticatedSession.template( + source.candidate(), + credential, + new CanonicalGameplayOriginalNewBoundCredentialVerifier(jwks, CLOCK), + 120_000L); + var template = raw.bindCapacityExecution(execution)) { + var current = + initialOwner() + .verifyCurrentOpenForTarget( + request.context() + instanceof + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .PlayerContext + player + ? player.accountId() + : null, + request.identity().tenantId(), + source.candidate().bindingIdentity().playableStateNamespaceId()); + if (!(current instanceof CanonicalGameplayAccountInitialOpenProof.CurrentOpen open)) throw new IllegalStateException("Actual INITIAL source is not OPEN"); - executionOwner.authorize(source,template,open,issuer.initializeAndRead(source.issuerAcknowledgement().operationId()),execution,deadline); + executionOwner.authorize( + source, + template, + open, + issuer.initializeAndRead(source.issuerAcknowledgement().operationId()), + execution, + deadline); } - var repository=new CanonicalGameplayRegionOwnerTransferRepository(binding.dsl(),CLOCK,tags); - var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); - var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(binding.dsl(),CLOCK,repository,executionOwner,receiver); - administration.sync().pexpire(ascii(regionInstallation.grant.key()),0); - regionInstallation=CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( - binding.dsl(),coordination,scripts,regionInstallation,sources.resolver,transfer,deadline); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(binding.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + binding.dsl(), CLOCK, repository, executionOwner, receiver); + administration.sync().pexpire(ascii(regionInstallation.grant.key()), 0); + regionInstallation = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + binding.dsl(), + coordination, + scripts, + regionInstallation, + sources.resolver, + transfer, + deadline); return reservation; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java index d98d8bf773..bc9356981a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java @@ -122,7 +122,6 @@ class CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest { Wxs2cbVLKG33dmmvG6TFL/+s3wbWL2LN5mxvpjYUg8ve3/ofBzgikHM9AAA= """; - @Container private static final GenericContainer REDIS = new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(PORT); @@ -198,8 +197,7 @@ static byte[] predecessorLuaForOwnerProof() throws Exception { byte[] preFenceScript; try (var input = new GZIPInputStream( - new ByteArrayInputStream( - Base64.getMimeDecoder().decode(PRE_FENCE_LUA_GZIP_BASE64)))) { + new ByteArrayInputStream(Base64.getMimeDecoder().decode(PRE_FENCE_LUA_GZIP_BASE64)))) { preFenceScript = input.readAllBytes(); } assertThat(HexFormatHolder.sha256(preFenceScript)).isEqualTo(PRE_FENCE_LUA_SHA256); @@ -344,8 +342,7 @@ void resetLossRefusesWithoutRecreatingCandidateIndexesOrBarriers() throws Except void absentExecutionFenceInstallsOnlyTheExactPersistentDenyWithoutRecreatingRuntimeState() throws Exception { ScriptCase original = seed(false); - for (int index = 0; index < 6; index++) - admin.del(new byte[][] {ascii(original.keys()[index])}); + for (int index = 0; index < 6; index++) admin.del(new byte[][] {ascii(original.keys()[index])}); Map before = physicalImage(original); // No credential, template, OPEN barrier, candidate or index is needed to deny future execution. @@ -507,7 +504,8 @@ void fenceRefusesWrongTypeTtlIdentityAndEveryUnexpectedPhysicalShapeWithoutMutat } @Test - void fenceRequiresTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() throws Exception { + void fenceRequiresTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() + throws Exception { for (String fault : List.of("missing-field", "extra-field", "wrong-tenant", "invalid-fence", "wrong-key")) { admin.flushdb(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index d0a06d7727..12f0b0a2b3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -335,88 +335,147 @@ void processStopAfterActualSqlAuthorizationBeforeRedisSendFencesUnknownAndActual throws Exception { repairAccountMember(); bridge(false); - var executionFile=directory.resolve("original-execution.json"); - java.nio.file.Files.write(executionFile,controlledCapacity.canonicalBytes()); - var process=new ProcessBuilder( - Path.of(System.getProperty("java.home"),"bin","java").toString(),"-cp",childClasspath(), - StopAfterAuthorizationCommit.class.getName(),POSTGRES.getJdbcUrl(),POSTGRES.getUsername(), - POSTGRES.getPassword(),executionFile.toString()).redirectErrorStream(true).start(); + var executionFile = directory.resolve("original-execution.json"); + java.nio.file.Files.write(executionFile, controlledCapacity.canonicalBytes()); + var process = + new ProcessBuilder( + Path.of(System.getProperty("java.home"), "bin", "java").toString(), + "-cp", + childClasspath(), + StopAfterAuthorizationCommit.class.getName(), + POSTGRES.getJdbcUrl(), + POSTGRES.getUsername(), + POSTGRES.getPassword(), + executionFile.toString()) + .redirectErrorStream(true) + .start(); try { - assertThat(process.waitFor(20,java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + assertThat(process.waitFor(20, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); assertThat(process.exitValue()).isEqualTo(72); - assertThat(new String(process.getInputStream().readAllBytes(),StandardCharsets.UTF_8)) + assertThat(new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8)) .contains("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); } finally { - if(process.isAlive()) { + if (process.isAlive()) { process.destroyForcibly(); - assertThat(process.waitFor(5,java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + assertThat(process.waitFor(5, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); } } - String originalKey=capacityKey(tags.assignmentForTransition(fixture.transitionId())); + String originalKey = capacityKey(tags.assignmentForTransition(fixture.transitionId())); assertThat(admin.type(ascii(originalKey))).isEqualTo("none"); - var original=regionBinding.installation(); - admin.pexpire(ascii(original.grant.key()),0); - var successor=actualTransferHandoff(); + var original = regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); - assertThat(admin.hget(ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))),ascii("state"))) + assertThat( + admin.hget( + ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))), + ascii("state"))) .containsExactly(ascii("FENCED_INDETERMINATE")); - assertThat(fixture.dsl().fetchSingle("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?",controlledCapacity.digest()).get(0,String.class)) + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) .isEqualTo("INSTALL_DISPATCHED"); - assertThatThrownBy(() -> capacityOwner().readExact(controlledCapacity.request(),controlledCapacity.reservation())) + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(() -> capacityOwner().closeOriginalAttempt(controlledCapacity.request(),controlledCapacity.reservation())) + assertThatThrownBy( + () -> + capacityOwner() + .closeOriginalAttempt( + controlledCapacity.request(), controlledCapacity.reservation())) .isInstanceOf(IllegalStateException.class); } @Test - void authorizedUnknownHandoffKeepsOriginalCandidateAndRefusesCompletedMutation() throws Exception { - repairAccountMember(); bridge(); - var original=regionBinding.installation(); - byte[] candidate=admin.get(ascii(installation.sessionKey())); - var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); - var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); - var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); - UUID transferId=transfer.advance(original.source,original.status,deadline()); + void authorizedUnknownHandoffKeepsOriginalCandidateAndRefusesCompletedMutation() + throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + byte[] candidate = admin.get(ascii(installation.sessionKey())); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + UUID transferId = transfer.advance(original.source, original.status, deadline()); assertThatThrownBy(() -> replaceRegionOwner("unproved-successor")) .isInstanceOf(IllegalStateException.class); - admin.pexpire(ascii(original.grant.key()),0); - var successor=CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( - fixture.dsl(),ownerClient,catalog,original,sources.resolver,transfer,deadline()); - var completed=receiver.observeForRegionOwnerTransfer(transferId,0,deadline()); + admin.pexpire(ascii(original.grant.key()), 0); + var successor = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), ownerClient, catalog, original, sources.resolver, transfer, deadline()); + var completed = receiver.observeForRegionOwnerTransfer(transferId, 0, deadline()); assertThat(completed.regionOwnerTransferContext().controlState()).isEqualTo("COMPLETED"); assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(candidate); - assertThatThrownBy(() -> repository.within(deadline(),ignored -> repository.capture(transferId))) + assertThatThrownBy( + () -> repository.within(deadline(), ignored -> repository.capture(transferId))) .isInstanceOf(IllegalStateException.class); assertThat(successor.status.ownerInstanceId()).isEqualTo("final-owner-handoff"); } @Test void retainedTransferFenceLossCannotBeReinstalledOrQualifyHandoff() throws Exception { - repairAccountMember(); bridge(); - var original=regionBinding.installation(); - var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); - var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); - var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); - transfer.advance(original.source,original.status,deadline()); - String key=capacityKey(tags.assignmentForTransition(fixture.transitionId())); + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + transfer.advance(original.source, original.status, deadline()); + String key = capacityKey(tags.assignmentForTransition(fixture.transitionId())); admin.del(ascii(key)); - String retained=sqlImage(); - admin.pexpire(ascii(original.grant.key()),0); - assertThatThrownBy(() -> CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( - fixture.dsl(),ownerClient,catalog,original,sources.resolver,transfer,deadline())) + String retained = sqlImage(); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + catalog, + original, + sources.resolver, + transfer, + deadline())) .isInstanceOf(IllegalStateException.class); assertThat(admin.type(ascii(key))).isEqualTo("none"); assertThat(sqlImage()).isEqualTo(retained); - assertThat(new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source).orElseThrow().executorFence()) + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow() + .executorFence()) .isEqualTo(original.status.executorFence()); } private CanonicalGameplayRegionLeaseOwner.Installation actualTransferHandoff() throws Exception { - var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); - var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); - var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); return CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( - fixture.dsl(),ownerClient,catalog,regionBinding.installation(),sources.resolver,transfer,deadline()); + fixture.dsl(), + ownerClient, + catalog, + regionBinding.installation(), + sources.resolver, + transfer, + deadline()); } @Test @@ -435,233 +494,443 @@ void retainedTransferFenceChangedEnvelopeCannotQualifyNativeHandoff() throws Exc } private void retainedTransferTamperBlocks(String fault) throws Exception { - repairAccountMember();bridge(); - var original=regionBinding.installation(); - var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); - var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); - var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); - transfer.advance(original.source,original.status,deadline()); - byte[] key=ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))); - if(fault.equals("ttl")) admin.pexpire(key,10000); - else if(fault.equals("type")) { admin.del(key);admin.set(key,ascii("wrong-type")); } - else admin.hset(key,ascii("binding"),ascii("{}")); - byte[] physical=admin.dump(key); - admin.pexpire(ascii(original.grant.key()),0); - assertThatThrownBy(() -> CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( - fixture.dsl(),ownerClient,catalog,original,sources.resolver,transfer,deadline())) + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + transfer.advance(original.source, original.status, deadline()); + byte[] key = ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))); + if (fault.equals("ttl")) admin.pexpire(key, 10000); + else if (fault.equals("type")) { + admin.del(key); + admin.set(key, ascii("wrong-type")); + } else admin.hset(key, ascii("binding"), ascii("{}")); + byte[] physical = admin.dump(key); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + catalog, + original, + sources.resolver, + transfer, + deadline())) .isInstanceOf(IllegalStateException.class); assertThat(admin.dump(key)).containsExactly(physical); - assertThat(new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source).orElseThrow().executorFence()) + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow() + .executorFence()) .isEqualTo(original.status.executorFence()); } @Test - void correctlySignedDifferentStorageGenerationCannotAdoptRetainedTransferReceipts() throws Exception { - repairAccountMember();bridge(); - var original=regionBinding.installation(); - var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); - var attestor=new CanonicalGameplayControlledRegionTransferObservationFixture(); - var originalTransfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),attestor.receiver(repository,tags)); - originalTransfer.advance(original.source,original.status,deadline()); - String retained=sqlImage(); - var changed=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),attestor.receiver(repository,tags,"storage-2")); - admin.pexpire(ascii(original.grant.key()),0); - assertThatThrownBy(() -> CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( - fixture.dsl(),ownerClient,catalog,original,sources.resolver,changed,deadline())) + void correctlySignedDifferentStorageGenerationCannotAdoptRetainedTransferReceipts() + throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var attestor = new CanonicalGameplayControlledRegionTransferObservationFixture(); + var originalTransfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), attestor.receiver(repository, tags)); + originalTransfer.advance(original.source, original.status, deadline()); + String retained = sqlImage(); + var changed = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), + CLOCK, + repository, + capacityOwner(), + attestor.receiver(repository, tags, "storage-2")); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + catalog, + original, + sources.resolver, + changed, + deadline())) .isInstanceOf(IllegalStateException.class); assertThat(sqlImage()).isEqualTo(retained); - assertThat(new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source).orElseThrow().executorFence()) + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow() + .executorFence()) .isEqualTo(original.status.executorFence()); } @Test - void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff() throws Exception { - repairAccountMember();bridge(); - var source=inventory.readOriginalNewFinalAdmissionSource(decision); + void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff() + throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); byte[] committed; - try(var credential=new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(),CLOCK); - var template=credential.template(); - var ignored=finalOwner().finalizeOriginalNewOnce(source,template,controlledAccountOpen(),issuerOpen(),controlledCapacity,deadline())) { - committed=admin.get(ascii(installation.sessionKey())); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var ignored = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + committed = admin.get(ascii(installation.sessionKey())); } // No SQL final receipt was retained by the interrupted final caller. - assertThat(fixture.dsl().fetchSingle("SELECT original_new_final_session_sha256 FROM game_session_canonical_binding_transition WHERE transition_id=?",fixture.transitionId()).get(0,String.class)).isNull(); - var original=regionBinding.installation(); - admin.pexpire(ascii(original.grant.key()),0); - var successor=actualTransferHandoff(); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT original_new_final_session_sha256 FROM game_session_canonical_binding_transition WHERE transition_id=?", + fixture.transitionId()) + .get(0, String.class)) + .isNull(); + var original = regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); - assertThat(fixture.dsl().fetchSingle("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?",controlledCapacity.digest()).get(0,String.class)).isEqualTo("COMMITTED"); - assertThat(capacityOwner().readExact(controlledCapacity.request(),controlledCapacity.reservation()).disposition()).isEqualTo("COMMITTED"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("COMMITTED"); + assertThat( + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation()) + .disposition()) + .isEqualTo("COMMITTED"); assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); } @Test - void committedHashWithoutCompletePositiveServingProofStillBlocksActualTransfer() throws Exception { - repairAccountMember();bridge(); - var source=inventory.readOriginalNewFinalAdmissionSource(decision); - try(var credential=new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(),CLOCK); - var template=credential.template(); - var ignored=finalOwner().finalizeOriginalNewOnce(source,template,controlledAccountOpen(),issuerOpen(),controlledCapacity,deadline())) { + void committedHashWithoutCompletePositiveServingProofStillBlocksActualTransfer() + throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var ignored = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { admin.del(ascii(installation.sessionKey())); } - var original=regionBinding.installation(); - admin.pexpire(ascii(original.grant.key()),0); + var original = regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()), 0); assertThatThrownBy(this::actualTransferHandoff).isInstanceOf(IllegalStateException.class); - assertThat(new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source).orElseThrow().executorFence()) + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow() + .executorFence()) .isEqualTo(original.status.executorFence()); - assertThat(fixture.dsl().fetchSingle("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?",controlledCapacity.digest()).get(0,String.class)).isEqualTo("AUTHORIZED"); - assertThat(admin.hget(ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))),ascii("state"))) + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("AUTHORIZED"); + assertThat( + admin.hget( + ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))), + ascii("state"))) .containsExactly(ascii("COMMITTED")); - assertThatThrownBy(() -> capacityOwner().readExact(controlledCapacity.request(),controlledCapacity.reservation())).isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); } private static String childClasspath() throws Exception { - var paths=new java.util.LinkedHashSet(); + var paths = new java.util.LinkedHashSet(); paths.addAll(List.of(System.getProperty("java.class.path").split(java.io.File.pathSeparator))); - for(ClassLoader loader=CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.class.getClassLoader();loader!=null;loader=loader.getParent()) { - if(loader instanceof java.net.URLClassLoader urls) for(var url:urls.getURLs()) { - if("file".equals(url.getProtocol())) paths.add(Path.of(url.toURI()).toString()); - } + for (ClassLoader loader = + CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.class.getClassLoader(); + loader != null; + loader = loader.getParent()) { + if (loader instanceof java.net.URLClassLoader urls) + for (var url : urls.getURLs()) { + if ("file".equals(url.getProtocol())) paths.add(Path.of(url.toURI()).toString()); + } } - paths.add(Path.of(CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString()); - return String.join(java.io.File.pathSeparator,paths); + paths.add( + Path.of( + CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .toURI()) + .toString()); + return String.join(java.io.File.pathSeparator, paths); } @Test - void delayedActualPredecessorInstallRefusesAfterNativeHandoffWithinOriginalDeadline() throws Exception { + void delayedActualPredecessorInstallRefusesAfterNativeHandoffWithinOriginalDeadline() + throws Exception { delayedPredecessorAfterHandoff(true); } @Test - void delayedActualPredecessorFinalRefusesAfterNativeHandoffWithinOriginalDeadline() throws Exception { + void delayedActualPredecessorFinalRefusesAfterNativeHandoffWithinOriginalDeadline() + throws Exception { delayedPredecessorAfterHandoff(false); } private void delayedPredecessorAfterHandoff(boolean installAction) throws Exception { - repairAccountMember();bridge(!installAction); - var source=inventory.readOriginalNewFinalAdmissionSource(decision); - var repository=new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(),CLOCK,tags); - var receiver=new CanonicalGameplayControlledRegionTransferObservationFixture().receiver(repository,tags); - var transfer=new CanonicalGameplayRegionOwnerTransferCoordinator(fixture.dsl(),CLOCK,repository,capacityOwner(),receiver); - String oldSha=admin.scriptLoad(CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.predecessorLuaForOwnerProof()); - var entered=new java.util.concurrent.CountDownLatch(1); - var release=new java.util.concurrent.CountDownLatch(1); - var calls=new java.util.concurrent.atomic.AtomicInteger(); - String action=installAction ? "INSTALL" : "FINAL"; - RedisClient delayed=mock(RedisClient.class); - when(delayed.connect(ByteArrayCodec.INSTANCE)).thenAnswer(ignored -> - delayedConnection(ownerClient.connect(ByteArrayCodec.INSTANCE),oldSha,action,entered,release,calls)); - try(var credential=new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(),CLOCK); - var raw=credential.template();var template=raw.bindCapacityExecution(controlledCapacity)) { - var account=controlledAccountOpen();var issuer=issuerOpen(); - long frozenDeadline=CLOCK.millis()+5000L; - var old=java.util.concurrent.CompletableFuture.runAsync(() -> { - if(installAction) { - new CanonicalGameplayOriginalNewCapacityExecutionOwner(fixture.dsl(),delayed,catalog,CLOCK,tags) - .authorize(source,template,account,issuer,controlledCapacity,frozenDeadline); - } else { - var owner=new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner(delayed,catalog,CLOCK,tags, - () -> delayed.connect(ByteArrayCodec.INSTANCE),() -> frozenDeadline-CLOCK.millis()); - try(var ignored=owner.finalizeOriginalNewOnce(source,template,account,issuer,controlledCapacity,frozenDeadline)) { - throw new AssertionError("Delayed old FINAL must not produce an admission receipt"); - } - } - }); + repairAccountMember(); + bridge(!installAction); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + String oldSha = + admin.scriptLoad( + CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest + .predecessorLuaForOwnerProof()); + var entered = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + var calls = new java.util.concurrent.atomic.AtomicInteger(); + String action = installAction ? "INSTALL" : "FINAL"; + RedisClient delayed = mock(RedisClient.class); + when(delayed.connect(ByteArrayCodec.INSTANCE)) + .thenAnswer( + ignored -> + delayedConnection( + ownerClient.connect(ByteArrayCodec.INSTANCE), + oldSha, + action, + entered, + release, + calls)); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var raw = credential.template(); + var template = raw.bindCapacityExecution(controlledCapacity)) { + var account = controlledAccountOpen(); + var issuer = issuerOpen(); + long frozenDeadline = CLOCK.millis() + 5000L; + var old = + java.util.concurrent.CompletableFuture.runAsync( + () -> { + if (installAction) { + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + fixture.dsl(), delayed, catalog, CLOCK, tags) + .authorize( + source, template, account, issuer, controlledCapacity, frozenDeadline); + } else { + var owner = + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + delayed, + catalog, + CLOCK, + tags, + () -> delayed.connect(ByteArrayCodec.INSTANCE), + () -> frozenDeadline - CLOCK.millis()); + try (var ignored = + owner.finalizeOriginalNewOnce( + source, template, account, issuer, controlledCapacity, frozenDeadline)) { + throw new AssertionError( + "Delayed old FINAL must not produce an admission receipt"); + } + } + }); try { - assertThat(entered.await(3,java.util.concurrent.TimeUnit.SECONDS)).isTrue(); - var original=regionBinding.installation(); - admin.pexpire(ascii(original.grant.key()),0); - var successor=CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( - fixture.dsl(),ownerClient,catalog,original,sources.resolver,transfer,frozenDeadline); + assertThat(entered.await(3, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + var original = regionBinding.installation(); + admin.pexpire(ascii(original.grant.key()), 0); + var successor = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + catalog, + original, + sources.resolver, + transfer, + frozenDeadline); assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); assertThat(CLOCK.millis()).isLessThan(frozenDeadline); release.countDown(); - assertThatThrownBy(() -> old.get(2,java.util.concurrent.TimeUnit.SECONDS)) + assertThatThrownBy(() -> old.get(2, java.util.concurrent.TimeUnit.SECONDS)) .isInstanceOf(java.util.concurrent.ExecutionException.class) .hasCauseInstanceOf(IllegalStateException.class); assertThat(calls.get()).isOne(); - assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(source.candidate().canonicalBytes()); - assertThat(admin.hget(ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))),ascii("state"))) + assertThat(admin.get(ascii(installation.sessionKey()))) + .containsExactly(source.candidate().canonicalBytes()); + assertThat( + admin.hget( + ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))), + ascii("state"))) .containsExactly(ascii("FENCED_INDETERMINATE")); } finally { release.countDown(); - try { old.get(5,java.util.concurrent.TimeUnit.SECONDS); } - catch(java.util.concurrent.ExecutionException expected) { /* already asserted failure */ } + try { + old.get(5, java.util.concurrent.TimeUnit.SECONDS); + } catch (java.util.concurrent.ExecutionException expected) { + /* already asserted failure */ + } } } } @SuppressWarnings("unchecked") - private static StatefulRedisConnection delayedConnection( - StatefulRedisConnection actual,String predecessorSha,String action, - java.util.concurrent.CountDownLatch entered,java.util.concurrent.CountDownLatch release, + private static StatefulRedisConnection delayedConnection( + StatefulRedisConnection actual, + String predecessorSha, + String action, + java.util.concurrent.CountDownLatch entered, + java.util.concurrent.CountDownLatch release, java.util.concurrent.atomic.AtomicInteger calls) { - var commands=actual.async(); - Object delayedCommands=java.lang.reflect.Proxy.newProxyInstance( - io.lettuce.core.api.async.RedisAsyncCommands.class.getClassLoader(), - new Class[]{io.lettuce.core.api.async.RedisAsyncCommands.class},(proxy,method,args) -> { - if(method.getName().equals("evalsha") && args.length==4 && args[3] instanceof byte[][] values - && values.length==19 && action.equals(new String(values[17],StandardCharsets.US_ASCII))) { - calls.incrementAndGet();entered.countDown(); - if(!release.await(4,java.util.concurrent.TimeUnit.SECONDS)) throw new IllegalStateException("Delayed old invocation not released"); - Object[] original=args.clone();original[0]=predecessorSha; - try { return method.invoke(commands,original); } - catch(java.lang.reflect.InvocationTargetException failure) { throw failure.getCause(); } - } - try { return method.invoke(commands,args); } - catch(java.lang.reflect.InvocationTargetException failure) { throw failure.getCause(); } - }); - return (StatefulRedisConnection)java.lang.reflect.Proxy.newProxyInstance( - StatefulRedisConnection.class.getClassLoader(),new Class[]{StatefulRedisConnection.class}, - (proxy,method,args) -> { - if(method.getName().equals("async")) return delayedCommands; - try { return method.invoke(actual,args); } - catch(java.lang.reflect.InvocationTargetException failure) { throw failure.getCause(); } - }); + var commands = actual.async(); + Object delayedCommands = + java.lang.reflect.Proxy.newProxyInstance( + io.lettuce.core.api.async.RedisAsyncCommands.class.getClassLoader(), + new Class[] {io.lettuce.core.api.async.RedisAsyncCommands.class}, + (proxy, method, args) -> { + if (method.getName().equals("evalsha") + && args.length == 4 + && args[3] instanceof byte[][] values + && values.length == 19 + && action.equals(new String(values[17], StandardCharsets.US_ASCII))) { + calls.incrementAndGet(); + entered.countDown(); + if (!release.await(4, java.util.concurrent.TimeUnit.SECONDS)) + throw new IllegalStateException("Delayed old invocation not released"); + Object[] original = args.clone(); + original[0] = predecessorSha; + try { + return method.invoke(commands, original); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + } + try { + return method.invoke(commands, args); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + return (StatefulRedisConnection) + java.lang.reflect.Proxy.newProxyInstance( + StatefulRedisConnection.class.getClassLoader(), + new Class[] {StatefulRedisConnection.class}, + (proxy, method, args) -> { + if (method.getName().equals("async")) return delayedCommands; + try { + return method.invoke(actual, args); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); } /** A real child JVM halts only after independent visibility of the real owner's SQL commit. */ public static final class StopAfterAuthorizationCommit { private StopAfterAuthorizationCommit() {} + public static void main(String[] args) throws Exception { - var raw=new DriverManagerDataSource(args[0],args[1],args[2]); - var execution=CanonicalGameplayRegionOwnerTransferRepository.decode(java.nio.file.Files.readAllBytes(Path.of(args[3]))); - var stopping=new org.springframework.jdbc.datasource.DelegatingDataSource(raw) { - @Override public java.sql.Connection getConnection() throws java.sql.SQLException { - var actual=raw.getConnection(); - return (java.sql.Connection)java.lang.reflect.Proxy.newProxyInstance( - java.sql.Connection.class.getClassLoader(),new Class[]{java.sql.Connection.class},(proxy,method,values) -> { - Object result; - try { result=method.invoke(actual,values); } - catch(java.lang.reflect.InvocationTargetException failure) { throw failure.getCause(); } - if(method.getName().equals("commit")) { - try(var independent=raw.getConnection();var check=independent.prepareStatement("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?")) { - check.setString(1,execution.digest()); - try(var rows=check.executeQuery()) { - if(rows.next() && "INSTALL_DISPATCHED".equals(rows.getString(1))) { - System.out.println("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); - System.out.flush(); - Runtime.getRuntime().halt(72); - } - } - } - } - return result; - }); - } - }; - var sql=org.jooq.impl.DSL.using(stopping,org.jooq.SQLDialect.POSTGRES); - var candidate=CanonicalGameplayOriginalNewCandidate.parseCanonical(sql.fetchSingle( - "SELECT original_new_candidate_bytes FROM game_session_canonical_binding_transition WHERE transition_id=?",execution.transitionId()).get(0,byte[].class)); - var inventory=new CanonicalGameplayBindingInventoryRepository(sql); - var decision=inventory.readAdmissionDecision(execution.transitionId(),candidate.leaseEvidence()); - var source=inventory.readOriginalNewFinalAdmissionSource(decision); - try(var unused=RedisClient.create("redis://127.0.0.1:1")) { - var scripts=RedisScriptCatalog.fromContributions(List.of(new net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution())); - var owner=new CanonicalGameplayOriginalNewCapacityExecutionOwner(sql,unused,scripts,Clock.systemUTC(),new CanonicalGameplayTenantGameplayTagRepository(sql,"test",1)); - owner.authorize(source,null,null,null,execution,System.currentTimeMillis()+5000); + var raw = new DriverManagerDataSource(args[0], args[1], args[2]); + var execution = + CanonicalGameplayRegionOwnerTransferRepository.decode( + java.nio.file.Files.readAllBytes(Path.of(args[3]))); + var stopping = + new org.springframework.jdbc.datasource.DelegatingDataSource(raw) { + @Override + public java.sql.Connection getConnection() throws java.sql.SQLException { + var actual = raw.getConnection(); + return (java.sql.Connection) + java.lang.reflect.Proxy.newProxyInstance( + java.sql.Connection.class.getClassLoader(), + new Class[] {java.sql.Connection.class}, + (proxy, method, values) -> { + Object result; + try { + result = method.invoke(actual, values); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + if (method.getName().equals("commit")) { + try (var independent = raw.getConnection(); + var check = + independent.prepareStatement( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?")) { + check.setString(1, execution.digest()); + try (var rows = check.executeQuery()) { + if (rows.next() && "INSTALL_DISPATCHED".equals(rows.getString(1))) { + System.out.println("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); + System.out.flush(); + Runtime.getRuntime().halt(72); + } + } + } + } + return result; + }); + } + }; + var sql = org.jooq.impl.DSL.using(stopping, org.jooq.SQLDialect.POSTGRES); + var candidate = + CanonicalGameplayOriginalNewCandidate.parseCanonical( + sql.fetchSingle( + "SELECT original_new_candidate_bytes FROM game_session_canonical_binding_transition WHERE transition_id=?", + execution.transitionId()) + .get(0, byte[].class)); + var inventory = new CanonicalGameplayBindingInventoryRepository(sql); + var decision = + inventory.readAdmissionDecision(execution.transitionId(), candidate.leaseEvidence()); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + try (var unused = RedisClient.create("redis://127.0.0.1:1")) { + var scripts = + RedisScriptCatalog.fromContributions( + List.of( + new net.firedevops.firemud.gamesession.service + .CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution())); + var owner = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + sql, + unused, + scripts, + Clock.systemUTC(), + new CanonicalGameplayTenantGameplayTagRepository(sql, "test", 1)); + owner.authorize(source, null, null, null, execution, System.currentTimeMillis() + 5000); } - throw new IllegalStateException("Expected committed authorization to stop the process before Redis dispatch"); + throw new IllegalStateException( + "Expected committed authorization to stop the process before Redis dispatch"); } } 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 a03ef3da4e..93f7ec8a0d 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 @@ -118,17 +118,38 @@ record ExistingBinding( CanonicalGameplayRegionLeaseOwner.Installation installation, CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement acknowledgement) {} - /** Actual acquire/install/revalidate path; only upstream placement/incarnation remain controlled. */ + /** + * Actual acquire/install/revalidate path; only upstream placement/incarnation remain controlled. + */ static CanonicalGameplayRegionLeaseOwner.Installation handoffExistingOriginal( - DSLContext dsl, RedisClient coordinationRedis, RedisScriptCatalog catalog, + DSLContext dsl, + RedisClient coordinationRedis, + RedisScriptCatalog catalog, CanonicalGameplayRegionLeaseOwner.Installation original, CanonicalInitialPlayerLocationRegionResolver resolver, - CanonicalGameplayRegionOwnerTransferCoordinator transfer,long deadline) { - var identity=new RuntimeIdentity("game-session-service","final-owner-handoff", - "localhost",Instant.now(),"test","test","controlled-test-image"); - var successor=CanonicalGameplayRegionLeaseOwnerFactory.compose(dsl,coordinationRedis,catalog, - new ControlledStableIncarnationSource(),resolver,identity,Duration.ofSeconds(30),Clock.systemUTC()); - return successor.installForTransition(null,original.transitionId,original.worldRequest,transfer,deadline); + CanonicalGameplayRegionOwnerTransferCoordinator transfer, + long deadline) { + var identity = + new RuntimeIdentity( + "game-session-service", + "final-owner-handoff", + "localhost", + Instant.now(), + "test", + "test", + "controlled-test-image"); + var successor = + CanonicalGameplayRegionLeaseOwnerFactory.compose( + dsl, + coordinationRedis, + catalog, + new ControlledStableIncarnationSource(), + resolver, + identity, + Duration.ofSeconds(30), + Clock.systemUTC()); + return successor.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline); } /** diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 7deacd9478..a96947e6dc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -45,8 +45,8 @@ import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -231,7 +231,9 @@ void sameNaturalScopeRejectsChangedWorldCaptureEvidence() { assertThatThrownBy( () -> repository.find( - source(source.gameInstanceId(), new UUID(0x6666666666666666L, 0x8666666666666666L)))) + source( + source.gameInstanceId(), + new UUID(0x6666666666666666L, 0x8666666666666666L)))) .isInstanceOf(IllegalStateException.class); } @@ -367,7 +369,8 @@ void actualAuthorizationHoldingRegionRowMakesFreezeWaitAndRetainsThatOriginal() Future authorization = executor.submit( () -> - proof.capacity(gate.attach(proof.sql)) + proof + .capacity(gate.attach(proof.sql)) .authorize( proof.admission, template, @@ -380,7 +383,8 @@ void actualAuthorizationHoldingRegionRowMakesFreezeWaitAndRetainsThatOriginal() executor.submit( () -> proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.begin(proof.scope, proof.prior))); + transferDeadline(), + ignored -> proof.transfers.begin(proof.scope, proof.prior))); try { assertDatabaseWaitsFor(proof.sql, gate.backendPid()); assertThat(freeze.isDone()).isFalse(); @@ -391,8 +395,9 @@ void actualAuthorizationHoldingRegionRowMakesFreezeWaitAndRetainsThatOriginal() UUID id = freeze.get(10, TimeUnit.SECONDS); assertThat(id).isNotNull(); assertThat(proof.executionState(proof.execution)).isEqualTo("AUTHORIZED"); - assertThat( - proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id))) + List captured = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertThat(captured) .extracting(item -> item.execution().digest()) .containsExactly(proof.execution.digest()); assertThat(proof.currentOwner()).isEqualTo(proof.prior); @@ -400,7 +405,8 @@ void actualAuthorizationHoldingRegionRowMakesFreezeWaitAndRetainsThatOriginal() } @Test - void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch() throws Exception { + void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch() + throws Exception { try (var proof = new TransferSqlProof(); var credential = new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( @@ -424,7 +430,8 @@ void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch( executor.submit( () -> { try { - proof.capacity(proof.sql) + proof + .capacity(proof.sql) .authorize( proof.admission, template, @@ -450,8 +457,9 @@ void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch( assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); // The INSERT trigger independently takes the same row lock and rejects raw late dispatch. assertSqlGuard(() -> proof.seedUndeliveredDispatch(proof.execution)); - assertThat( - proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id))) + List captured = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertThat(captured) .extracting(item -> item.execution().digest()) .containsExactly(seeded.digest()); assertThat(proof.currentOwner()).isEqualTo(proof.prior); @@ -468,8 +476,7 @@ void competingTransferCreatorsAndLostBeginReplyKeepOneOriginalIntent() throws Ex var other = proof.transfers(proof.sql); Future first = executor.submit(() -> beginAfterBarrier(proof, proof.transfers, ready, start)); - Future second = - executor.submit(() -> beginAfterBarrier(proof, other, ready, start)); + Future second = executor.submit(() -> beginAfterBarrier(proof, other, ready, start)); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); UUID retained = first.get(10, TimeUnit.SECONDS); @@ -477,26 +484,29 @@ void competingTransferCreatorsAndLostBeginReplyKeepOneOriginalIntent() throws Ex String original = proof.transferImage(retained); assertThatThrownBy( () -> { - other.within( - transferDeadline(), ignored -> other.begin(proof.scope, proof.prior)); - throw new IllegalStateException("Controlled lost begin reply after committed readback"); + other.within(transferDeadline(), ignored -> other.begin(proof.scope, proof.prior)); + throw new IllegalStateException( + "Controlled lost begin reply after committed readback"); }) .hasMessage("Controlled lost begin reply after committed readback"); var recreated = proof.transfers(proof.sql); - assertThat( - recreated.within( - transferDeadline(), ignored -> recreated.begin(proof.scope, proof.prior))) - .isEqualTo(retained); + UUID replayed = + recreated.within( + transferDeadline(), ignored -> recreated.begin(proof.scope, proof.prior)); + assertThat(replayed).isEqualTo(retained); assertThat(proof.transferImage(retained)).isEqualTo(original); assertThat( - proof.sql.fetchSingle("SELECT count(*) FROM game_session_region_owner_transfer") + proof + .sql + .fetchSingle("SELECT count(*) FROM game_session_region_owner_transfer") .get(0, Long.class)) .isEqualTo(1L); } } @Test - void boundedCensusAndVerificationResumeBeyondThirtyTwoWithoutLosingAnyOriginal() throws Exception { + void boundedCensusAndVerificationResumeBeyondThirtyTwoWithoutLosingAnyOriginal() + throws Exception { try (var proof = new TransferSqlProof()) { // Controlled reservation envelopes seed SQL custody, not Account-authorized multiattempt // behavior. Every candidate, bridge, mapping and owner source is retained by its real owner. @@ -531,8 +541,7 @@ void boundedCensusAndVerificationResumeBeyondThirtyTwoWithoutLosingAnyOriginal() for (int size : List.of(32, 32, 1)) { long after = cursor; var page = - proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.page(id, after)); + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.page(id, after)); assertThat(page).hasSize(size); captured.addAll(page.stream().map(item -> item.execution().digest()).toList()); cursor = page.getLast().ordinal(); @@ -541,45 +550,49 @@ void boundedCensusAndVerificationResumeBeyondThirtyTwoWithoutLosingAnyOriginal() .containsExactlyInAnyOrderElementsOf( originals.stream().map(OriginalNewCapacityExecution::digest).toList()); assertThat(cursor).isEqualTo(64L); - assertThat( - proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.verificationCursor(id))) - .isEqualTo(-1L); + long initialVerificationCursor = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id)); + assertThat(initialVerificationCursor).isEqualTo(-1L); proof.verifyPage(id); - assertThat( - proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.finishVerification(id))) - .isFalse(); + boolean firstPageComplete = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(firstPageComplete).isFalse(); assertThatThrownBy(() -> proof.install(id)).isInstanceOf(IllegalStateException.class); proof.recreateTransferOwners(); - assertThat( - proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.verificationCursor(id))) - .isEqualTo(31L); + long resumedVerificationCursor = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.verificationCursor(id)); + assertThat(resumedVerificationCursor).isEqualTo(31L); proof.verifyPage(id); - assertThat( - proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.finishVerification(id))) - .isFalse(); + boolean secondPageComplete = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(secondPageComplete).isFalse(); proof.recreateTransferOwners(); proof.verifyPage(id); - assertThat( - proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.finishVerification(id))) - .isTrue(); + boolean allPagesComplete = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(allPagesComplete).isTrue(); var installed = proof.install(id); assertThat(installed.executorFence()).isGreaterThan(proof.prior.executorFence()); assertThat(proof.currentOwner()).isEqualTo(installed); assertThat(proof.transfers.readCurrent(id, 64).controlState()).isEqualTo("COMPLETED"); assertThat( - proof.sql.fetchSingle( + proof + .sql + .fetchSingle( "SELECT count(*) FROM game_session_region_owner_transfer_item" + " WHERE transfer_id=? AND fence_readback IS NOT NULL AND verified_round IS NOT NULL", id) .get(0, Long.class)) .isEqualTo(65L); assertThat( - proof.sql.fetch("SELECT status FROM game_session_original_new_capacity_execution") + proof + .sql + .fetch("SELECT status FROM game_session_original_new_capacity_execution") .getValues("status", String.class)) .containsOnly("INSTALL_DISPATCHED"); } @@ -597,10 +610,10 @@ void finalQualificationRechecksLostFenceBeyondTheFirstPageWithoutRecreatingIt() proof.verifyPage(id); proof.recreateTransferOwners(); proof.verifyPage(id); - assertThat( - proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.finishVerification(id))) - .isTrue(); + boolean allPagesComplete = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(allPagesComplete).isTrue(); var last = proof.transfers.within( transferDeadline(), ignored -> proof.transfers.page(id, 31).getFirst()); @@ -643,8 +656,7 @@ void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throw assertThat(proof.currentOwner()).isEqualTo(proof.prior); proof.captureAndFence(id); proof.verifyPage(id); - proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.finishVerification(id)); var installed = proof.install(id); String completed = proof.transferImage(id); assertSqlGuard(() -> proof.rawReplaceOwner("different-successor", "f".repeat(64))); @@ -676,7 +688,8 @@ void recreatedRepositoryRetainsLostFenceReplyAndImmutableOriginalReceiptsAndComp var replay = proof.transfers.within( transferDeadline(), ignored -> proof.transfers.page(id, -1).getFirst()); - assertThat(replay.execution().canonicalBytes()).containsExactly(item.execution().canonicalBytes()); + assertThat(replay.execution().canonicalBytes()) + .containsExactly(item.execution().canonicalBytes()); proof.fence(replay); assertThat(proof.itemImage(id)).isEqualTo(receipt); assertSqlGuard( @@ -713,8 +726,7 @@ void recreatedRepositoryRetainsLostFenceReplyAndImmutableOriginalReceiptsAndComp assertThat(proof.originalImage()).isEqualTo(original); assertThat(proof.itemImage(id)).isEqualTo(receipt); proof.verifyPage(id); - proof.transfers.within( - transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.finishVerification(id)); var installed = proof.install(id); String completion = proof.transferImage(id); proof.recreateTransferOwners(); @@ -790,8 +802,7 @@ private static final class RegionRowLockGate extends DefaultExecuteListener private final CountDownLatch resume = new CountDownLatch(1); DSLContext attach(DSLContext sql) { - return DSL.using( - sql.configuration().derive(new DefaultExecuteListenerProvider(this))); + return DSL.using(sql.configuration().derive(new DefaultExecuteListenerProvider(this))); } @Override @@ -845,11 +856,13 @@ private final class TransferSqlProof implements AutoCloseable { private final Clock clock = Clock.systemUTC(); private final RedisClient redis; private final CanonicalGameplayAdmissionAbortCompositionFixture fixture; - private final CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources upstream; + private final CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources + upstream; private final DSLContext sql; private final CanonicalGameplayTenantGameplayTagRepository tags; private final RedisScriptCatalog scripts; - private final CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource admission; + private final CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource + admission; private final CanonicalGameplayRegionRuntimeStatusRepository.Source scope; private final CanonicalGameplayRegionRuntimeStatus prior; private final OriginalNewCapacityExecution execution; @@ -874,20 +887,35 @@ private TransferSqlProof() throws Exception { dataSource.setPassword(POSTGRES.getPassword()); var candidate = new Candidate( - UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), - "SHARED", UUID.randomUUID(), 1L, UUID.randomUUID(), UUID.randomUUID(), - BigInteger.ONE, GameSessionAccountDelegationProfile.ISSUER, BigInteger.ONE, - BigInteger.ONE, BigInteger.ONE, BigInteger.valueOf(64)); + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 1L, + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(64)); fixture = new CanonicalGameplayAdmissionAbortCompositionFixture(dataSource, candidate, redis); sql = fixture.dsl(); tags = new CanonicalGameplayTenantGameplayTagRepository(sql, "test", 1); scripts = RedisScriptCatalog.fromContributions( List.of( - new net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution(), - new net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution(), - new net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution(), - new net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())); + new net.firedevops.firemud.gamesession.service + .CanonicalGameplayOriginalNewCandidateRedisScriptContribution(), + new net.firedevops.firemud.gamesession.service + .CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution(), + new net.firedevops.firemud.gamesession.service + .CanonicalGameplayAccountMemberRepairRedisScriptContribution(), + new net.firedevops.firemud.gamesession.service + .CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())); upstream = new CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources( sql, fixture.originalPreparedDecisionWithControlledAccountLease(), directory); @@ -900,7 +928,12 @@ private TransferSqlProof() throws Exception { .repair(fixture.transitionId()); var region = CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( - sql, redis, fixture.transitionId(), upstream.request, upstream.resolver, upstream.entity); + sql, + redis, + fixture.transitionId(), + upstream.request, + upstream.resolver, + upstream.entity); admission = inventory.readOriginalNewFinalAdmissionSource(decision); scope = region.installation().source; prior = new CanonicalGameplayRegionRuntimeStatusRepository(sql).find(scope).orElseThrow(); @@ -910,10 +943,15 @@ private TransferSqlProof() throws Exception { private OriginalNewCapacityExecution newControlledExecution() { var controlled = - CanonicalGameplayOriginalNewFinalAdmissionTestFixture.controlledCapacity(admission, clock); + CanonicalGameplayOriginalNewFinalAdmissionTestFixture.controlledCapacity( + admission, clock); return new OriginalNewCapacityExecution( - controlled.request(), controlled.reservation(), controlled.transitionId(), - controlled.candidateDigest(), prior.ownerInstanceId(), prior.executorFence().longValueExact()); + controlled.request(), + controlled.reservation(), + controlled.transitionId(), + controlled.candidateDigest(), + prior.ownerInstanceId(), + prior.executorFence().longValueExact()); } private CanonicalGameplayRegionOwnerTransferRepository transfers(DSLContext context) { @@ -921,13 +959,18 @@ private CanonicalGameplayRegionOwnerTransferRepository transfers(DSLContext cont } private CanonicalGameplayOriginalNewCapacityExecutionOwner capacity(DSLContext context) { - return new CanonicalGameplayOriginalNewCapacityExecutionOwner(context, redis, scripts, clock, tags); + return new CanonicalGameplayOriginalNewCapacityExecutionOwner( + context, redis, scripts, clock, tags); } private void recreateTransferOwners() throws Exception { transfers = transfers(sql); - receiver = new CanonicalGameplayControlledRegionTransferObservationFixture(clock).receiver(transfers, tags); - coordinator = new CanonicalGameplayRegionOwnerTransferCoordinator(sql, clock, transfers, capacity(sql), receiver); + receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture(clock) + .receiver(transfers, tags); + coordinator = + new CanonicalGameplayRegionOwnerTransferCoordinator( + sql, clock, transfers, capacity(sql), receiver); } private UUID begin() { @@ -943,12 +986,19 @@ private void seedUndeliveredDispatch(OriginalNewCapacityExecution original) { + " reservation_id,reservation_fence,mutation_digest,execution_digest,canonical_execution," + " selected_owner_id,selected_owner_fence,tenant_gameplay_tag,status)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,'INSTALL_DISPATCHED')", - original.request().identity().tenantId(), original.request().identity().requestId(), - original.request().identity().admissionId(), original.request().admissionAttemptId(), - original.transitionId(), original.request().capacityRearmFence(), - original.reservation().reservationId(), original.reservation().reservationFence(), - original.request().mutationDigest(), original.digest(), original.canonicalBytes(), - original.selectedOwnerId(), original.selectedOwnerFence(), + original.request().identity().tenantId(), + original.request().identity().requestId(), + original.request().identity().admissionId(), + original.request().admissionAttemptId(), + original.transitionId(), + original.request().capacityRearmFence(), + original.reservation().reservationId(), + original.reservation().reservationFence(), + original.request().mutationDigest(), + original.digest(), + original.canonicalBytes(), + original.selectedOwnerId(), + original.selectedOwnerFence(), tags.assignmentForTransition(original.transitionId()).tenantGameplayTag()); } @@ -960,9 +1010,13 @@ private List captureAndFenc } private void fence(CanonicalGameplayRegionOwnerTransferRepository.Item item) { - var before = receiver.observeForRegionOwnerTransfer(item.transferId(), item.ordinal(), transferDeadline()); + var before = + receiver.observeForRegionOwnerTransfer( + item.transferId(), item.ordinal(), transferDeadline()); var actual = capacity(sql).fenceForTransfer(item, transferDeadline()); - var after = receiver.observeForRegionOwnerTransfer(item.transferId(), item.ordinal(), transferDeadline()); + var after = + receiver.observeForRegionOwnerTransfer( + item.transferId(), item.ordinal(), transferDeadline()); transfers.within( transferDeadline(), ignored -> { @@ -972,7 +1026,8 @@ private void fence(CanonicalGameplayRegionOwnerTransferRepository.Item item) { } private void verifyPage(UUID id) { - long cursor = transfers.within(transferDeadline(), ignored -> transfers.verificationCursor(id)); + long cursor = + transfers.within(transferDeadline(), ignored -> transfers.verificationCursor(id)); var page = transfers.within(transferDeadline(), ignored -> transfers.page(id, cursor)); assertThat(page.size()).isLessThanOrEqualTo(32); for (var item : page) { @@ -989,12 +1044,22 @@ private void verifyPage(UUID id) { } private CanonicalGameplayRegionRuntimeStatus install(UUID id) { - return coordinator.install(id, scope, prior, "e".repeat(64), "game-session-service", "sql-proof-successor", transferDeadline()); + return coordinator.install( + id, + scope, + prior, + "e".repeat(64), + "game-session-service", + "sql-proof-successor", + transferDeadline()); } private CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback issuerOpen() { - var repository = new CanonicalGameplayIssuerAdmissionBarrierRepository(sql, tags, fixture.currentIssuerSource()); - return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner(redis, scripts, repository, fixture.currentIssuerSource()) + var repository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + sql, tags, fixture.currentIssuerSource()); + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + redis, scripts, repository, fixture.currentIssuerSource()) .initializeAndRead(fixture.originalOperationId()); } @@ -1003,22 +1068,55 @@ private CanonicalGameplayAccountInitialOpenProof.CurrentOpen controlledAccountOp var assignment = tags.assignmentForTransition(fixture.transitionId()); UUID initializer = UUID.randomUUID(); String incarnation = "sha256:" + "a".repeat(64); - String key = "session:game:account-admission:{" + assignment.tenantGameplayTag() + "}:" - + binding.accountId() + ":" + binding.playableStateNamespaceId(); - Map fields = Map.of( - "schema", CanonicalGameplayAccountInitialBarrierValue.SCHEMA, "state", "OPEN", - "accountId", binding.accountId().toString(), "tenantId", binding.tenantId().toString(), - "playableStateNamespaceId", binding.playableStateNamespaceId().toString(), - "tenantGameplayTag", assignment.tenantGameplayTag(), "ownerOperationId", initializer.toString(), - "ownerFenceEpoch", "1", "incarnationDigest", incarnation); + String key = + "session:game:account-admission:{" + + assignment.tenantGameplayTag() + + "}:" + + binding.accountId() + + ":" + + binding.playableStateNamespaceId(); + Map fields = + Map.of( + "schema", + CanonicalGameplayAccountInitialBarrierValue.SCHEMA, + "state", + "OPEN", + "accountId", + binding.accountId().toString(), + "tenantId", + binding.tenantId().toString(), + "playableStateNamespaceId", + binding.playableStateNamespaceId().toString(), + "tenantGameplayTag", + assignment.tenantGameplayTag(), + "ownerOperationId", + initializer.toString(), + "ownerFenceEpoch", + "1", + "incarnationDigest", + incarnation); try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) { - fields.forEach((field, value) -> connection.sync().hset(ascii(key), ascii(field), ascii(value))); + fields.forEach( + (field, value) -> connection.sync().hset(ascii(key), ascii(field), ascii(value))); } long now = clock.millis(); return new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( - initializer, UUID.randomUUID(), UUID.randomUUID(), 1L, binding.accountId(), binding.tenantId(), - binding.playableStateNamespaceId(), key, BigInteger.ONE, BigInteger.ONE, incarnation, - incarnation, incarnation, now, now + 60_000L, fields); + initializer, + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + binding.accountId(), + binding.tenantId(), + binding.playableStateNamespaceId(), + key, + BigInteger.ONE, + BigInteger.ONE, + incarnation, + incarnation, + incarnation, + now, + now + 60_000L, + fields); } private CanonicalGameplayRegionRuntimeStatus currentOwner() { @@ -1026,14 +1124,25 @@ private CanonicalGameplayRegionRuntimeStatus currentOwner() { } private String executionState(OriginalNewCapacityExecution original) { - Record row = sql.fetchOne("SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", original.digest()); + Record row = + sql.fetchOne( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + original.digest()); return row == null ? null : row.get(0, String.class); } private boolean physicalExecutionExists(OriginalNewCapacityExecution original) { String tag = tags.assignmentForTransition(original.transitionId()).tenantGameplayTag(); try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) { - return connection.sync().exists(ascii("session:game:capacity-execution:{" + tag + "}:" + original.request().admissionAttemptId())) != 0; + return connection + .sync() + .exists( + ascii( + "session:game:capacity-execution:{" + + tag + + "}:" + + original.request().admissionAttemptId())) + != 0; } } @@ -1041,9 +1150,14 @@ private void losePhysicalExecution(OriginalNewCapacityExecution original) { String tag = tags.assignmentForTransition(original.transitionId()).tenantGameplayTag(); try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) { assertThat( - connection.sync().del( - ascii("session:game:capacity-execution:{" + tag + "}:" - + original.request().admissionAttemptId()))) + connection + .sync() + .del( + ascii( + "session:game:capacity-execution:{" + + tag + + "}:" + + original.request().admissionAttemptId()))) .isEqualTo(1L); } } @@ -1051,21 +1165,33 @@ private void losePhysicalExecution(OriginalNewCapacityExecution original) { private void rawReplaceOwner(String owner, String correlation) { sql.execute( "UPDATE game_session_region_runtime_status SET owner_instance_id=?,executor_fence=nextval('game_session_region_executor_fence_seq'),lease_token_correlation=? WHERE tenant_id=? AND game_instance_id=? AND region_id=?", - owner, correlation, scope.tenantId(), scope.gameInstanceId(), scope.regionId()); + owner, + correlation, + scope.tenantId(), + scope.gameInstanceId(), + scope.regionId()); } private String originalImage() { - return sql.fetch("SELECT to_jsonb(e)::text FROM game_session_original_new_capacity_execution e ORDER BY execution_digest") - .getValues(0, String.class).toString(); + return sql.fetch( + "SELECT to_jsonb(e)::text FROM game_session_original_new_capacity_execution e ORDER BY execution_digest") + .getValues(0, String.class) + .toString(); } private String transferImage(UUID id) { - return sql.fetchSingle("SELECT to_jsonb(t)::text FROM game_session_region_owner_transfer t WHERE transfer_id=?", id).get(0, String.class); + return sql.fetchSingle( + "SELECT to_jsonb(t)::text FROM game_session_region_owner_transfer t WHERE transfer_id=?", + id) + .get(0, String.class); } private String itemImage(UUID id) { - return sql.fetch("SELECT to_jsonb(i)::text FROM game_session_region_owner_transfer_item i WHERE transfer_id=? ORDER BY target_ordinal", id) - .getValues(0, String.class).toString(); + return sql.fetch( + "SELECT to_jsonb(i)::text FROM game_session_region_owner_transfer_item i WHERE transfer_id=? ORDER BY target_ordinal", + id) + .getValues(0, String.class) + .toString(); } @Override diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index ca90b468da..832a475832 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -876,7 +876,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } - for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065")) { + for (String version : + List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -903,7 +904,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } - for (String version : List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065")) { + for (String version : + List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -1488,33 +1490,62 @@ void genuineV1063ToV1064CompletionRepairRetainsEpochSevenAndSnapshotsBeforeSeali @Test void genuineV1064ToV1065TransferFenceUpgradeRetainsOriginalRowsSnapshotsAndEpochs() { - try(Fixture f=fixture("1064")) { + try (Fixture f = fixture("1064")) { f.populatePredecessor(); - var original=f.owner().capture(request()); + var original = f.owner().capture(request()); assertThat(original.catalog().catalogEpoch()).isEqualTo(8); - Map before=f.rows(f.tables()); - before.remove(f.history);before.remove(EPOCHS);before.remove(CLASSIFICATIONS); - var epochs=f.dsl.fetch("SELECT to_jsonb(e)::text||':'||xmin::text FROM " + EPOCHS + " e ORDER BY catalog_epoch").getValues(0,String.class); - var history=f.historyRows(false); - var classifications=f.classificationRows(); - migration(f.source,f.schema,f.history,"1065").migrate(); + Map before = f.rows(f.tables()); + before.remove(f.history); + before.remove(EPOCHS); + before.remove(CLASSIFICATIONS); + var epochs = + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e ORDER BY catalog_epoch") + .getValues(0, String.class); + var history = f.historyRows(false); + var classifications = f.classificationRows(); + migration(f.source, f.schema, f.history, "1065").migrate(); assertThat(f.rows(before.keySet())).isEqualTo(before); - assertThat(f.classificationRows()).containsAllEntriesOf(classifications).hasSize(classifications.size()+2); - assertThat(f.dsl.fetch("SELECT to_jsonb(e)::text||':'||xmin::text FROM " + EPOCHS + " e WHERE catalog_epoch<=8 ORDER BY catalog_epoch").getValues(0,String.class)).isEqualTo(epochs); - assertThat(f.historyRows(false)).hasSize(history.size()+1); - assertThat(f.historyRows(false).subList(0,history.size())).isEqualTo(history); - assertThat(f.evidence(original.request())).isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); - var current=f.owner().capture(request()); + assertThat(f.classificationRows()) + .containsAllEntriesOf(classifications) + .hasSize(classifications.size() + 2); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e WHERE catalog_epoch<=8 ORDER BY catalog_epoch") + .getValues(0, String.class)) + .isEqualTo(epochs); + assertThat(f.historyRows(false)).hasSize(history.size() + 1); + assertThat(f.historyRows(false).subList(0, history.size())).isEqualTo(history); + assertThat(f.evidence(original.request())) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + var current = f.owner().capture(request()); assertThat(current.catalog().catalogEpoch()).isEqualTo(9); assertThat(f.owner().readExact(current.request())).isEqualTo(current); - assertThat(current.catalog().families()).anyMatch(family -> family.familyId().equals("game_session_region_owner_transfer")) + assertThat(current.catalog().families()) + .anyMatch(family -> family.familyId().equals("game_session_region_owner_transfer")) .anyMatch(family -> family.familyId().equals("game_session_region_owner_transfer_item")); - assertThat(f.dsl.fetchSingle("SELECT catalog_bytes=gs_runtime_family_catalog_bytes(9) FROM " + EPOCHS + " WHERE catalog_epoch=9").get(0,Boolean.class)).isTrue(); - for(String table:List.of("game_session_region_owner_transfer","game_session_region_owner_transfer_item")) { + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes=gs_runtime_family_catalog_bytes(9) FROM " + + EPOCHS + + " WHERE catalog_epoch=9") + .get(0, Boolean.class)) + .isTrue(); + for (String table : + List.of( + "game_session_region_owner_transfer", "game_session_region_owner_transfer_item")) { assertThat(f.count(table)).isZero(); - assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")).isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); } - migration(f.source,f.schema,f.history,"1065").validate(); + migration(f.source, f.schema, f.history, "1065").validate(); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java index 61b1083963..e990b39600 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java @@ -119,7 +119,9 @@ void transferSignedPurposeCannotBeReplayedThroughAccountReceiver() { .thenReturn( List.of( CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( - context.targetOrdinal(), context.tenantId(), context.playableStateNamespaceId()))); + context.targetOrdinal(), + context.tenantId(), + context.playableStateNamespaceId()))); when(fixture.assignment.isBindingTransition()).thenReturn(false); when(fixture.assignment.admissionFenceIntentOperationId()).thenReturn(context.transferId()); when(fixture.assignment.barrierTargetOrdinal()).thenReturn(context.targetOrdinal()); @@ -130,7 +132,8 @@ void transferSignedPurposeCannotBeReplayedThroughAccountReceiver() { repository, fixture.tags, fixture::signed, fixture.trust(), fixture.clock); assertThatThrownBy( () -> receiver.observeForFenceTarget(context.transferId(), context.targetOrdinal())) - .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); } @Test @@ -164,15 +167,28 @@ void transferSignedPurposeCannotBeReplayedThroughInitialReceiver() { new CanonicalGameplayProtectedIncarnationReceiver( repository, fixture.tags, fixture::signed, fixture.trust(), fixture.clock); assertThatThrownBy(() -> receiver.observeForInitialAccountBarrier(context.requestId())) - .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); } @ParameterizedTest @ValueSource( strings = { - "transferId", "transferIntentDigest", "frozenSourceDigest", "oldRegionOwnerId", - "oldRegionOwnerFence", "gameInstanceId", "regionId", "regionEpoch", "transitionId", - "requestId", "accountId", "executionDigest", "candidateDigest", "controlState", "completionDigest" + "transferId", + "transferIntentDigest", + "frozenSourceDigest", + "oldRegionOwnerId", + "oldRegionOwnerFence", + "gameInstanceId", + "regionId", + "regionEpoch", + "transitionId", + "requestId", + "accountId", + "executionDigest", + "candidateDigest", + "controlState", + "completionDigest" }) void everySignedTransferOwnerTupleMutationRefuses(String field) { var fixture = new Fixture(); @@ -183,8 +199,12 @@ void everySignedTransferOwnerTupleMutationRefuses(String field) { @ParameterizedTest @ValueSource( strings = { - "targetOrdinal", "tenantId", "playableStateNamespaceId", "tenantGameplayTag", - "workloadNamespace", "allocationVersion" + "targetOrdinal", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "workloadNamespace", + "allocationVersion" }) void everySignedTargetTupleMutationRefuses(String field) { var fixture = new Fixture(); @@ -208,8 +228,12 @@ void everySignedDeploymentIncarnationMutationRefuses(String field) { @ParameterizedTest @ValueSource( strings = { - "attestorBinding", "attestorKeyId", "acceptedAttestationDigest", "observationNonce", - "coordOpsRoAclDigest", "coordRedisConfigObservedDigest" + "attestorBinding", + "attestorKeyId", + "acceptedAttestationDigest", + "observationNonce", + "coordOpsRoAclDigest", + "coordRedisConfigObservedDigest" }) void signedTrustAndCorrelationMutationRefuses(String field) { var fixture = new Fixture(); @@ -220,8 +244,15 @@ void signedTrustAndCorrelationMutationRefuses(String field) { @ParameterizedTest @ValueSource( strings = { - "isBindingTransition", "transitionId", "accountId", "tenantId", "gameInstanceId", - "playableStateNamespaceId", "tenantGameplayTag", "workloadNamespace", "allocationVersion" + "isBindingTransition", + "transitionId", + "accountId", + "tenantId", + "gameInstanceId", + "playableStateNamespaceId", + "tenantGameplayTag", + "workloadNamespace", + "allocationVersion" }) void independentlyResolvedAssignmentMustMatchBeforeRemoteCall(String field) { var fixture = new Fixture(); @@ -242,8 +273,13 @@ void assignmentMustStillMatchAfterSignatureVerification() { @ParameterizedTest @ValueSource( strings = { - "transferIntentDigest", "frozenSourceDigest", "oldRegionOwnerId", "oldRegionOwnerFence", - "regionEpoch", "executionDigest", "candidateDigest" + "transferIntentDigest", + "frozenSourceDigest", + "oldRegionOwnerId", + "oldRegionOwnerFence", + "regionEpoch", + "executionDigest", + "candidateDigest" }) void frozenSourceMutationDuringSignedReadRefuses(String field) { var fixture = new Fixture(); @@ -265,7 +301,8 @@ void unavailableCurrentSourceAfterSignatureCannotProduceProof() { var fixture = new Fixture(); fixture.afterSign = () -> fixture.sourceUnavailable = true; assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) - .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); assertThat(fixture.sourceReads).hasValue(2); } @@ -300,7 +337,10 @@ void changedSealedCompletionDuringObservationRefuses() { @ValueSource(strings = {"FROZEN", "COMPLETED"}) void signedProofCannotSubstituteTheOtherControlPhase(String currentPhase) { var fixture = - new Fixture("game-session-original", currentPhase, "COMPLETED".equals(currentPhase) ? DIGEST : null); + new Fixture( + "game-session-original", + currentPhase, + "COMPLETED".equals(currentPhase) ? DIGEST : null); fixture.mutation = root -> { var owner = object(root, "owner"); @@ -330,11 +370,16 @@ void phaseAndCompletionFieldsMustBothBePresentEvenForFrozenNullCompletion() { @Test void sourceContextRejectsUnsupportedOrMismatchedControlPhaseAndCompletion() { var context = new Fixture().original; - assertThatThrownBy(() -> withPhase(context, "UNKNOWN", null)).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> withPhase(context, null, null)).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> withPhase(context, "FROZEN", DIGEST)).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> withPhase(context, "COMPLETED", null)).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> withPhase(context, "COMPLETED", "not-a-digest")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "UNKNOWN", null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "FROZEN", DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "COMPLETED", null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> withPhase(context, "COMPLETED", "not-a-digest")) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -362,7 +407,8 @@ void retainedOwnerLengthUsesThePostgresCharacterBound() { void timeWindowMismatchOrDeadlineExpiryRefuses(String mode) { var fixture = new Fixture(); switch (mode) { - case "issued" -> fixture.mutation = root -> root.put("observationIssuedAtEpochMillis", NOW - 1L); + case "issued" -> + fixture.mutation = root -> root.put("observationIssuedAtEpochMillis", NOW - 1L); case "observed-before" -> fixture.mutation = root -> root.put("observationObservedAtEpochMillis", NOW - 1L); case "observed-after" -> @@ -380,7 +426,8 @@ void timeWindowMismatchOrDeadlineExpiryRefuses(String mode) { void expiredOperationNeverReadsSourceOrCallsChannel() { var fixture = new Fixture(); assertThatThrownBy(() -> fixture.observe(NOW)) - .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); assertThat(fixture.sourceReads).hasValue(0); assertThat(fixture.channelCalls).hasValue(0); } @@ -390,7 +437,8 @@ void sourceReadCannotRenewAnOperationThatExpiredBeforeChannelDispatch() { var fixture = new Fixture(); fixture.onSourceRead = () -> fixture.now.set(NOW + 1_000L); assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) - .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); assertThat(fixture.channelCalls).hasValue(0); } @@ -404,7 +452,15 @@ void signedUnknownFieldsAreRejectedInEveryClosedObject(String object) { } @ParameterizedTest - @ValueSource(strings = {"operationId", "operationFence", "initializerId", "originalAttemptFence", "progressCursor", "completedCount"}) + @ValueSource( + strings = { + "operationId", + "operationFence", + "initializerId", + "originalAttemptFence", + "progressCursor", + "completedCount" + }) void accountInitialAndMutableProgressFieldsAreNotTransferOwnerFields(String field) { var fixture = new Fixture(); fixture.mutation = root -> object(root, "owner").put(field, "unexpected"); @@ -412,7 +468,8 @@ void accountInitialAndMutableProgressFieldsAreNotTransferOwnerFields(String fiel } @ParameterizedTest - @ValueSource(strings = {"signature", "unpinned", "noncanonical", "duplicate", "oversized", "utf8"}) + @ValueSource( + strings = {"signature", "unpinned", "noncanonical", "duplicate", "oversized", "utf8"}) void cryptographicCanonicalParsingAndSizeFailuresRefuse(String mode) { var fixture = new Fixture(); fixture.encodingFailure = mode; @@ -437,40 +494,83 @@ void ambientTransactionRefusesBeforeReadingSqlOrCallingChannel() { void sourceContextRejectsInvalidUuidFenceEpochDigestAndBoundedIdentifiers() { var context = new Fixture().original; for (String field : - List.of("nil-transfer", "negative-ordinal", "zero-fence", "zero-epoch", "digest", "owner", "owner-null", "owner-blank", "owner-untrimmed", "workload", "allocation")) { - assertThatThrownBy(() -> invalid(context, field)).isInstanceOf(IllegalArgumentException.class); + List.of( + "nil-transfer", + "negative-ordinal", + "zero-fence", + "zero-epoch", + "digest", + "owner", + "owner-null", + "owner-blank", + "owner-untrimmed", + "workload", + "allocation")) { + assertThatThrownBy(() -> invalid(context, field)) + .isInstanceOf(IllegalArgumentException.class); } } private static void assertRejected(Fixture fixture) { assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) - .isInstanceOf(CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); } private static CanonicalGameplayRegionOwnerTransferObservationSource.Context changed( CanonicalGameplayRegionOwnerTransferObservationSource.Context c, String field) { return new CanonicalGameplayRegionOwnerTransferObservationSource.Context( - c.transferId(), c.targetOrdinal(), + c.transferId(), + c.targetOrdinal(), "transferIntentDigest".equals(field) ? OTHER_DIGEST : c.transferIntentDigest(), "frozenSourceDigest".equals(field) ? OTHER_DIGEST : c.frozenSourceDigest(), "oldRegionOwnerId".equals(field) ? "different-owner" : c.oldRegionOwnerId(), - "oldRegionOwnerFence".equals(field) ? c.oldRegionOwnerFence() + 1L : c.oldRegionOwnerFence(), - c.tenantId(), c.gameInstanceId(), c.regionId(), + "oldRegionOwnerFence".equals(field) + ? c.oldRegionOwnerFence() + 1L + : c.oldRegionOwnerFence(), + c.tenantId(), + c.gameInstanceId(), + c.regionId(), "regionEpoch".equals(field) ? c.regionEpoch() + 1L : c.regionEpoch(), - c.transitionId(), c.requestId(), c.accountId(), c.playableStateNamespaceId(), + c.transitionId(), + c.requestId(), + c.accountId(), + c.playableStateNamespaceId(), "executionDigest".equals(field) ? OTHER_DIGEST : c.executionDigest(), "candidateDigest".equals(field) ? OTHER_DIGEST : c.candidateDigest(), - c.tenantGameplayTag(), c.workloadNamespace(), c.allocationVersion(), c.controlState(), c.completionDigest()); + c.tenantGameplayTag(), + c.workloadNamespace(), + c.allocationVersion(), + c.controlState(), + c.completionDigest()); } private static CanonicalGameplayRegionOwnerTransferObservationSource.Context withPhase( - CanonicalGameplayRegionOwnerTransferObservationSource.Context c, String phase, String completionDigest) { + CanonicalGameplayRegionOwnerTransferObservationSource.Context c, + String phase, + String completionDigest) { return new CanonicalGameplayRegionOwnerTransferObservationSource.Context( - c.transferId(), c.targetOrdinal(), c.transferIntentDigest(), c.frozenSourceDigest(), - c.oldRegionOwnerId(), c.oldRegionOwnerFence(), c.tenantId(), c.gameInstanceId(), c.regionId(), - c.regionEpoch(), c.transitionId(), c.requestId(), c.accountId(), c.playableStateNamespaceId(), - c.executionDigest(), c.candidateDigest(), c.tenantGameplayTag(), c.workloadNamespace(), - c.allocationVersion(), phase, completionDigest); + c.transferId(), + c.targetOrdinal(), + c.transferIntentDigest(), + c.frozenSourceDigest(), + c.oldRegionOwnerId(), + c.oldRegionOwnerFence(), + c.tenantId(), + c.gameInstanceId(), + c.regionId(), + c.regionEpoch(), + c.transitionId(), + c.requestId(), + c.accountId(), + c.playableStateNamespaceId(), + c.executionDigest(), + c.candidateDigest(), + c.tenantGameplayTag(), + c.workloadNamespace(), + c.allocationVersion(), + phase, + completionDigest); } private static CanonicalGameplayRegionOwnerTransferObservationSource.Context invalid( @@ -487,14 +587,24 @@ private static CanonicalGameplayRegionOwnerTransferObservationSource.Context inv "nil-transfer".equals(field) ? new UUID(0L, 0L) : c.transferId(), "negative-ordinal".equals(field) ? -1L : c.targetOrdinal(), "digest".equals(field) ? "sha256:" + "A".repeat(64) : c.transferIntentDigest(), - c.frozenSourceDigest(), owner, + c.frozenSourceDigest(), + owner, "zero-fence".equals(field) ? 0L : c.oldRegionOwnerFence(), - c.tenantId(), c.gameInstanceId(), c.regionId(), + c.tenantId(), + c.gameInstanceId(), + c.regionId(), "zero-epoch".equals(field) ? 0L : c.regionEpoch(), - c.transitionId(), c.requestId(), c.accountId(), c.playableStateNamespaceId(), - c.executionDigest(), c.candidateDigest(), c.tenantGameplayTag(), + c.transitionId(), + c.requestId(), + c.accountId(), + c.playableStateNamespaceId(), + c.executionDigest(), + c.candidateDigest(), + c.tenantGameplayTag(), "workload".equals(field) ? "INVALID_NAMESPACE" : c.workloadNamespace(), - "allocation".equals(field) ? 0 : c.allocationVersion(), c.controlState(), c.completionDigest()); + "allocation".equals(field) ? 0 : c.allocationVersion(), + c.controlState(), + c.completionDigest()); } @SuppressWarnings("unchecked") @@ -533,7 +643,8 @@ private static final class Fixture { private final AtomicInteger sourceReads = new AtomicInteger(); private final AtomicInteger channelCalls = new AtomicInteger(); private final CanonicalGameplayRegionOwnerTransferObservationSource.Context original; - private final AtomicReference current; + private final AtomicReference + current; private final CanonicalGameplayTenantGameplayTagRepository tags = mock(CanonicalGameplayTenantGameplayTagRepository.class); private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = @@ -552,10 +663,27 @@ private Fixture(String ownerId, String controlState, String completionDigest) { UUID tenant = UUID.randomUUID(); original = new CanonicalGameplayRegionOwnerTransferObservationSource.Context( - UUID.randomUUID(), 3L, DIGEST, DIGEST, ownerId, 7L, - tenant, UUID.randomUUID(), UUID.randomUUID(), 11L, UUID.randomUUID(), - UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), DIGEST, DIGEST, - "g1-" + tenant.toString().replace("-", ""), "test-workload", 1, controlState, completionDigest); + UUID.randomUUID(), + 3L, + DIGEST, + DIGEST, + ownerId, + 7L, + tenant, + UUID.randomUUID(), + UUID.randomUUID(), + 11L, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + DIGEST, + DIGEST, + "g1-" + tenant.toString().replace("-", ""), + "test-workload", + 1, + controlState, + completionDigest); current = new AtomicReference<>(original); when(clock.millis()).thenAnswer(invocation -> now.get()); when(tags.assignmentForTransition(original.transitionId())).thenReturn(assignment); @@ -570,18 +698,23 @@ private Fixture(String ownerId, String controlState, String completionDigest) { when(assignment.allocationVersion()).thenReturn(original.allocationVersion()); } - private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observe(long deadline) { + private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observe( + long deadline) { return CanonicalGameplayProtectedIncarnationReceiver.forRegionOwnerTransfer( (transferId, ordinal) -> { sourceReads.incrementAndGet(); onSourceRead.run(); if (sourceUnavailable) { - throw new CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException( + throw new CanonicalGameplayProtectedIncarnationReceiver + .ObservationUnavailableException( "Controlled current SQL transfer source became unavailable"); } return current.get(); }, - tags, this::signed, trust(), clock) + tags, + this::signed, + trust(), + clock) .observeForRegionOwnerTransfer(original.transferId(), original.targetOrdinal(), deadline); } @@ -594,8 +727,10 @@ private void breakAssignment(String field) { case "gameInstanceId" -> when(assignment.gameInstanceId()).thenReturn(UUID.randomUUID()); case "playableStateNamespaceId" -> when(assignment.playableStateNamespaceId()).thenReturn(UUID.randomUUID()); - case "tenantGameplayTag" -> when(assignment.tenantGameplayTag()).thenReturn("g1-" + "f".repeat(32)); - case "workloadNamespace" -> when(assignment.workloadNamespace()).thenReturn("different-workload"); + case "tenantGameplayTag" -> + when(assignment.tenantGameplayTag()).thenReturn("g1-" + "f".repeat(32)); + case "workloadNamespace" -> + when(assignment.workloadNamespace()).thenReturn("different-workload"); case "allocationVersion" -> when(assignment.allocationVersion()).thenReturn(2); default -> throw new IllegalArgumentException(field); } @@ -604,12 +739,27 @@ private void breakAssignment(String field) { private CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration trust() { var evidence = new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( - "controlled-target", "generation-1", List.of("redis-a", "redis-b"), - "redis-build", "registry-1", DIGEST, "READY", "boot-1", "startup-1", - "storage-1", "aof-1"); + "controlled-target", + "generation-1", + List.of("redis-a", "redis-b"), + "redis-build", + "registry-1", + DIGEST, + "READY", + "boot-1", + "startup-1", + "storage-1", + "aof-1"); return new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( - "controlled-transfer-binding", DIGEST, Map.of(KEY_ID, (RSAPublicKey) KEYS.getPublic()), - evidence, DIGEST, DIGEST, 16 * 1024, 2, Duration.ofSeconds(30)); + "controlled-transfer-binding", + DIGEST, + Map.of(KEY_ID, (RSAPublicKey) KEYS.getPublic()), + evidence, + DIGEST, + DIGEST, + 16 * 1024, + 2, + Duration.ofSeconds(30)); } private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation signed( @@ -620,11 +770,18 @@ private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation signed( try { byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); switch (encodingFailure) { - case "noncanonical" -> bytes = (new String(bytes, StandardCharsets.UTF_8) + " ").getBytes(StandardCharsets.UTF_8); - case "duplicate" -> bytes = ("{\"schema\":\"duplicate\"," + new String(bytes, StandardCharsets.UTF_8).substring(1)).getBytes(StandardCharsets.UTF_8); + case "noncanonical" -> + bytes = + (new String(bytes, StandardCharsets.UTF_8) + " ") + .getBytes(StandardCharsets.UTF_8); + case "duplicate" -> + bytes = + ("{\"schema\":\"duplicate\"," + + new String(bytes, StandardCharsets.UTF_8).substring(1)) + .getBytes(StandardCharsets.UTF_8); case "oversized" -> bytes = new byte[17 * 1024]; case "utf8" -> bytes = new byte[] {(byte) 0xc3, (byte) 0x28}; - default -> { } + default -> {} } Signature signer = Signature.getInstance("SHA256withRSA"); signer.initSign(KEYS.getPrivate()); From 650d56d58dcaf5eadde31493829ab2d564d00420 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 04:28:39 +1300 Subject: [PATCH 22/52] Fix transfer fencing envelope and physical recovery fixtures Use the exact canonical 18-field execution envelope; preserve deterministic raw Redis images, connect transfer fixtures with their named principal and correct SQL schema, and export the cross-service observation fixture. Preserve the already-corrected runtime owner epoch regression. 111 focused unit cases, main/integration-source compilation, formatting and the rebuilt proof jar pass. Fresh physical PostgreSQL/Redis proof remains required; interrupted-INSTALL and retention obligations stay open. --- .../game-session-service/build.gradle.kts | 1 + ...ayOriginalNewFinalAdmissionRedisOwner.java | 6 ++ ...e-session-original-new-final-admission.lua | 8 ++- ...-session-original-new-final-admission.json | 2 +- ...alNewFinalAdmissionLuaIntegrationTest.java | 72 +++++++++++++++++-- ...NewFinalAdmissionOwnerIntegrationTest.java | 44 ++++++++++-- ...NewFinalAdmissionPhysicalImageFixture.java | 49 +++++++++++++ ...untimeStatusRepositoryIntegrationTest.java | 47 ++++++++++-- ...eFamilyCatalogPostgresIntegrationTest.java | 8 +-- 9 files changed, 218 insertions(+), 19 deletions(-) create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.java diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index c2bd44fa92..7ca1e44b0f 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -189,6 +189,7 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledInitialObservationFixture*.class") + include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture*.class") include("net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture*.class") } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index 04e89b7dca..a3f4184d04 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -361,6 +361,12 @@ long fenceCapacityExecutionOnce( long absoluteDeadlineMillis) { requireNoAmbientTransaction(); requireAssignment(assignment, candidate); + if (!candidate.bindingDecisionId().equals(execution.transitionId()) + || !candidate.bindingIdentity().tenantId().equals(execution.request().identity().tenantId()) + || !execution + .candidateDigest() + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(candidate.canonicalBytes()))) + throw unavailable(); String accountKey = ACCOUNT_PREFIX + "{" diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua index a7578545b6..f903e14e90 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua @@ -102,8 +102,14 @@ if KEYS[1] ~= prefix .. slot .. ':' .. gameInstanceId .. ':' .. sessionId if action == 'FENCE' then local capacityNames = {'schema', 'tenantId', 'requestId', 'admissionId', 'admissionAttemptId', 'reservationId', 'reservationFence', 'capacityRearmFence', 'selectedOwnerId', - 'selectedOwnerFence', 'transitionId', 'expiresAtMillis'} + 'selectedOwnerFence', 'transitionId', 'expiresAtMillis', 'mutationDigest', 'expiresAt', + 'snapshotIdentity', 'evaluationIdentity', 'candidateDigest', 'canonicalAttemptPayload'} if not objectWithFields(capacity, capacityNames) then return -2 end + for _, name in ipairs(capacityNames) do + if type(capacity[name]) ~= 'string' or #capacity[name] == 0 then return -2 end + end + if #capacity.candidateDigest ~= 71 + or not string.match(capacity.candidateDigest, '^sha256:[0-9a-f]+$') then return -2 end local capacityType = redis.call('TYPE', KEYS[7]).ok if capacityType ~= 'none' then if capacityType ~= 'hash' or redis.call('PTTL', KEYS[7]) ~= -1 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json index 42b71ac832..9ea8d50009 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.original-new-final-admission.v1", "resourcePath": "redis/lua/game-session-original-new-final-admission.lua", - "sha256": "a9c4f5505d12ed4a06cc96f4ab29c5738889ebb5c9321536b084fa82faa273d4", + "sha256": "0ed090df2d591f1d9001f812ce0ffe23a9de2916c17423834f7ced02bb6fbcc9", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java index bc9356981a..8b7f1d6c60 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java @@ -507,7 +507,20 @@ void fenceRefusesWrongTypeTtlIdentityAndEveryUnexpectedPhysicalShapeWithoutMutat void fenceRequiresTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() throws Exception { for (String fault : - List.of("missing-field", "extra-field", "wrong-tenant", "invalid-fence", "wrong-key")) { + List.of( + "missing-field", + "missing-mutationDigest", + "missing-expiresAt", + "missing-snapshotIdentity", + "missing-evaluationIdentity", + "missing-candidateDigest", + "missing-canonicalAttemptPayload", + "extra-field", + "wrong-tenant", + "invalid-fence", + "invalid-candidate-digest", + "non-string-candidate-digest", + "wrong-key")) { admin.flushdb(); ScriptCase original = seed(false); byte[][] arguments = action(original, "FENCE").arguments().clone(); @@ -515,9 +528,18 @@ void fenceRequiresTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() var envelope = (tools.jackson.databind.node.ObjectNode) JSON.readTree(arguments[16]); switch (fault) { case "missing-field" -> envelope.remove("reservationId"); + case "missing-mutationDigest", + "missing-expiresAt", + "missing-snapshotIdentity", + "missing-evaluationIdentity", + "missing-candidateDigest", + "missing-canonicalAttemptPayload" -> + envelope.remove(fault.substring("missing-".length())); case "extra-field" -> envelope.put("unexpected", "foreign"); case "wrong-tenant" -> envelope.put("tenantId", ACCOUNT); case "invalid-fence" -> envelope.put("selectedOwnerFence", "0"); + case "invalid-candidate-digest" -> envelope.put("candidateDigest", "foreign"); + case "non-string-candidate-digest" -> envelope.put("candidateDigest", 1); case "wrong-key" -> keys[6] = keys[6] + ":foreign"; default -> throw new IllegalStateException("Unknown fixture fault: " + fault); } @@ -533,16 +555,50 @@ void fenceRequiresTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() private Map physicalImage(ScriptCase original) { Map image = new LinkedHashMap<>(); - for (String key : original.keys()) image.put(key, admin.dump(ascii(key))); + for (String key : original.keys()) + image.put( + key, + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, ascii(key))); return image; } + @Test + void physicalImagePreservesRawHashFieldsValuesAndSetMembersIndependentOfIterationOrder() + throws Exception { + ScriptCase original = seed(); + byte[] hash = ascii(original.keys()[4]); + byte[] field = new byte[] {0, (byte) 0xff, 1}; + byte[] value = new byte[] {2, 0, (byte) 0xfe}; + admin.hset(hash, field, value); + Map before = physicalImage(original); + admin.hdel(hash, field); + admin.hset(hash, field, value); + assertPhysicalImage(original, before, 7); + + admin.hset(hash, field, new byte[] {2, 0, (byte) 0xff}); + assertThat(physicalImage(original).get(original.keys()[4])) + .isNotEqualTo(before.get(original.keys()[4])); + admin.hdel(hash, field); + admin.hset(hash, new byte[] {0, (byte) 0xff, 2}, value); + assertThat(physicalImage(original).get(original.keys()[4])) + .isNotEqualTo(before.get(original.keys()[4])); + admin.hdel(hash, new byte[] {0, (byte) 0xff, 2}); + admin.hset(hash, field, value); + admin.sadd(ascii(original.keys()[2]), value); + assertThat(physicalImage(original).get(original.keys()[2])) + .isNotEqualTo(before.get(original.keys()[2])); + for (String key : original.keys()) assertThat(admin.pttl(ascii(key))).isEqualTo(-1L); + } + private void assertPhysicalImage( ScriptCase original, Map expected, int keyCount) { for (int index = 0; index < keyCount; index++) { String key = original.keys()[index]; - if (expected.get(key) == null) assertThat(admin.dump(ascii(key))).as(key).isNull(); - else assertThat(admin.dump(ascii(key))).as(key).containsExactly(expected.get(key)); + assertThat( + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( + admin, ascii(key))) + .as(key) + .containsExactly(expected.get(key)); } } @@ -659,6 +715,14 @@ private static Map capacity(long expiresAt) { Map.entry("reservationId", UUID.randomUUID().toString()), Map.entry("reservationFence", "1"), Map.entry("capacityRearmFence", "1"), + Map.entry("mutationDigest", "a".repeat(64)), + Map.entry("expiresAt", java.time.Instant.ofEpochMilli(expiresAt).toString()), + Map.entry("snapshotIdentity", "sha256:" + "b".repeat(64)), + Map.entry("evaluationIdentity", "sha256:" + "c".repeat(64)), + Map.entry("candidateDigest", "sha256:" + "d".repeat(64)), + Map.entry( + "canonicalAttemptPayload", + Base64.getEncoder().encodeToString(ascii("controlled-attempt"))), Map.entry("selectedOwnerId", "controlled-owner"), Map.entry("selectedOwnerFence", "1"), Map.entry("transitionId", TRANSITION), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 12f0b0a2b3..22c9bb8860 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -330,6 +330,35 @@ void recreatedCapacityOwnerClosesExactAttemptAndRejectsDelayedFinalCas() throws .containsExactly(proof.canonicalReadback()); } + @Test + void transferFenceRejectsChangedCandidateDigestBeforeSubmittingRedis() throws Exception { + repairAccountMember(); + bridge(false); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var assignment = tags.assignmentForTransition(fixture.transitionId()); + var changed = + new net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution( + controlledCapacity.request(), + controlledCapacity.reservation(), + controlledCapacity.transitionId(), + "sha256:" + "0".repeat(64), + controlledCapacity.selectedOwnerId(), + controlledCapacity.selectedOwnerFence()); + String retained = sqlImage(); + Map physical = physicalImage(); + + assertThatThrownBy( + () -> + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + ownerClient, catalog, CLOCK, tags) + .fenceCapacityExecutionOnce( + changed, source.candidate(), assignment, deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(admin.type(ascii(capacityKey(assignment)))).isEqualTo("none"); + assertThat(sqlImage()).isEqualTo(retained); + assertThat(physicalImage()).isEqualTo(physical); + } + @Test void processStopAfterActualSqlAuthorizationBeforeRedisSendFencesUnknownAndActuallyHandsOff() throws Exception { @@ -337,13 +366,15 @@ void processStopAfterActualSqlAuthorizationBeforeRedisSendFencesUnknownAndActual bridge(false); var executionFile = directory.resolve("original-execution.json"); java.nio.file.Files.write(executionFile, controlledCapacity.canonicalBytes()); + String jdbcUrl = POSTGRES.getJdbcUrl(); + String schema = fixture.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); var process = new ProcessBuilder( Path.of(System.getProperty("java.home"), "bin", "java").toString(), "-cp", childClasspath(), StopAfterAuthorizationCommit.class.getName(), - POSTGRES.getJdbcUrl(), + jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=" + schema, POSTGRES.getUsername(), POSTGRES.getPassword(), executionFile.toString()) @@ -351,9 +382,9 @@ void processStopAfterActualSqlAuthorizationBeforeRedisSendFencesUnknownAndActual .start(); try { assertThat(process.waitFor(20, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); - assertThat(process.exitValue()).isEqualTo(72); - assertThat(new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8)) - .contains("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + assertThat(process.exitValue()).as("Child output: %s", output).isEqualTo(72); + assertThat(output).contains("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); } finally { if (process.isAlive()) { process.destroyForcibly(); @@ -2505,7 +2536,10 @@ private Map physicalImage() { for (byte[] key : admin.keys("session:game:*")) { image.put( new String(key, StandardCharsets.US_ASCII), - java.util.Base64.getEncoder().encodeToString(admin.dump(key))); + java.util.Base64.getEncoder() + .encodeToString( + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( + admin, key))); } return image; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.java new file mode 100644 index 0000000000..9a994988f0 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.api.sync.RedisCommands; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Map; + +/** Exact physical bytes without Redis DUMP's unspecified hash/set iteration order. */ +final class CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture { + private CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture() {} + + static byte[] image(RedisCommands commands, byte[] key) { + var output = new ByteArrayOutputStream(); + String type = commands.type(key); + append(output, type.getBytes(StandardCharsets.US_ASCII)); + long ttl = commands.pttl(key); + // Persistent/missing keys stay exact. Expiring fault fixtures retain a positive-TTL marker; + // their separate assertions check expiry without comparing a naturally decreasing duration. + append(output, Long.toString(ttl > 0 ? 1 : ttl).getBytes(StandardCharsets.US_ASCII)); + switch (type) { + case "none" -> {} + case "string" -> append(output, commands.get(key)); + case "hash" -> { + var fields = new ArrayList<>(commands.hgetall(key).entrySet()); + fields.sort((left, right) -> Arrays.compareUnsigned(left.getKey(), right.getKey())); + for (Map.Entry field : fields) { + append(output, field.getKey()); + append(output, field.getValue()); + } + } + case "set" -> { + var members = new ArrayList<>(commands.smembers(key)); + members.sort(Arrays::compareUnsigned); + for (byte[] member : members) append(output, member); + } + default -> + throw new IllegalStateException("Unexpected final-admission fixture key type: " + type); + } + return output.toByteArray(); + } + + private static void append(ByteArrayOutputStream output, byte[] value) { + output.writeBytes(Integer.toString(value.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(value); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index a96947e6dc..478c04c826 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -3,9 +3,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.lettuce.core.AclSetuserArgs; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Path; @@ -850,7 +853,7 @@ public void close() { * Actual SQL, candidate/issuer/region and capacity/transfer owners over physical PostgreSQL and * Redis. Account lease/reservation/OPEN, World/Entity RPC content, grant and attestor custody are * controlled inputs. This proves SQL serialization/retention, not Account issuance or activation. - * The Redis test connection is privileged; ACL qualification belongs to its separate owner proof. + * Owners use the required named Redis principal; ACL qualification belongs to separate proof. */ private final class TransferSqlProof implements AutoCloseable { private final Clock clock = Clock.systemUTC(); @@ -871,14 +874,50 @@ private final class TransferSqlProof implements AutoCloseable { private CanonicalGameplayRegionOwnerTransferCoordinator coordinator; private TransferSqlProof() throws Exception { + String password = UUID.randomUUID().toString(); + try (var administrator = + RedisClient.create(RedisURI.create(REDIS.getHost(), REDIS.getMappedPort(6379))); + var connection = administrator.connect(ByteArrayCodec.INSTANCE)) { + connection.sync().flushdb(); + connection + .sync() + .aclSetuser( + "gamesession_coord_app", + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:game:*") + .keyPattern("tick:*") + .keyPattern("tick-executor-lease:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.SADD) + .addCommand(CommandType.SISMEMBER) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HDEL) + .addCommand(CommandType.PEXPIRE) + .addCommand(CommandType.EXISTS) + .addCommand(CommandType.DEL) + .addCommand(CommandType.TIME)); + } redis = RedisClient.create( RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)) + .withAuthentication("gamesession_coord_app", password) .withTimeout(Duration.ofSeconds(5)) .build()); - try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) { - connection.sync().flushdb(); - } var dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(POSTGRES.getDriverClassName()); String url = POSTGRES.getJdbcUrl(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 832a475832..f257bb0539 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -926,12 +926,12 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip try (Fixture f = fixture(null)) { var original = f.owner().capture(request()); f.addComponent(); - for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 8, 10}) { + for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 11}) { assertThatThrownBy(() -> f.installEpoch(invalid)) .hasMessageContaining("exact classified installed schema"); } // Controlled explicit owner revision, not an exposed registry/runtime mutation API. - f.installEpoch(9); + f.installEpoch(10); assertThatThrownBy(() -> f.owner().capture(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().readExact(original.request())) @@ -939,9 +939,9 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip assertThat(f.evidence(original.request())) .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().capture(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(9); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(10); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count(EPOCHS)).isEqualTo(9); + assertThat(f.count(EPOCHS)).isEqualTo(10); } } From 09a606ec54dde1bf7ce6be0c5daac6dabd1511ee Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 05:17:23 +1300 Subject: [PATCH 23/52] Fix physical handoff fixture composition and Redis client policy Register region-lease scripts, preserve original incarnation source in Account handoff, and use the required no-reconnect Redis client. Focused proof: 111 unit cases, Game Session and Account integration source compilation, cross-service proof jar, formatting. Physical CI remains required. --- ...alNewFinalAdmissionCompositionFixture.java | 2 ++ ...NewFinalAdmissionOwnerIntegrationTest.java | 2 ++ ...GameplayRegionOwnerCompositionFixture.java | 23 ++++++++++++++++++- ...untimeStatusRepositoryIntegrationTest.java | 2 ++ 4 files changed, 28 insertions(+), 1 deletion(-) 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 c78787d4a7..bb4d8f52b0 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 @@ -740,6 +740,8 @@ public Candidate candidate() { scripts, regionInstallation, sources.resolver, + CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture + ::controlledRegionIncarnation, transfer, deadline); return reservation; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 22c9bb8860..62452a63a8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -137,6 +137,8 @@ void setUp() throws Exception { .CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution(), new net.firedevops.firemud.gamesession.service .CanonicalGameplayAccountMemberRepairRedisScriptContribution(), + new net.firedevops.firemud.gamesession.service + .CanonicalGameplayRegionLeaseRedisScriptContribution(), new net.firedevops.firemud.gamesession.service .CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())); // Allocate test PKI and start controlled source servers before the short lease starts. 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 93f7ec8a0d..7e0b0de3ff 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 @@ -129,6 +129,27 @@ static CanonicalGameplayRegionLeaseOwner.Installation handoffExistingOriginal( CanonicalInitialPlayerLocationRegionResolver resolver, CanonicalGameplayRegionOwnerTransferCoordinator transfer, long deadline) { + return handoffExistingOriginal( + dsl, + coordinationRedis, + catalog, + original, + resolver, + new ControlledStableIncarnationSource(), + transfer, + deadline); + } + + /** Rechecks the same explicit current incarnation source used by the original installation. */ + static CanonicalGameplayRegionLeaseOwner.Installation handoffExistingOriginal( + DSLContext dsl, + RedisClient coordinationRedis, + RedisScriptCatalog catalog, + CanonicalGameplayRegionLeaseOwner.Installation original, + CanonicalInitialPlayerLocationRegionResolver resolver, + CanonicalGameplayRegionIncarnationSource incarnationSource, + CanonicalGameplayRegionOwnerTransferCoordinator transfer, + long deadline) { var identity = new RuntimeIdentity( "game-session-service", @@ -143,7 +164,7 @@ static CanonicalGameplayRegionLeaseOwner.Installation handoffExistingOriginal( dsl, coordinationRedis, catalog, - new ControlledStableIncarnationSource(), + incarnationSource, resolver, identity, Duration.ofSeconds(30), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 478c04c826..2bfe78fb24 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.codec.ByteArrayCodec; @@ -918,6 +919,7 @@ private TransferSqlProof() throws Exception { .withAuthentication("gamesession_coord_app", password) .withTimeout(Duration.ofSeconds(5)) .build()); + redis.setOptions(ClientOptions.builder().autoReconnect(false).build()); var dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(POSTGRES.getDriverClassName()); String url = POSTGRES.getJdbcUrl(); From be71dd4fa368001e71933a86c80b8901da7ec040 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 06:31:04 +1300 Subject: [PATCH 24/52] fix(capacity): preserve terminal handoff and exact recovery claims Keep ordinary provisional transfers separate from committed final-proof revalidation. Reuse the real-clock recovery worker and strengthen physical fixtures. 126 focused unit cases and integration compilation passed; replacement physical CI remains required. --- ...alAdmissionCompositionIntegrationTest.java | 25 +++- ...calGameplayBindingInventoryRepository.java | 127 ++++++++++++++++++ .../CanonicalGameplayRegionLeaseOwner.java | 37 ++++- ...NewFinalAdmissionOwnerIntegrationTest.java | 62 +++++++++ 4 files changed, 241 insertions(+), 10 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 1387ba3db7..1e0e6bfd17 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -231,13 +231,10 @@ void actualNormalHandoffKeepsUnknownCapacityHeldAndBoundedRecoveryQuarantinesSam session.capacityRequest, reservation, CLOCK.instant().plusSeconds(5))) .isInstanceOf(RuntimeException.class); TenantCapacityAdmission.Result result = reservation; + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + session.capacityOwner, session.dsl, session.capacityRead, CLOCK); for (int attempt = 0; attempt < 12; attempt++) { - var recovery = - new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( - session.capacityOwner, - session.dsl, - session.capacityRead, - Clock.offset(CLOCK, Duration.ofSeconds(attempt * 20L))); result = recovery.reconcile( session.capacityRequest, @@ -246,9 +243,25 @@ void actualNormalHandoffKeepsUnknownCapacityHeldAndBoundedRecoveryQuarantinesSam assertThat(result.reservationId()).isEqualTo(reservation.reservationId()); assertThat(result.reservationFence()).isEqualTo(reservation.reservationFence()); assertThat(result.admissionAttemptId()).isEqualTo(reservation.admissionAttemptId()); + assertThat(result.identity()).isEqualTo(reservation.identity()); + assertThat(result.capacityRearmFence()).isEqualTo(reservation.capacityRearmFence()); } assertThat(result.state()) .isEqualTo(TenantCapacityAdmission.State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); + var retainedRecovery = + session.dsl.fetchSingle( + "SELECT recovery_attempt_count, recovery_claim_fence FROM account_tenant_capacity_reservations WHERE reservation_id=?", + reservation.reservationId()); + assertThat(retainedRecovery.get("recovery_attempt_count", Integer.class)).isEqualTo(12); + assertThat(retainedRecovery.get("recovery_claim_fence", Long.class)).isEqualTo(12L); + assertThat( + session + .dsl + .fetchSingle( + "SELECT count(*) FROM account_tenant_capacity_recovery_evidence WHERE admission_attempt_id=?", + reservation.admissionAttemptId()) + .get(0, Long.class)) + .isEqualTo(12L); var usage = session.dsl.fetchSingle( "SELECT held_units,used_units FROM account_tenant_capacity_usage WHERE tenant_uuid=? AND owner_service='game-session-service'", 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 c3ceb824b0..9c8b466efe 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 @@ -1044,6 +1044,133 @@ OriginalNewFinalAdmissionSource readOriginalNewFinalAdmissionSource( }); } + /** Pins original identity only; ordinary provisional handoff needs no final ACK capability. */ + CanonicalGameplayOriginalNewCandidate readRegionTransferOriginalCandidate( + UUID transitionId, CanonicalGameplayBindingProvisionalCasEvidence expectedOriginal) { + requireNoAmbientTransaction(); + Objects.requireNonNull(expectedOriginal, "expected original placement"); + if (!expectedOriginal.transition().transitionId().equals(transitionId) + || expectedOriginal.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || expectedOriginal.expectedPrior() != null) { + throw conflict("Region transfer requires its exact original provisional placement"); + } + CanonicalGameplayAdmissionDecision decision = + dsl.transactionResult( + configuration -> + toAdmissionDecision( + readTransition(DSL.using(configuration), transitionId), expectedOriginal)); + return CanonicalGameplayOriginalNewCandidate.fromOriginalSources(expectedOriginal, decision); + } + + /** Only an explicitly observed COMMITTED original selects the strict terminal source path. */ + Optional readRegionTransferCommittedSource( + UUID transitionId, CanonicalGameplayOriginalNewCandidate expectedOriginal) { + requireNoAmbientTransaction(); + Objects.requireNonNull(expectedOriginal, "pinned original transfer candidate"); + if (!expectedOriginal.bindingDecisionId().equals(transitionId)) { + throw conflict("Region transfer changed its original transition"); + } + boolean committed = + dsl.transactionResult( + configuration -> { + var transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record row = readTransition(transaction, transitionId); + if (row == null) throw conflict("Region transfer original transition is missing"); + String status = row.get("status", String.class); + if ("COMMITTED".equals(status)) return true; + if (!"PROVISIONAL".equals(status)) { + throw conflict("Region transfer original has no current installation lifecycle"); + } + var provisional = loadProvisionalCasEvidence(transaction, transitionId, false); + var decision = toAdmissionDecision(row, provisional); + if (!expectedOriginal.equals( + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + provisional, decision))) { + throw conflict( + "Region transfer original differs from its current provisional source"); + } + return false; + }); + if (!committed) return Optional.empty(); + var decision = + new CanonicalGameplayAdmissionDecision( + transitionId, + expectedOriginal.leaseEvidence(), + expectedOriginal.bindingIdentity(), + expectedOriginal.transition().bindingGeneration(), + null, + expectedOriginal.targetEvidence()); + var current = readOriginalNewFinalAdmissionSource(decision); + if (current.transitionStatus() != CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED + || !expectedOriginal.equals(current.candidate())) { + throw conflict("Region transfer committed source differs from the pinned original"); + } + return Optional.of(current); + } + + /** Revalidates actual final lifecycle/receipts; never presents COMMITTED as provisional work. */ + OriginalNewFinalAdmissionSource readRegionTransferOriginalSource( + UUID transitionId, OriginalNewFinalAdmissionSource expectedOriginal) { + requireNoAmbientTransaction(); + Objects.requireNonNull(expectedOriginal, "pinned original transfer source"); + var candidate = expectedOriginal.candidate(); + if (!candidate.bindingDecisionId().equals(transitionId)) { + throw conflict("Region transfer changed its original transition"); + } + var decision = + new CanonicalGameplayAdmissionDecision( + transitionId, + candidate.leaseEvidence(), + candidate.bindingIdentity(), + candidate.transition().bindingGeneration(), + null, + candidate.targetEvidence()); + var current = readOriginalNewFinalAdmissionSource(decision); + if (!candidate.equals(current.candidate()) + || !expectedOriginal.candidateDigest().equals(current.candidateDigest()) + || !expectedOriginal + .originalCandidateReadbackDigest() + .equals(current.originalCandidateReadbackDigest()) + || !regionTransferAcknowledgementFields(expectedOriginal.regionAcknowledgement()) + .equals(regionTransferAcknowledgementFields(current.regionAcknowledgement())) + || !Arrays.equals( + expectedOriginal.issuerAcknowledgement().exactBytes(), + current.issuerAcknowledgement().exactBytes()) + || (expectedOriginal.finalReceipt().isPresent() + && !expectedOriginal.finalReceipt().equals(current.finalReceipt()))) { + throw conflict("Region transfer original or retained final proof changed"); + } + return current; + } + + private static List regionTransferAcknowledgementFields( + CanonicalGameplayBindingRegionBridgeObligation acknowledgement) { + // The strict source reader separately binds controller identity and current inventory revision. + // Final SQL retention advances that revision, but none of the original ACK proof may change. + return Arrays.asList( + acknowledgement.bridgeOperationId(), + acknowledgement.bridgePreimageState(), + acknowledgement.runtimeEntityId(), + acknowledgement.entityProjectionGeneration(), + acknowledgement.entityProjectionFence(), + acknowledgement.entityWorkloadNamespace(), + acknowledgement.actorOrigin(), + acknowledgement.entityReferenceDigest(), + acknowledgement.worldSourceDigest(), + acknowledgement.canonicalRegionId(), + acknowledgement.worldLifecycleEpoch(), + acknowledgement.worldLifecycleRowVersion(), + acknowledgement.worldCaptureId(), + acknowledgement.worldGraphSha256(), + acknowledgement.worldPreparationInputDigest(), + acknowledgement.executorFence(), + acknowledgement.leaseTokenCorrelation(), + acknowledgement.redisReadbackDigest(), + acknowledgement.acknowledgedAt()); + } + void requireSameProvisionalSource( CanonicalGameplayBindingProvisionalCasEvidence expected, CanonicalGameplayBindingProvisionalCasEvidence current) { 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 d049f4df3d..cf6347055c 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 @@ -10,6 +10,7 @@ import java.util.UUID; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayActorOrigins; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; @@ -99,6 +100,8 @@ Installation installForTransition( if (prior == null && expectedRegionEpoch != 1L) throw unavailable(); if (prior != null && prior.regionEpoch() != expectedRegionEpoch) throw unavailable(); UUID transferId = null; + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource = + null; CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; @@ -209,7 +212,15 @@ Installation installForTransition( if (transferOwner.alreadyCompleted( prior, runtimeIdentity.serviceInstanceId(), absoluteDeadlineMillis)) throw unavailable(); + var transferCandidate = + bindingInventory.readRegionTransferOriginalCandidate(transitionId, evidence); transferId = transferOwner.advance(source, prior, absoluteDeadlineMillis); + // Advance may retain a COMMITTED winner and activate its SQL inventory row. Keep that + // exact terminal source separate from provisional binding/bridge authority. + transferSource = + bindingInventory + .readRegionTransferCommittedSource(transitionId, transferCandidate) + .orElse(null); } grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); } else { @@ -226,7 +237,7 @@ Installation installForTransition( redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); } CanonicalGameplayRegionRuntimeStatusRepository.Source afterAcquire = - resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); + resolveCurrentInstallationSource(worldRequest, evidence, transferSource); requireSameSource(source, afterAcquire); redisOwner.renew(grant, leaseTtl); redisOwner.requireCurrent(grant); @@ -259,7 +270,7 @@ Installation installForTransition( statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!installed.equals(observed) || observed.paused()) throw unavailable(); CanonicalGameplayRegionRuntimeStatusRepository.Source afterInstall = - resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); + resolveCurrentInstallationSource(worldRequest, evidence, transferSource); requireSameSource(source, afterInstall); redisOwner.requireCurrent(grant); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); @@ -269,7 +280,7 @@ Installation installForTransition( redisOwner.verifyInitializedTimeline(grant, preparation); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); requireSameSource( - source, resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId))); + source, resolveCurrentInstallationSource(worldRequest, evidence, transferSource)); CanonicalGameplayRegionRuntimeStatus finalStatus = statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!installed.equals(finalStatus) || finalStatus.paused()) throw unavailable(); @@ -704,11 +715,29 @@ private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveExactSource return resolveExactBridgeSource(request, evidence).source; } + private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveCurrentInstallationSource( + CanonicalInitialPlayerLocationRequest request, + CanonicalGameplayBindingProvisionalCasEvidence original, + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource) { + if (transferSource == null) { + return resolveExactSource( + request, readCurrentProvisionalEvidence(original.transition().transitionId())); + } + var current = + bindingInventory.readRegionTransferOriginalSource( + original.transition().transitionId(), transferSource); + return resolveExactBridgeSource(request, current.candidate().bindingIdentity()).source; + } + private ResolvedBridgeSource resolveExactBridgeSource( CanonicalInitialPlayerLocationRequest request, CanonicalGameplayBindingProvisionalCasEvidence evidence) { + return resolveExactBridgeSource(request, evidence.candidate().identity()); + } + + private ResolvedBridgeSource resolveExactBridgeSource( + CanonicalInitialPlayerLocationRequest request, CanonicalGameplayBindingIdentity identity) { requireNoAmbientTransaction(); - var identity = evidence.candidate().identity(); var target = request.getExpectedTarget(); if (!identity.accountId().toString().equals(request.getCanonicalAccountUuid()) || !identity.characterId().toString().equals(request.getCharacterUuid()) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 62452a63a8..02b503570f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -607,6 +607,47 @@ void correctlySignedDifferentStorageGenerationCannotAdoptRetainedTransferReceipt .isEqualTo(original.status.executorFence()); } + @Test + void ordinaryProvisionalHandoffWithoutCapacityExecutionNeedsNoFinalAcknowledgements() + throws Exception { + regionBinding = + CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( + fixture.dsl(), + ownerClient, + fixture.transitionId(), + sources.request, + sources.resolver, + sources.entity); + var original = regionBinding.installation(); + var before = inventory.readProvisionalCasEvidence(fixture.transitionId()); + assertThat(before.candidate().accountIndexState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry + .IndexState.REPAIR_REQUIRED); + assertThatThrownBy(() -> inventory.readOriginalNewFinalAdmissionSource(decision)) + .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM game_session_original_new_capacity_execution") + .get(0, Long.class)) + .isZero(); + + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); + + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(inventory.readProvisionalCasEvidence(fixture.transitionId())).isEqualTo(before); + assertThatThrownBy(() -> inventory.readOriginalNewFinalAdmissionSource(decision)) + .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM game_session_region_owner_transfer") + .get(0, Long.class)) + .isZero(); + } + @Test void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff() throws Exception { @@ -638,6 +679,7 @@ void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff( .get(0, String.class)) .isNull(); var original = regionBinding.installation(); + var pinned = source; admin.pexpire(ascii(original.grant.key()), 0); var successor = actualTransferHandoff(); assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); @@ -655,6 +697,26 @@ void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff( .disposition()) .isEqualTo("COMMITTED"); assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); + var retained = inventory.readRegionTransferOriginalSource(fixture.transitionId(), pinned); + assertThat(retained.transitionStatus()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED); + assertThat(retained.candidate()).isEqualTo(pinned.candidate()); + assertThat(retained.finalReceipt().orElseThrow().finalSessionSha256()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution.sha256( + committed)); + assertThat( + inventory + .readRegionTransferOriginalSource(fixture.transitionId(), retained) + .finalReceipt()) + .isEqualTo(retained.finalReceipt()); + assertThatThrownBy(() -> inventory.readProvisionalCasEvidence(fixture.transitionId())) + .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("A first binding cannot proceed while an active controller exists"); + assertThatThrownBy( + () -> inventory.readRegionTransferOriginalSource(UUID.randomUUID(), retained)) + .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("Region transfer changed its original transition"); } @Test From f53cfd48a1399cebbee50134a33010f0bf04612c Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 07:31:31 +1300 Subject: [PATCH 25/52] test(capacity): isolate connector saturation and resource cleanup Use synchronized dedicated callers and four distinct late resources. Retain actual deadlines, exact connector cap/no-queue rejection and one disposal per resource without masking primary failures in cleanup. Production behavior unchanged. Focused22 cases and two5-case reruns passed; exact-head CI remains required before descendant carry. --- ...nalNewCapacityExecutionConnectionTest.java | 79 +++++++++++++++---- 1 file changed, 65 insertions(+), 14 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java index f3a83c8b4c..1632004fa0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionConnectionTest.java @@ -108,13 +108,20 @@ void expiredCallDoesNotWaitForConnectionAndDisposesTheLateConnection() throws Ex void nonInterruptibleConnectsSaturateFourSharedSlotsWithoutQueuingAnotherAttempt() throws Exception { RedisClient redis = mock(); - StatefulRedisConnection late = mock(); - when(late.closeAsync()).thenReturn(CompletableFuture.completedFuture(null)); int maximum = CanonicalGameplayOriginalNewCapacityExecutionOwner.MAX_IN_FLIGHT_CONNECTS; + var lateConnections = new java.util.ArrayList>(); + for (int index = 0; index < maximum; index++) { + StatefulRedisConnection late = mock(); + when(late.closeAsync()).thenReturn(CompletableFuture.completedFuture(null)); + lateConnections.add(late); + } + var nextConnection = new java.util.concurrent.atomic.AtomicInteger(); + CountDownLatch ready = new CountDownLatch(maximum), start = new CountDownLatch(1); CountDownLatch entered = new CountDownLatch(maximum), release = new CountDownLatch(1); when(redis.connect(ByteArrayCodec.INSTANCE)) .thenAnswer( invocation -> { + var late = lateConnections.get(nextConnection.getAndIncrement()); entered.countDown(); for (; ; ) { try { @@ -126,32 +133,76 @@ void nonInterruptibleConnectsSaturateFourSharedSlotsWithoutQueuingAnotherAttempt } return late; }); + ThreadPoolExecutor connectors = + (ThreadPoolExecutor) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionOwner.class, "CONNECTS")); + Semaphore permits = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, "OPERATIONS")); + int operationMaximum = + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_IN_FLIGHT_OPERATIONS; + long completedBefore = connectors.getCompletedTaskCount(); var owner = owner(mock(), redis, mock()); var scheduler = Executors.newSingleThreadScheduledExecutor(); - var callers = new java.util.ArrayList>(); + var callerThreads = Executors.newFixedThreadPool(maximum); + var callers = new java.util.ArrayList>(); try { for (int index = 0; index < maximum; index++) callers.add( - CompletableFuture.runAsync( + callerThreads.submit( () -> { - assertThatThrownBy( - () -> - Context.current() - .withDeadlineAfter(200, TimeUnit.MILLISECONDS, scheduler) - .call(owner::connectForRead)) - .isInstanceOf(IllegalStateException.class); + ready.countDown(); + start.await(); + // Construct deadlines only after all dedicated callers are ready. Common-pool + // startup and mock preparation must not consume the controlled deadline. + try (var context = + Context.current().withDeadlineAfter(1, TimeUnit.SECONDS, scheduler)) { + assertThatThrownBy(() -> context.call(owner::connectForRead)) + .isInstanceOf(IllegalStateException.class); + } + return null; })); + assertThat(ready.await(2, TimeUnit.SECONDS)).isTrue(); + start.countDown(); assertThat(entered.await(2, TimeUnit.SECONDS)).isTrue(); - CompletableFuture.allOf(callers.toArray(CompletableFuture[]::new)).get(2, TimeUnit.SECONDS); - // All four call deadlines have returned, but their blocked connects still occupy the cap. + for (var caller : callers) caller.get(3, TimeUnit.SECONDS); + // Caller return can precede resource-worker abandonment. Prove operation permits have + // recovered before testing connector saturation, so that the fifth refusal cannot be + // explained by the independent operation cap. + Awaitility.await() + .atMost(2, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(permits.availablePermits()).isEqualTo(operationMaximum)); + assertThat(connectors.getActiveCount()).isEqualTo(maximum); + assertThat(connectors.getQueue()).isEmpty(); + assertThat(connectors.getTaskCount()).isEqualTo(completedBefore + maximum); assertThatThrownBy(owner::connectForRead).isInstanceOf(IllegalStateException.class); verify(redis, org.mockito.Mockito.times(maximum)).connect(ByteArrayCodec.INSTANCE); - verifyNoInteractions(late); + assertThat(connectors.getActiveCount()).isEqualTo(maximum); + assertThat(connectors.getQueue()).isEmpty(); + assertThat(connectors.getTaskCount()).isEqualTo(completedBefore + maximum); + lateConnections.forEach(org.mockito.Mockito::verifyNoInteractions); } finally { + // Cleanup never verifies: a failed barrier/deadline assertion must remain the primary error. + start.countDown(); release.countDown(); scheduler.shutdownNow(); - verify(late, timeout(2000).times(maximum)).closeAsync(); + callerThreads.shutdownNow(); } + Awaitility.await() + .atMost(2, TimeUnit.SECONDS) + .untilAsserted( + () -> { + assertThat(connectors.getActiveCount()).isZero(); + assertThat(connectors.getQueue()).isEmpty(); + assertThat(connectors.getCompletedTaskCount()).isEqualTo(completedBefore + maximum); + }); + for (var late : lateConnections) verify(late).closeAsync(); + assertThat(permits.availablePermits()).isEqualTo(operationMaximum); + assertThat(callerThreads.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } @Test From fe30e5a04957d3d75800aea29dd087c976a7a618 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 08:13:04 +1300 Subject: [PATCH 26/52] Retain explicit SpotBugs XML diagnostics for failed validation --- .../actions/check-gradle-module/action.yml | 9 ++++++ build.gradle.kts | 3 ++ .../tests/ci-lightweight-scope-contract.sh | 32 +++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/.github/actions/check-gradle-module/action.yml b/.github/actions/check-gradle-module/action.yml index c74002b107..c0bcb78827 100644 --- a/.github/actions/check-gradle-module/action.yml +++ b/.github/actions/check-gradle-module/action.yml @@ -102,6 +102,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 63e88cd1d0..1bdbe0ae08 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -350,6 +350,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/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index b5f0621ab4..63d0a172f6 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -679,6 +679,30 @@ require_equal( "ci workflow", ) +spotbugs_reports_step = find_step( + module_ci, "build-and-test", "Upload SpotBugs Reports if Failed", "ci workflow" +) +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" ) @@ -1306,6 +1330,14 @@ require_equal( gradle_build = Path(sys.argv[6]).read_text(encoding="utf-8") root_configuration, subproject_configuration = gradle_build.split("subprojects {", 1) +spotbugs_xml_report = re.search( + r'tasks\.withType\(\)\.configureEach\s*\{\s*' + r'enabled = fullCheck\s*reports\.create\("xml"\)\s*\{\s*' + r'required\.set\(true\)\s*\}', + re.sub(r"//[^\n]*", "", subproject_configuration), +) +if spotbugs_xml_report is None: + 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" ) From fa8be621332c5f62d66e14dd852a7b0506142f51 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 08:39:43 +1300 Subject: [PATCH 27/52] Clarify binary varargs and JDBC ownership in admission tests --- ...alNewFinalAdmissionLuaIntegrationTest.java | 6 +- ...NewFinalAdmissionOwnerIntegrationTest.java | 76 +++++++++++-------- 2 files changed, 50 insertions(+), 32 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java index 8b7f1d6c60..1c5efd647e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java @@ -463,7 +463,8 @@ void fenceRefusesWrongTypeTtlIdentityAndEveryUnexpectedPhysicalShapeWithoutMutat byte[] key = ascii(original.keys()[6]); switch (fault) { case "type" -> { - admin.del(new byte[][] {key}); + byte[][] keysToDelete = {key}; + admin.del(keysToDelete); admin.set(key, ascii("foreign-type")); } case "ttl" -> admin.pexpire(key, 60_000L); @@ -584,7 +585,8 @@ void physicalImagePreservesRawHashFieldsValuesAndSetMembersIndependentOfIteratio .isNotEqualTo(before.get(original.keys()[4])); admin.hdel(hash, new byte[] {0, (byte) 0xff, 2}); admin.hset(hash, field, value); - admin.sadd(ascii(original.keys()[2]), value); + byte[][] membersToAdd = {value}; + admin.sadd(ascii(original.keys()[2]), membersToAdd); assertThat(physicalImage(original).get(original.keys()[2])) .isNotEqualTo(before.get(original.keys()[2])); for (String key : original.keys()) assertThat(admin.pttl(ascii(key))).isEqualTo(-1L); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 02b503570f..7e6a22c769 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -541,7 +541,8 @@ private void retainedTransferTamperBlocks(String fault) throws Exception { byte[] key = ascii(capacityKey(tags.assignmentForTransition(fixture.transitionId()))); if (fault.equals("ttl")) admin.pexpire(key, 10000); else if (fault.equals("type")) { - admin.del(key); + byte[][] keysToDelete = {key}; + admin.del(keysToDelete); admin.set(key, ascii("wrong-type")); } else admin.hset(key, ascii("binding"), ascii("{}")); byte[] physical = admin.dump(key); @@ -958,6 +959,49 @@ private static StatefulRedisConnection delayedConnection( public static final class StopAfterAuthorizationCommit { private StopAfterAuthorizationCommit() {} + // The returned proxy owns actual: close delegates to it, including normal jOOQ cleanup. + private static java.sql.Connection stopAfterCommit( + java.sql.Connection actual, javax.sql.DataSource raw, String executionDigest) + throws java.sql.SQLException { + try { + return (java.sql.Connection) + java.lang.reflect.Proxy.newProxyInstance( + java.sql.Connection.class.getClassLoader(), + new Class[] {java.sql.Connection.class}, + (proxy, method, values) -> { + Object result; + try { + result = method.invoke(actual, values); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + if (method.getName().equals("commit")) { + try (var independent = raw.getConnection(); + var check = + independent.prepareStatement( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?")) { + check.setString(1, executionDigest); + try (var rows = check.executeQuery()) { + if (rows.next() && "INSTALL_DISPATCHED".equals(rows.getString(1))) { + System.out.println("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); + System.out.flush(); + Runtime.getRuntime().halt(72); + } + } + } + } + return result; + }); + } catch (RuntimeException | Error failure) { + try { + actual.close(); + } catch (java.sql.SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; + } + } + public static void main(String[] args) throws Exception { var raw = new DriverManagerDataSource(args[0], args[1], args[2]); var execution = @@ -967,35 +1011,7 @@ public static void main(String[] args) throws Exception { new org.springframework.jdbc.datasource.DelegatingDataSource(raw) { @Override public java.sql.Connection getConnection() throws java.sql.SQLException { - var actual = raw.getConnection(); - return (java.sql.Connection) - java.lang.reflect.Proxy.newProxyInstance( - java.sql.Connection.class.getClassLoader(), - new Class[] {java.sql.Connection.class}, - (proxy, method, values) -> { - Object result; - try { - result = method.invoke(actual, values); - } catch (java.lang.reflect.InvocationTargetException failure) { - throw failure.getCause(); - } - if (method.getName().equals("commit")) { - try (var independent = raw.getConnection(); - var check = - independent.prepareStatement( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?")) { - check.setString(1, execution.digest()); - try (var rows = check.executeQuery()) { - if (rows.next() && "INSTALL_DISPATCHED".equals(rows.getString(1))) { - System.out.println("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); - System.out.flush(); - Runtime.getRuntime().halt(72); - } - } - } - } - return result; - }); + return stopAfterCommit(raw.getConnection(), raw, execution.digest()); } }; var sql = org.jooq.impl.DSL.using(stopping, org.jooq.SQLDialect.POSTGRES); From 36a6d22e50440115a20bf4478e8d7273b3596328 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 11:18:53 +1300 Subject: [PATCH 28/52] Fix capacity recovery deadlines and independent admission proofs --- .../game-session-service/runtime-and-data.md | 6 +- .../player-access-and-session.md | 2 +- .../AccountTenantCapacityRecoveryWorker.java | 12 +- ...tionCompletionPostgresIntegrationTest.java | 167 +++++++++++++++- .../capacity/CapacityAdmissionDigestTest.java | 104 ++++++++++ .../capacity-admission-v1-vectors.json | 41 +++- .../test_capacity_admission_vectors.py | 45 ++++- .../TenantCapacityAdmissionGrpcCodec.java | 7 +- .../TenantCapacityAdmissionGrpcCodecTest.java | 15 ++ ...calGameplayBindingInventoryRepository.java | 12 ++ ...layOriginalNewCapacityExecutionBudget.java | 38 +++- ...playOriginalNewCapacityExecutionOwner.java | 9 +- .../CanonicalGameplayRegionLeaseOwner.java | 101 ++++++++-- ...GameplayRegionOwnerTransferRepository.java | 2 +- ...NewFinalAdmissionOwnerIntegrationTest.java | 154 +++++++++++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 15 +- ...ayOriginalNewAuthenticatedSessionTest.java | 4 +- ...riginalNewCapacityExecutionBudgetTest.java | 184 +++++++++++++++++- ...nOwnerTransferObservationReceiverTest.java | 2 + 19 files changed, 869 insertions(+), 51 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index d44bffd885..ac117d27ed 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,13 +10,13 @@ The finalized schema-2 reader requires `capacityExecutionDigest`; predecessor fi Positive SQL terminal retention follows actual persistent session/index/atomic-outcome and final-receipt verification. That retained result survives later serving-index retirement. Retained negative replay requires the already-verified immutable SQL CLOSED proof, full original identity, exact persistent Redis CLOSED tombstone, absence of contradictory final SQL receipt/state and a fresh actual current-owner observation. Serving-index absence is never negative evidence. Missing tombstones and closure before SQL proof retention remain indeterminate. The credential-free owner-local continuation independently verifies an already-committed tenant-slot effect and persists any missing final SQL receipt before retaining terminal evidence. The existing original-attempt closure entry point invokes that positive reconciliation before refusing negative closure; it does not need the original LOGIN, credential, live grant or fresh OPEN barriers, and it never dispatches a new final effect. Serving retirement must wait for retained positive evidence or independently retained exact closure. Capacity authorization locks and checks the durable region owner before creating dispatch custody; ordinary owner replacement takes that same lock and refuses unresolved installation or authorization unless the normal-handoff evidence below is complete. Lease expiry alone never satisfies this gate. The coordinator revalidates its grant immediately before final dispatch and preserves verified positive receipt/retention before a later currentness failure can withhold success. The existing never-admitted cleanup owner accepts only untouched PREPARED dispatches; cleanup of this already-acknowledged PROVISIONAL final-admission boundary and finalized-usage retirement on real runtime teardown remain separate unfinished Account/owner work. No default owner, receiver, recovery scheduler or source custody is registered by this slice. -The capacity execution owner uses one absolute budget for each complete operation: the earlier incoming gRPC or explicit coordinator deadline, capped at five seconds. Its local SQL connection provider and transaction provider derive from the existing configuration without changing shared datasource settings. Four resource operations are admitted without a waiting queue. Acquisition, SQL and cleanup stay in the admitted worker; cancellation requests the active JDBC statement's cancellation, while a late acquisition cannot execute SQL. Statement close and pool return detach the statement under the same monitor as cancellation. A blocked driver cancellation or acquisition retains its admission slot until it exits. A throwing pool return preserves uncertain connection ownership and retains the slot rather than blindly retrying or claiming disposal. The JVM-wide Micrometer gauge `original_new_capacity_sql_release_failure_retained_operations`, exposed through the existing Prometheus actuator path, counts retained operation slots once per affected operation, even if several connections fail to return. A nonzero value identifies lost local admission capacity; four retained slots exhaust this SQL boundary. Investigate the provider failure before a controlled process restart. Restart recovers local admission slots only and supplies no reservation or selected-owner outcome proof. JDBC query timeouts back up cancellation; neither cancellation nor deadline return proves driver termination or an owner outcome. The separate four-slot Redis connector, scoped capacity INSTALL/CLOSE writes and all successive Redis commands consume the same remaining operation budget. INSTALL and the first CLOSE mutation carry that operation's frozen absolute deadline, enforced by Redis time; completed CLOSE replay remains read-only. Other final-admission callers retain their existing connection and command policy. +The capacity execution owner uses one absolute budget for each complete operation: the earlier incoming gRPC or explicit coordinator deadline, capped at five seconds. Its local SQL connection provider and transaction provider derive from the existing configuration without changing shared datasource settings. Four resource operations are admitted without a waiting queue. Public Account recovery reads and transfer operations share a two-operation sublimit inside that same four-operation ceiling, preserving two slots for final admission even when background work is saturated. Both limits remain held until the admitted resource and cancellation workers finish; uncertain release retains both permits. Acquisition, SQL and cleanup stay in the admitted worker; cancellation requests the active JDBC statement's cancellation, while a late acquisition cannot execute SQL. Statement close and pool return detach the statement under the same monitor as cancellation. A blocked driver cancellation or acquisition retains its admission slot until it exits. A throwing pool return preserves uncertain connection ownership and retains the slot rather than blindly retrying or claiming disposal. The JVM-wide Micrometer gauge `original_new_capacity_sql_release_failure_retained_operations`, exposed through the existing Prometheus actuator path, counts retained operation slots once per affected operation, even if several connections fail to return. A nonzero value identifies lost local admission capacity; four retained slots exhaust this SQL boundary. Investigate the provider failure before a controlled process restart. Restart recovers local admission slots only and supplies no reservation or selected-owner outcome proof. JDBC query timeouts back up cancellation; neither cancellation nor deadline return proves driver termination or an owner outcome. The separate four-slot Redis connector, scoped capacity INSTALL/CLOSE writes and all successive Redis commands consume the same remaining operation budget. INSTALL and the first CLOSE mutation carry that operation's frozen absolute deadline, enforced by Redis time; completed CLOSE replay remains read-only. Other final-admission callers retain their existing connection and command policy. ### Normal-handoff future-execution fencing Game Session may exclude an unresolved original from future execution while its historical outcome remains indeterminate. This normal-handoff operation is separate from original-attempt closure, reservation recovery and cleanup. Its permanent tenant-slot `FENCED_INDETERMINATE` hash contains only the exact retained execution binding, digest and denying state. It may be created when the execution key is absent or replace the state of an exact persistent `AUTHORIZED` hash; neither action establishes that an earlier effect did not happen. The existing `INSTALL`, `FINAL` and `CLOSE` arms, including the predecessor script, reject that state. It never creates an authorization, session candidate, session or index, and supplies no `NOT_EXECUTED_AFTER_AUTHORIZATION` evidence. The Account reservation, original attempt/fence and complete capacity hold remain pending or quarantined under Account's existing recovery policy. -Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The frozen generation refuses new dispatch markers, including through the database guard. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. +After the ordinary timeline/incarnation qualification and lost-completion checks, the contender must acquire the successor Redis grant before freezing the current generation. A still-renewing incumbent therefore rejects the contender without transfer or execution-fence mutation. Before freezing, the contender rechecks the exact source, protected incarnation, initialized timeline and current grant; after fencing it renews and revalidates the grant before protected installation. Grant acquisition does not replace the transfer proof. The handoff freezes one absolute deadline before inventory selection, capped at five seconds and the incoming deadline. Initial provisional/candidate selection, exact committed-source selection and every later installation source revalidation use that same deadline and the original inventory provider through the existing bounded resource worker. Each scoped SQL context owns its derived connection and transaction provider; blocked acquisition, query cancellation and uncertain release retain their existing custody rules. An expired read cannot authorize successor installation. Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The frozen generation refuses new dispatch markers, including through the database guard. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. The protected receiver has a separate `REGION_OWNER_TRANSFER` purpose and signed schema. Its actual SQL source binds the frozen transfer, original execution, immutable tenant-tag assignment and complete protected deployment/registry/ACL/configuration/storage/AOF identity. Nonce, signature, exact carrier, time and two-source-read checks apply to each observation. Before and after fencing, and around a complete streamed physical verification before owner installation, fresh purpose-correct observations must agree with the transfer's retained incarnation. Historical SQL receipts alone cannot qualify a missing marker or a changed, unavailable, reset, restored or rolled-back store. Verification never recreates a previously retained missing fence. An inventory which cannot be completely re-read within the operation deadline remains frozen rather than dropping the currentness requirement. Normal handoff does not authorize adoption across storage loss; the owning reset/recovery qualification remains required. @@ -102,7 +102,7 @@ Game Session's runtime-family catalog is a manually composed **LOCAL SQL** sourc The catalog seals the actual current Game Session PostgreSQL schema, not a historical union of `CREATE TABLE` statements, a prefix exclusion or a static expected-table response. Every installed table, including empty tables, requires an explicit family disposition; named mixed components additionally bind their actual columns. Sorted definition digests cover tables, columns, constraints, indexes, triggers, routines, sequences, views, types, policies and rules, alongside the actual configured Flyway history. View and materialized-view facts bind both the query definition and relation options, including security-invoker, security-barrier and materialized-view storage settings; changing options invalidates the current seal even when the query text is unchanged. Unknown or removed relations/components refuse capture; changed schema definitions, routines, classification or prior/later migration facts invalidate the sealed epoch and previously retained reads. A new epoch requires an explicit monotonic owner installation against the complete current classified schema, not automatic resampling during a read. -Flyway writes each installing migration's own history row only after its migration transaction. The seal therefore binds distinct stable V1057, V1058, V1059, V1060, V1061, V1062, V1063 and V1064 installation markers and the actual installed definitions; it excludes only those eight installing history rows without inventing or claiming their eventual checksums. After installation, capture/readback additionally require exactly one successful SQL row for each version with its exact installing script in the configured history table. All other prior and later history facts remain part of the seal. Each forward installer seals the next monotonic owner epoch only after all routine replacements: V1058 binds view options, V1059 narrows the initial-preparation public-target conflict while preserving retained private projections, V1060 installs classified private catalog revision history/current-head control relations, and V1061 adds immutable private FRESH runtime identity provenance and seals epoch `5`; V1062 adds pending source protection and its writer guards before sealing epoch `6`; V1063 adds exact original-NEW capacity execution and its final-receipt binding before sealing epoch `7`; V1064 restores the final Human runtime completion row-version lower bound while preserving the full current RUNNING launch, candidate, capacity and identity guard, then seals epoch `8`. Earlier migrations and all retained epoch, snapshot and history bytes remain immutable. Requests retained under an older epoch conflict with the current epoch rather than being rewritten or resampled. Other installation and retention obligations remain with the [database migration owner](../../system-architecture-database-migrations.md); the configured history table, rather than an assumed `flyway_schema_history` alias, is itself explicitly classified as retained control evidence. +Flyway writes each installing migration's own history row only after its migration transaction. The seal therefore binds distinct stable V1057, V1058, V1059, V1060, V1061, V1062, V1063, V1064 and V1065 installation markers and the actual installed definitions; it excludes only those nine installing history rows without inventing or claiming their eventual checksums. After installation, capture/readback additionally require exactly one successful SQL row for each version with its exact installing script in the configured history table. All other prior and later history facts remain part of the seal. Each forward installer seals the next monotonic owner epoch only after all routine replacements: V1058 binds view options, V1059 narrows the initial-preparation public-target conflict while preserving retained private projections, V1060 installs classified private catalog revision history/current-head control relations, and V1061 adds immutable private FRESH runtime identity provenance and seals epoch `5`; V1062 adds pending source protection and its writer guards before sealing epoch `6`; V1063 adds exact original-NEW capacity execution and its final-receipt binding before sealing epoch `7`; V1064 restores the final Human runtime completion row-version lower bound while preserving the full current RUNNING launch, candidate, capacity and identity guard, then seals epoch `8`; V1065 adds retained normal-handoff transfer control and per-original fencing receipt families before sealing epoch `9`. Earlier migrations and all retained epoch, snapshot and history bytes remain immutable. Requests retained under an older epoch conflict with the current epoch rather than being rewritten or resampled. Other installation and retention obligations remain with the [database migration owner](../../system-architecture-database-migrations.md); the configured history table, rather than an assumed `flyway_schema_history` alias, is itself explicitly classified as retained control evidence. Gameplay commands and remote work whose namespace partition or replacement class is unresolved remain `UNKNOWN` and blocking, never implicitly S3. Durable tick/effect recovery, selected-work manifests, remote outcomes, script-pin authority/history and region/timeline provenance remain separate blocking evidence rather than cloned gameplay payload or a FRESH manifest. Input history and reconnect context retain their distinct audit/privacy consequences. `game_manifest` remains unsupported unqualified legacy lineage, not a build or FRESH source. Catalog/pointer, original operator/LOGIN/roster/binding/account/issuer authority, installed Saga control, and their original request, nonce, fence, replay, retirement and hold guards retain their owning consequences. Classification grants neither cleanup authority nor permission to discard uncertain work. The private preparation, original allocation and lifecycle-bound catalog revision branch are included as retained control/provenance; `PREPARING` is not a private runtime, CLOSED pointer or readiness result. 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 4bc8b35dcc..001b77a5a5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -54,7 +54,7 @@ Remaining qualification includes these exact-source checks, complete Account rea The new [normal-handoff source](../../architecture/microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing) prepares V1065 transfer custody, bounded region census/verification, real signed transfer-purpose currentness and deny-only tenant-slot fencing through the actual lease-owner path. New physical definitions cover abrupt process stop after the real SQL authorization commit, native handoff, predecessor Lua rejection, positive-retention refusal, current marker loss, Account hold/quarantine preservation and retained catalog upgrade. On the integrated local postimages, canonical V1065 jOOQ generation, production and Game Session integration-source compilation, both service Java format checks and documentation checks pass. The focused signed transfer-observation suite passes 101 cases and the Account workload-identity suite passes two cases, with zero failures, errors or skips. Initial compilation exposed a Jackson 3 checked-exception mismatch and generic AssertJ inference in the concurrency definitions; both were corrected before the passing checks. The multi-page/concurrency definitions use controlled reservation envelopes, separate from actual Account composition. All new physical PostgreSQL/Redis execution, complete affected static analysis and final published-source qualification remain pending. Production attestor custody, storage continuity, registration, runtime activation and admission remain held. -The prepared recovery policy `capacity-recovery/1` retains an immutable observation per current fenced claim, with twelve bounded read attempts and the original reconciliation deadline. Unavailable, invalid, late and ambiguous reads never release the hold. Exhaustion durably quarantines the original reservation, fence, exact payload and full held quota; replay performs no further source call. No operator release, automatic expiry, replacement reservation or unaudited quarantine-resolution API is supplied. The physical fixture includes controlled-source exhaustion/quarantine proof definitions; these remain unrun. Genuine audited Account remediation from independent owner evidence remains an activation prerequisite. +The prepared recovery policy `capacity-recovery/1` retains an immutable observation per current fenced claim, with twelve bounded read attempts and the original reconciliation deadline. A first delayed reconciliation still performs one bounded exact-owner read before quarantine and accepts only independent positive commit evidence after that deadline. New controlled-source definitions cover late positive finalization, late negative/malformed/unavailable/over-budget quarantine, mixed background/admission saturation under the combined four-operation cap, and a healthy renewing owner refusing a transfer contender before freeze. The new SQL/Redis physical definitions remain unrun. The handoff also freezes one deadline before inventory selection and retains it through every exact committed-source revalidation using the original provider with scoped connection and transaction custody. Blocked first committed selection and pre-install revalidation have physical test definitions that require no successor installation; they remain unrun. Focused cached compilation of all fifteen changed Java files and the five codec/session/transfer-observation/resource-budget/digest unit suites pass (135 tests, no failures or skips). An independent Python consumer passes four tests against the shared literal corpus, including a complete PLAYER_ADMISSION preimage with distinct player-context UUIDs and character/session changes; the Java consumer checks those same literal bytes. This does not qualify physical recovery, transfer, catalog upgrade or deployed authority. Unavailable, invalid, late and ambiguous reads never release the hold. Exhaustion durably quarantines the original reservation, fence, exact payload and full held quota; replay performs no further source call. No operator release, automatic expiry, replacement reservation or unaudited quarantine-resolution API is supplied. The physical fixture includes controlled-source exhaustion/quarantine proof definitions; these remain unrun. Genuine audited Account remediation from independent owner evidence remains an activation prerequisite. 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. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java index 2ac314ba86..fca009081f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java @@ -148,13 +148,19 @@ public Result reconcile(Request request, NoCommitAction noCommitAction) { } Observation candidate = null; byte[] candidateProof = null; - if (claim.attempts() < 12 && clock.instant().isBefore(claim.reconcileDeadline())) { - Instant deadline = clock.instant().plusSeconds(5); - if (claim.reconcileDeadline().isBefore(deadline)) deadline = claim.reconcileDeadline(); + if (claim.attempts() < 12) { + Instant started = clock.instant(); + boolean positiveOnly = !started.isBefore(claim.reconcileDeadline()); + Instant deadline = started.plusSeconds(5); + if (!positiveOnly && claim.reconcileDeadline().isBefore(deadline)) + deadline = claim.reconcileDeadline(); try { candidate = source.readExact(request, claim.reservation(), deadline); if (!clock.instant().isBefore(deadline)) throw unavailable(); requireExactSource(request, claim.reservation(), candidate); + // A delayed first reconciliation must still recognize an exact committed effect. The + // expired negative-evidence window never permits a late read to release the hold. + if (positiveOnly && candidate.disposition() != Disposition.COMMITTED) throw unavailable(); candidateProof = proof(request, candidate); } catch (RuntimeException unavailableSource) { // Missing, malformed, late and failed reads are indeterminate, never no-commit proof. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 8d29b9c7da..421d4c6c0f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -547,22 +547,170 @@ void boundedIndeterminateCapacityRecoveryQuarantinesTheOriginalCompleteHold() { assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_recovery_evidence"))) .isEqualTo(12); var usage = - f.context.dsl.fetchOne( - "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", - f.request.identity().tenantId()); + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()), + "Capacity usage row is absent"); assertThat(usage.get("held_units", Long.class)).isEqualTo(17); assertThat(usage.get("used_units", Long.class)).isZero(); var retained = - f.context.dsl.fetchOne( - "SELECT recovery_attempt_count, recovery_escalated_at, next_reconcile_at FROM account_tenant_capacity_reservations WHERE reservation_id = ?", - result.reservationId()); + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT recovery_attempt_count, recovery_escalated_at, next_reconcile_at FROM account_tenant_capacity_reservations WHERE reservation_id = ?", + result.reservationId()), + "Capacity reservation row is absent"); assertThat(retained.get("recovery_attempt_count", Integer.class)).isEqualTo(12); assertThat(retained.get("recovery_escalated_at")).isNotNull(); assertThat(retained.get("next_reconcile_at")).isNull(); } + @Test + void firstRecoveryAfterDeadlineFinalizesAnExactPositiveOnce() { + var f = capacityPersistenceFixture(true); + assertThat(Instant.now()).isAfter(f.initial.expiresAt().plusSeconds(60)); + var calls = new java.util.concurrent.atomic.AtomicInteger(); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + calls.incrementAndGet(); + assertThat(deadline).isAfter(Instant.now()); + assertThat(deadline).isBeforeOrEqualTo(Instant.now().plusSeconds(5)); + return capacityObservation( + request, + reservation, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.COMMITTED); + }, + java.time.Clock.systemUTC()); + var result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.FINALIZED); + assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.reservationFence()).isEqualTo(f.initial.reservationFence()); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(1); + var usage = + f.context.dsl.fetchSingle( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()); + assertThat(usage.get("held_units", Long.class)).isZero(); + assertThat(usage.get("used_units", Long.class)).isEqualTo(17); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_recovery_evidence"))) + .isEqualTo(1); + } + + @Test + void firstLateNegativeMalformedUnavailableAndOverBudgetReadsQuarantineWithoutReleasing() { + for (String outcome : + List.of("negative", "indeterminate", "malformed", "unavailable", "late")) { + var f = capacityPersistenceFixture(true); + assertThat(Instant.now()).isAfter(f.initial.expiresAt().plusSeconds(60)); + var now = new java.util.concurrent.atomic.AtomicReference<>(Instant.now()); + var recoveryClock = + new java.time.Clock() { + @Override + public java.time.ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public java.time.Clock withZone(java.time.ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now.get(); + } + }; + var calls = new java.util.concurrent.atomic.AtomicInteger(); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + calls.incrementAndGet(); + assertThat(deadline).isEqualTo(now.get().plusSeconds(5)); + if (outcome.equals("unavailable")) + throw new IllegalStateException("Controlled source unavailable"); + if (outcome.equals("late")) now.set(deadline); + var disposition = + outcome.equals("negative") + ? net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Disposition + .NOT_EXECUTED_AFTER_AUTHORIZATION + : outcome.equals("indeterminate") + ? net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Disposition.INDETERMINATE + : net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED; + var observation = capacityObservation(request, reservation, disposition); + if (!outcome.equals("malformed")) return observation; + return new net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Observation( + "spiffe://firemud/ns/prod/sa/wrong-owner", + observation.reservation(), + observation.canonicalAttemptPayload(), + observation.disposition(), + observation.proofId(), + observation.currentOwnerFence(), + observation.authoritativeStateDigest(), + observation.canonicalOwnerReadback()); + }, + recoveryClock); + var result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.state()) + .as(outcome) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State + .QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); + assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.reservationFence()).isEqualTo(f.initial.reservationFence()); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(1); + var usage = + f.context.dsl.fetchSingle( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()); + assertThat(usage.get("held_units", Long.class)).isEqualTo(17); + assertThat(usage.get("used_units", Long.class)).isZero(); + var retained = + f.context.dsl.fetchSingle( + "SELECT outcome, canonical_readback FROM account_tenant_capacity_recovery_evidence"); + assertThat(retained.get("outcome", String.class)) + .isEqualTo("QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION"); + assertThat(retained.get("canonical_readback")).isNull(); + } + } + /** Genuine same-transaction fresh creation; controlled entitlement and owner execution source. */ private static CapacityPersistenceFixture capacityPersistenceFixture() { + return capacityPersistenceFixture(false); + } + + private static CapacityPersistenceFixture capacityPersistenceFixture(boolean expired) { StorageContext c = storageContext(); var fixture = storageFixture(c); var assembled = assembleStoredOwner(c, fixture, new AccountAuditOutboxRepository(c.dsl)); @@ -575,7 +723,12 @@ private static CapacityPersistenceFixture capacityPersistenceFixture() { var base = net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.worldRequest( 17L); - var now = java.time.Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS); + // A retained historical reservation is inserted through the same controlled source fixture. + // No live producer accepts stale evidence, and no immutable row or database clock is changed. + var now = + java.time.Instant.now() + .minusSeconds(expired ? 120 : 0) + .truncatedTo(java.time.temporal.ChronoUnit.MICROS); String json = new String(base.evidence().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) .replace(base.identity().tenantId().toString(), tenant.toString()) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index 79c87dba01..dbc77a6006 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -7,9 +7,12 @@ import java.util.Base64; import java.util.HexFormat; import java.util.List; +import java.util.UUID; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Operation; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Shape; import org.junit.jupiter.api.Test; @@ -72,6 +75,107 @@ void sharedCorpusFixesCompleteEvidenceAndAbsentZeroPositiveBoundaryPreimages() t .isNotEqualTo(CapacityAdmissionTestFixture.worldRequest(0L).mutationDigest()); } + @Test + void sharedPlayerCorpusFixesIndependentPreimageAndDistinctCharacterAndSessionBindings() + throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + var request = corpus.path("playerRequest"); + var context = request.path("ownerContext"); + var vector = corpus.path("playerVector"); + var player = + new PlayerContext( + UUID.fromString(context.path("accountId").asText()), + UUID.fromString(context.path("tenantId").asText()), + UUID.fromString(context.path("playableStateNamespaceId").asText()), + UUID.fromString(context.path("gameInstanceId").asText()), + UUID.fromString(context.path("characterId").asText()), + UUID.fromString(context.path("sessionId").asText()), + UUID.fromString(context.path("realmId").asText()), + UUID.fromString(context.path("requestId").asText()), + context.path("playableStateScope").asText()); + assertThat( + List.of( + player.accountId(), + player.tenantId(), + player.playableStateNamespaceId(), + player.gameInstanceId(), + player.characterId(), + player.sessionId(), + player.realmId(), + player.requestId())) + .doesNotHaveDuplicates(); + assertThat(request.path("ownerService").asText()).isEqualTo(player.owner().service()); + Request action = + new Request( + new Identity( + UUID.fromString(request.path("tenantId").asText()), + UUID.fromString(request.path("requestId").asText()), + UUID.fromString(request.path("admissionId").asText())), + UUID.fromString(request.path("admissionAttemptId").asText()), + TenantCapacityAdmission.decimal(request.path("capacityRearmFence").asText()), + request.path("targetNamespace").asText(), + player, + Operation.valueOf(request.path("operation").asText()), + vectorShape(request.path("priorShape")), + vectorShape(request.path("requestedShape")), + Evidence.parse( + Base64.getDecoder() + .decode(request.path("canonicalAccountEvidenceBase64").asText()), + Owner.GAME_SESSION), + TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText()), + null) + .withDigest(); + action.requireCommittable(); + assertThat(HexFormat.of().formatHex(CapacityAdmissionDigest.preimage(action))) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(CapacityAdmissionDigest.digest(action)).isEqualTo(vector.path("sha256").asText()); + UUID changed = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + for (var ids : + List.of( + List.of(changed, player.sessionId()), + List.of(player.characterId(), changed), + List.of(player.sessionId(), player.characterId()))) { + var mutation = + new PlayerContext( + player.accountId(), + player.tenantId(), + player.playableStateNamespaceId(), + player.gameInstanceId(), + ids.get(0), + ids.get(1), + player.realmId(), + player.requestId(), + player.playableStateScope()); + Request altered = + new Request( + action.identity(), + action.admissionAttemptId(), + action.capacityRearmFence(), + action.targetNamespace(), + mutation, + action.operation(), + action.priorShape(), + action.requestedShape(), + action.evidence(), + action.capacityDelta(), + null) + .withDigest(); + altered.requireCommittable(); + assertThat(altered.mutationDigest()).isNotEqualTo(action.mutationDigest()); + } + } + } + + private static Shape vectorShape(tools.jackson.databind.JsonNode shape) { + return new Shape( + TenantCapacityAdmission.decimal(shape.get(0).asText()), + TenantCapacityAdmission.decimal(shape.get(1).asText()), + TenantCapacityAdmission.decimal(shape.get(2).asText())); + } + @Test void sharedRejectedEvidenceAndRequestsReachCanonicalValidators() throws Exception { var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json index 6d63b4d240..c8120d1075 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json +++ b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json @@ -195,5 +195,44 @@ "expected": "CAPACITY_QUOTA_EXCEEDED", "acceptedDigest": null } - ] + ], + "playerRequest": { + "tenantId": "22222222-2222-4222-8222-222222222222", + "requestId": "33333333-3333-4333-8333-333333333333", + "admissionId": "44444444-4444-4444-8444-444444444444", + "ownerService": "game-session-service", + "targetNamespace": "prod", + "ownerContext": { + "accountId": "11111111-1111-4111-8111-111111111111", + "tenantId": "22222222-2222-4222-8222-222222222222", + "playableStateNamespaceId": "66666666-6666-4666-8666-666666666666", + "gameInstanceId": "77777777-7777-4777-8777-777777777777", + "characterId": "88888888-8888-4888-8888-888888888888", + "sessionId": "99999999-9999-4999-8999-999999999999", + "realmId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "requestId": "33333333-3333-4333-8333-333333333333", + "playableStateScope": "SHARED" + }, + "admissionAttemptId": "55555555-5555-4555-8555-555555555555", + "capacityRearmFence": "1", + "operation": "CAPACITY_CREATING", + "priorShape": [ + "0", + "0", + "0" + ], + "requestedShape": [ + "1", + "0", + "0" + ], + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5U291cmNlRXZpZGVuY2UiOlt7ImNhbm9uaWNhbEV2ZW50SnNvbiI6IntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNFwiLFwiZXZlbnRJZFwiOlwiZWRiM2JkMzMtODZlMS0zYmZkLTllYjItZjY3ZmZkYzNjOTZiXCIsXCJldmVudFR5cGVcIjpcIlRFTkFOVF9BVVRIT1JJVFlfQ0hBTkdFRFwiLFwib3V0Ym94U2VxdWVuY2VcIjpcIjFcIixcIm91dGJveFN0cmVhbUtleVwiOlwiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJyZXF1ZXN0RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwicmVxdWVzdElkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInNjaGVtYVZlcnNpb25cIjpcImFjY291bnQtdGVuYW50LWF1dGhvcml0eS1ldmVudC92MVwiLFwic291cmNlRXZpZGVuY2VcIjp7XCJjYW5vbmljYWxUZW5hbnRJZFwiOlwiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJjcmVhdGlvblJlcXVlc3RJZFwiOlwiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzXCIsXCJldmlkZW5jZURpZ2VzdFwiOlwic2hhMjU2OjcxNzQwZWZmNTcxNzI0ZDY3ZmJiMjVjMGY4NzQ1MjYyMzY1NzRmNzI0MjlhODg1OTI2ODljMWFjNDdlODAzY2VcIixcIm9wZXJhdGlvbklkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInByb3ZlbmFuY2VLaW5kXCI6XCJORVdfR0FNRV9ST1dcIixcInJlcXVlc3REaWdlc3RcIjpcInNoYTI1NjpmMDZlNWU1MGJiZGE5OTE3YjNmZGFkOGUyNzczNzA2OTNmNDlhZmMzMzllZWM3Zjc1NDhiMWU1NDEyNTQ2NjkwXCIsXCJzY2hlbWFWZXJzaW9uXCI6MSxcInNvdXJjZUdhbWVSb3dJZFwiOlwiMTdcIixcInNvdXJjZUdhbWVUZW5hbnRLZXlcIjpcIndvcmxkXCIsXCJ0YXJnZXROYW1lc3BhY2VcIjpcInByb2RcIn0sXCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uXCI6XCIyXCIsXCJ0ZW5hbnRBdXRob3JpdHlTb3VyY2VWZXJzaW9uXCI6XCIyXCIsXCJ0ZW5hbnRCaWxsaW5nUmVjZWlwdFwiOntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwiZXZlbnRJZFwiOlwiNWFjMTU4MmItYTQwZC0zNTA1LWFiNDItZjc3NjY1N2I0YjYwXCIsXCJvdXRib3hTdHJlYW1LZXlcIjpcImFjY291bnQ6dGVuYW50LWVudGl0bGVtZW50OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIixcInRlbmFudEJpbGxpbmdTZXF1ZW5jZVwiOlwiMVwifSxcInRlbmFudElkXCI6XCIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIn0iLCJldmVudERpZ2VzdCI6InNoYTI1NjowZTg0Mjk5ODMzZDg1NzU0ZmE1ODNlNDE1MGZhN2Q5MTM3NDZiODNhZWVjMzRhMDU2YzRjY2I1NjZhMTUwYzI0IiwiZXZlbnRJZCI6ImVkYjNiZDMzLTg2ZTEtM2JmZC05ZWIyLWY2N2ZmZGMzYzk2YiIsIm91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9XSwiYXV0aG9yaXR5VHVwbGUiOnsiYWNjb3VudEF1dGhvcml0eUdlbmVyYXRpb24iOiIxIiwiaXNzdWVyQXV0aEdlbmVyYXRpb24iOiIxIiwibWVtYmVyc2hpcEF1dGhvcml0eUdlbmVyYXRpb24iOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjoiMSJ9LCJwcml2YXRlUmVhbG1HcmFudFZlcnNpb25zIjpbXSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiIyIn0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiIyIiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMSJ9fX0sImJ1bmRsZVZlcnNpb24iOiIxIiwiY2FsbGVyQWNjb3VudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIiwiY2FsbGVyV29ya2xvYWQiOiJzcGlmZmU6Ly9maXJlbXVkL25zL3Byb2Qvc2EvZ2FtZS1zZXNzaW9uLXNlcnZpY2UiLCJlbnRpdGxlbWVudFZlcnNpb24iOiIxIiwiZXZhbHVhdGVkQXQiOiIyMDI2LTExLTAyVDAwOjAwOjAwWiIsImV2YWx1YXRpb25JZGVudGl0eSI6InNoYTI1NjoyZDE4MzNlYTE0OTNlNjQzNmM0NTgxMDhlZjk4MWZkODEyODFhNjE3NjA4NTcyYWQ4MGJmM2JkY2RmNDgxZTdlIiwiZ2FtZXBsYXlBZG1pc3Npb25BbGxvd2VkIjpmYWxzZSwiZ2FtZXBsYXlBdmFpbGFibGUiOnRydWUsImlzc3VhbmNlRmVuY2UiOiIxIiwiaXNzdWVyIjoiZmlyZW11ZC1hY2NvdW50LXNlcnZpY2UiLCJtZW1iZXJzaGlwQXV0aG9yaXR5R2VuZXJhdGlvbiI6IjEiLCJtZW1iZXJzaGlwRXhpc3RzIjpmYWxzZSwibWVtYmVyc2hpcExpZmVjeWNsZVN0YXRlIjoiTUlTU0lORyIsIm1lbWJlcnNoaXBWZXJzaW9uIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6IjEifSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6YWNjb3VudC8xMTExMTExMS0xMTExLTQxMTEtODExMS0xMTExMTExMTExMTEifSx7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6aXNzdWVyL2ZpcmVtdWQtYWNjb3VudC1zZXJ2aWNlIn0seyJvdXRib3hTZXF1ZW5jZSI6IjAiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOm1lbWJlcnNoaXAvMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExLzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9LHsib3V0Ym94U2VxdWVuY2UiOiIxIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwic291cmNlRXZlbnREaWdlc3QiOiJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNCIsInNvdXJjZUV2ZW50SWQiOiJlZGIzYmQzMy04NmUxLTNiZmQtOWViMi1mNjdmZmRjM2M5NmIifV0sInByb3Zpc2lvbmluZ1N0YXR1cyI6bnVsbCwicXVvdGFzIjp7Im1heEFjdGl2ZVNlc3Npb25zIjoiMyIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiMiIsIm1heFN0b3JhZ2VCeXRlcyI6IjQwOTYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwicm9sZXMiOltdLCJzY2hlbWEiOiJhY2NvdW50LWF1dGgtZXZpZGVuY2UtYnVuZGxlL3YxIiwic25hcHNob3RJZGVudGl0eSI6InNoYTI1Njo0M2U1ZjVjNjEwZmNmMjBjYjQ0M2ExMzNkZWNlZWIwYzY2OTM5NmYwZWVjYTRmMmY5ODQ5MTFjMTNhNmZiM2YyIiwic291cmNlS2luZCI6Ik5PTl9QQUlEX0RFTU8iLCJzb3VyY2VSZWZlcmVuY2VzIjp7ImFkbWlzc2lvblBvaW50ZXJTbmFwc2hvdERpZ2VzdCI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb21taXRQcm9vZlNoYTI1NiI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb250ZXh0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJjYWxsZXJPcGVyYXRpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclJlZ2lzdHJ5UmVjb3JkU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImNhbGxlclRva2VuRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJjYWxsZXJUb2tlbkp0aSI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclRva2VuU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImVudGl0bGVtZW50U291cmNlRGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJnYW1lU2Vzc2lvbk93bmVyUHJvb2ZEaWdlc3QiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInBhaWRSZWNlaXB0VmFsaWRVbnRpbCI6bnVsbCwicHVibGlzaGVkUG9saWN5U2V0RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzY29wZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRDYXB0dXJlSWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJ3b3JsZExpZmVjeWNsZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRSb3dWZXJzaW9uIjoiMCJ9LCJzdWJzY3JpcHRpb25TdGF0dXMiOm51bGwsInRhcmdldCI6eyJhY3RpdmVXb3JsZEVwb2NoIjoiNSIsImNhbm9uaWNhbFZlcnNpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhdGFsb2dSZXZpc2lvbiI6IjciLCJjaGFyYWN0ZXJDcmVhdGlvblBvbGljeSI6IlBSRVNFRURFRF9PTkxZIiwiY29ubmVjdFNjb3BlRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMjowMFoiLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDFUMjM6NTk6NDBaIiwiZ2FtZUluc3RhbmNlSWQiOiI3Nzc3Nzc3Ny03Nzc3LTQ3NzctODc3Ny03Nzc3Nzc3Nzc3NzciLCJwbGF5YWJsZVN0YXRlTmFtZXNwYWNlSWQiOiI2NjY2NjY2Ni02NjY2LTQ2NjYtODY2Ni02NjY2NjY2NjY2NjYiLCJwbGF5YWJsZVN0YXRlU2NvcGUiOiJTSEFSRUQiLCJwb2ludGVyVmVyc2lvbiI6IjMiLCJyZWFsbUlkIjoiYWFhYWFhYWEtYWFhYS00YWFhLThhYWEtYWFhYWFhYWFhYWFhIiwicmVhbG1TbHVnIjoicHJvZHVjdGlvbiIsInRhcmdldENsYXNzIjoiUFVCTElDX1BST0RVQ1RJT04iLCJ0YXJnZXROYW1lc3BhY2UiOiJwcm9kIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ0ZW5hbnRTbHVnIjoidGVuYW50Iiwid29ybGRTbHVnIjoid29ybGQifSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjIiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YWxpZFVudGlsIjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJ2YXJpYW50IjoiUExBWUVSX0FETUlTU0lPTiIsInZlcmlmaWVkQ29ubmVjdFNjb3BlSWQiOiJjb250cm9sbGVkLXNjb3BlIn0=" + }, + "playerVector": { + "name": "distinct-player-admission-positive", + "capacityDelta": "1", + "commitAllowed": true, + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313634363a313a3331323a6f776e657253657276696365363a737472696e673132303a67616d652d73657373696f6e2d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313533353a313a39393a6163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323232343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a36363636363636362d363636362d343636362d383636362d36363636363636363636363631343a67616d65496e7374616e63654964363a737472696e673133363a37373737373737372d373737372d343737372d383737372d37373737373737373737373731313a6368617261637465724964363a737472696e673133363a38383838383838382d383838382d343838382d383838382d383838383838383838383838393a73657373696f6e4964363a737472696e673133363a39393939393939392d393939392d343939392d383939392d393939393939393939393939373a7265616c6d4964363a737472696e673133363a61616161616161612d616161612d346161612d386161612d616161616161616161616161393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331383a706c617961626c65537461746553636f7065363a737472696e6731363a53484152454431353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431383435353a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3132333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731383130343a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523555323931636d4e6c52585a705a475675593255694f6c7437496d4e68626d397561574e68624556325a573530536e4e7662694936496e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e4677694c4677695a585a6c626e524a5a4677694f6c77695a5752694d324a6b4d7a4d744f445a6c4d53307a596d5a6b4c546c6c596a49745a6a59335a6d5a6b597a4e6a4f545a695843497358434a6c646d56756446523563475663496a7063496c5246546b464f564639425656524954314a4a56466c6651306842546b6446524677694c46776962335630596d3934553256786457567559325663496a7063496a466349697863496d393164474a7665464e30636d56686255746c655677694f6c776959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a795a5846315a584e3052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c467769636d56786457567a64456c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e4e6a6147567459565a6c636e4e7062323563496a7063496d466a59323931626e517464475675595735304c57463164476876636d6c306553316c646d5675644339324d5677694c46776963323931636d4e6c52585a705a47567559325663496a703758434a6a59573576626d6c6a595778555a573568626e524a5a4677694f6c77694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a6a636d566864476c76626c4a6c6358566c6333524a5a4677694f6c77694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a5843497358434a6c646d6c6b5a57356a5a5552705a32567a644677694f6c7769633268684d6a55324f6a63784e7a51775a575a6d4e5463784e7a49305a4459335a6d4a694d6a566a4d4759344e7a51314d6a59794d7a59314e7a526d4e7a49304d6a6c684f4467314f5449324f446c6a4d57466a4e44646c4f44417a5932566349697863496d39775a584a6864476c76626b6c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e427962335a6c626d46755932564c6157356b5843493658434a4f525664665230464e525639535431646349697863496e4a6c6358566c633352456157646c63335263496a7063496e4e6f595449314e6a706d4d445a6c4e5755314d474a695a4745354f544533596a4e6d5a47466b4f4755794e7a637a4e7a41324f544e6d4e446c685a6d4d7a4d7a6c6c5a574d335a6a63314e4468694d5755314e4445794e5451324e6a6b775843497358434a7a5932686c625746575a584a7a61573975584349364d537863496e4e7664584a6a5a556468625756536233644a5a4677694f6c77694d54646349697863496e4e7664584a6a5a556468625756555a573568626e524c5a586c63496a7063496e6476636d786b5843497358434a3059584a6e5a58524f5957316c6333426859325663496a7063496e427962325263496e307358434a305a573568626e52426458526f62334a7064486c485a57356c636d46306157397558434936584349795843497358434a305a573568626e52426458526f62334a7064486c5462335679593256575a584a7a6157397558434936584349795843497358434a305a573568626e5243615778736157356e556d566a5a576c77644677694f6e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c4677695a585a6c626e524a5a4677694f6c77694e57466a4d5455344d6d4974595451775a43307a4e5441314c5746694e4449745a6a63334e6a59314e324930596a59775843497358434a76645852696233685464484a6c5957314c5a586c63496a7063496d466a59323931626e513664475675595735304c57567564476c30624756745a5735304f6e59784f6e526c626d4675644338794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a6349697863496e526c626d467564454a7062477870626d64545a5846315a57356a5a5677694f6c77694d56776966537863496e526c626d467564456c6b58434936584349794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a63496e30694c434a6c646d5675644552705a32567a64434936496e4e6f595449314e6a6f775a5467304d6a6b354f444d7a5a4467314e7a55305a6d45314f444e6c4e4445314d475a684e3251354d544d334e445a694f444e685a57566a4d7a52684d445532597a526a593249314e6a5a684d545577597a4930496977695a585a6c626e524a5a434936496d566b596a4e695a444d7a4c5467325a5445744d324a6d5a4330355a5749794c5759324e325a6d5a474d7a597a6b3259694973496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a395853776959585630614739796158523556485677624755694f6e736959574e6a623356756445463164476876636d6c306555646c626d567959585270623234694f6949784969776961584e7a64575679515856306145646c626d567959585270623234694f6949784969776962575674596d5679633268706345463164476876636d6c306555646c626d567959585270623234694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a6f694d534a394c434a77636d6c325958526c556d566862473148636d467564465a6c636e4e706232357a496a7062585377696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694979496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694979496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d534a3966583073496d4a31626d52735a565a6c636e4e70623234694f69497849697769593246736247567951574e6a6233567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784969776959324673624756795632397961327876595751694f694a7a63476c6d5a6d55364c79396d61584a6c6258566b4c32357a4c33427962325176633245765a3246745a53317a5a584e7a615739754c584e6c636e5a70593255694c434a6c626e52706447786c6257567564465a6c636e4e70623234694f694978496977695a585a68624856686447566b515851694f6949794d4449324c5445784c544179564441774f6a41774f6a417757694973496d563259577831595852706232354a5a47567564476c3065534936496e4e6f595449314e6a6f795a4445344d7a4e6c595445304f544e6c4e6a517a4e6d4d304e5467784d44686c5a6a6b344d575a6b4f4445794f4446684e6a45334e6a41344e546379595751344d474a6d4d324a6b5932526d4e4467785a54646c496977695a3246745a58427359586c425a47317063334e7062323542624778766432566b496a706d5957787a5a5377695a3246745a58427359586c42646d467062474669624755694f6e527964575573496d6c7a63335668626d4e6c526d5675593255694f6949784969776961584e7a64575679496a6f695a6d6c795a5731315a43316859324e76645735304c584e6c636e5a70593255694c434a745a5731695a584a7a61476c77515856306147397961585235523256755a584a6864476c7662694936496a45694c434a745a5731695a584a7a61476c77525868706333527a496a706d5957787a5a53776962575674596d567963326870634578705a6d566a65574e735a564e305958526c496a6f6954556c5455306c4f52794973496d316c62574a6c636e4e6f615842575a584a7a61573975496a7037496a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694936496a45696653776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453659574e6a62335675644338784d5445784d5445784d5330784d5445784c5451784d5445744f4445784d5330784d5445784d5445784d5445784d54456966537837496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453661584e7a645756794c325a70636d56746457517459574e6a623356756443317a5a584a3261574e6c496e307365794a7664585269623368545a5846315a57356a5a534936496a41694c434a76645852696233685464484a6c5957314c5a586b694f694a6859324e76645735304f6d4631644767745958563061473979615852354f6e59784f6d316c62574a6c636e4e6f615841764d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a394c48736962335630596d39345532567864575675593255694f6949784969776962335630596d3934553352795a57467453325635496a6f6959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49794969776963323931636d4e6c52585a6c626e52456157646c633351694f694a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e434973496e4e7664584a6a5a5556325a573530535751694f694a6c5a47497a596d517a4d7930344e6d55784c544e695a6d51744f5756694d69316d4e6a646d5a6d526a4d324d354e6d496966563073496e427962335a7063326c76626d6c755a314e305958523163794936626e567362437769635856766447467a496a7037496d31686545466a64476c325a564e6c63334e706232357a496a6f694d794973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694d694973496d316865464e3062334a685a3256436558526c63794936496a51774f54596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a49697769636d39735a584d694f6c74644c434a7a5932686c625745694f694a6859324e76645735304c574631644767745a585a705a47567559325574596e56755a47786c4c335978496977696332356863484e6f6233524a5a47567564476c3065534936496e4e6f595449314e6a6f304d3255315a6a566a4e6a45775a6d4e6d4d6a426a596a51304d3245784d7a4e6b5a574e6c5a574977597a59324f544d354e6d59775a57566a5954526d4d6d59354f4451354d54466a4d544e684e6d5a694d3259794969776963323931636d4e6c53326c755a434936496b3550546c395151556c4558305246545538694c434a7a62335679593256535a575a6c636d56755932567a496a7037496d466b62576c7a63326c76626c4276615735305a584a54626d467763326876644552705a32567a64434936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a446232317461585251636d39765a6c4e6f595449314e694936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a44623235305a586830535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a6a595778735a584a5063475679595852706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c4a6c5a326c7a64484a35556d566a62334a6b553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d4e686247786c636c5276613256755258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a6a595778735a584a556232746c626b703061534936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c527661325675553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d567564476c30624756745a57353055323931636d4e6c52476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6e5957316c5532567a63326c76626b3933626d567955484a7662325a456157646c633351694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4268615752535a574e6c61584230566d467361575256626e527062434936626e5673624377696348566962476c7a6147566b5547397361574e355532563052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a593239775a5552705a32567a64434936496e4e6f595449314e6a70685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746684969776964323979624752445958423064584a6c535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a3362334a735a4578705a6d566a65574e735a5552705a32567a64434936496e4e6f595449314e6a7068595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668496977696432397962475253623364575a584a7a61573975496a6f694d434a394c434a7a64574a7a59334a7063485270623235546447463064584d694f6d353162477773496e5268636d646c6443493665794a6859335270646d565862334a735a45567762324e6f496a6f694e534973496d4e68626d397561574e6862465a6c636e4e706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e6864474673623264535a585a7063326c7662694936496a63694c434a6a6147467959574e305a584a44636d566864476c76626c427662476c6a65534936496c425352564e465255524652463950546b785a4969776959323975626d566a64464e6a6233426c5258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d6a6f774d466f694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d4446554d6a4d364e546b364e444261496977695a3246745a556c7563335268626d4e6c535751694f6949334e7a63334e7a63334e7930334e7a63334c5451334e7a63744f4463334e7930334e7a63334e7a63334e7a63334e7a63694c434a776247463559574a735a564e305958526c546d46745a584e7759574e6c535751694f6949324e6a59324e6a59324e6930324e6a59324c5451324e6a59744f4459324e6930324e6a59324e6a59324e6a59324e6a59694c434a776247463559574a735a564e305958526c55324e76634755694f694a5453454653525551694c434a7762326c7564475679566d567963326c7662694936496a4d694c434a795a57467362556c6b496a6f695957466859574668595745745957466859533030595746684c546868595745745957466859574668595746685957466849697769636d5668624731546248566e496a6f6963484a765a48566a64476c7662694973496e5268636d646c64454e7359584e7a496a6f695546564354456c4458314253543052565131524a543034694c434a3059584a6e5a58524f5957316c63334268593255694f694a77636d396b496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a305a573568626e52546248566e496a6f6964475675595735304969776964323979624752546248566e496a6f696432397962475169665377696447567559573530515856306147397961585235523256755a584a6864476c7662694936496a49694c434a305a573568626e5243615778736157356e5532567864575675593255694f694978496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a32595778705a46567564476c73496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a3259584a7059573530496a6f6955457842575556535830464554556c5455306c5054694973496e5a6c636d6c6d6157566b51323975626d566a64464e6a6233426c535751694f694a6a62323530636d39736247566b4c584e6a6233426c496e303d31333a636170616369747944656c7461363a6e756d62657231313a3131313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "89ac3918c76ccd8ac17a1338ff4812ea9a2e814ccfa793e50886777b7fce334b" + } } diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py index b777da33ee..8581399ca5 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -1,5 +1,6 @@ """Independent capacity-admission/1 corpus consumer. Encoding proof, not runtime authority.""" import base64 +import copy import hashlib import json import re @@ -59,39 +60,51 @@ def reject_duplicates(pairs): return result -def evidence(encoded): +def evidence(encoded, variant="TENANT_OPERATION"): raw = base64.b64decode(encoded, validate=True) if not 0 < len(raw) <= 262144: raise ValueError("evidence bound") parsed = json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=reject_duplicates) canonical = json.dumps(parsed, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8") - if raw != canonical or parsed["schema"] != "account-auth-evidence-bundle/v1" or parsed["variant"] != "TENANT_OPERATION": + if raw != canonical or parsed["schema"] != "account-auth-evidence-bundle/v1" or parsed["variant"] != variant: raise ValueError("exact canonical variant required") tenant = parsed["tenantId"] cutoff = parsed["authorityTuple"]["tenantBillingCutoff"][tenant] points = parsed["outboxCheckpoints"] - if len(points) != 1 or any(cutoff[k] != points[0][k] for k in ("outboxStreamKey", "outboxSequence")): + matching = [point for point in points if point["outboxStreamKey"] == cutoff["outboxStreamKey"]] + if (variant == "TENANT_OPERATION" and len(points) != 1) or len(matching) != 1 or any( + cutoff[k] != matching[0][k] for k in ("outboxStreamKey", "outboxSequence")): raise ValueError("cutoff checkpoint mismatch") return encoded def preimage(request, candidate): context = request["ownerContext"] + if request["ownerService"] == "game-session-service": + variant = "PLAYER_ADMISSION" + owner_fields = [(key, string(context[key])) for key in + ("accountId", "tenantId", "playableStateNamespaceId", "gameInstanceId", + "characterId", "sessionId", "realmId", "requestId", "playableStateScope")] + elif request["ownerService"] == "world-management-service": + variant = "TENANT_OPERATION" + owner_fields = [(key, string(context[key])) for key in + ("tenantId", "operationId", "lifecycleId", "gameInstanceId", "ownerId")] + owner_fields.append(("ownerFence", number(context["ownerFence"]))) + else: + raise ValueError("known owner service required") fields = [ ("actionFamilySchemaId", string("capacity-admission")), ("actionFamilySchemaVersion", string("1")), ("scope", obj([(key, string(request[key])) for key in ("tenantId", "requestId", "admissionId")])), ("target", obj([("ownerService", string(request["ownerService"])), ("targetNamespace", string(request["targetNamespace"])), - ("ownerContext", obj([(key, string(context[key])) for key in - ("tenantId", "operationId", "lifecycleId", "gameInstanceId", "ownerId")] - + [("ownerFence", number(context["ownerFence"]))]))])), + ("ownerContext", obj(owner_fields))])), ("expectedVersion", obj([("admissionAttemptId", string(request["admissionAttemptId"])), ("capacityRearmFence", number(request["capacityRearmFence"]))])), ("mutation", obj([("operation", string(candidate.get("operation", request["operation"]))), ("priorShape", shape(candidate.get("priorShape", request["priorShape"]))), ("requestedShape", shape(candidate.get("requestedShape", request["requestedShape"]))), - ("accountEvidence", string(evidence(request["canonicalAccountEvidenceBase64"]))), + ("accountEvidence", string(evidence(request["canonicalAccountEvidenceBase64"], variant))), ("capacityDelta", value("absent", b"", False) if candidate["capacityDelta"] is None else number(candidate["capacityDelta"]))])), ("auditReason", string("capacity-admission"))] @@ -114,6 +127,24 @@ def test_shared_golden_preimages_and_digests(self): digests.append(digest) self.assertNotEqual(digests[0], digests[1]) + def test_player_golden_preimage_and_each_player_identity(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + request, candidate = corpus["playerRequest"], corpus["playerVector"] + context_ids = [item for key, item in request["ownerContext"].items() if key.endswith("Id")] + self.assertEqual(len(context_ids), len(set(context_ids))) + encoded = preimage(request, candidate) + self.assertEqual(encoded.hex(), candidate["preimageHex"]) + self.assertEqual(hashlib.sha256(encoded).hexdigest(), candidate["sha256"]) + for key in ("characterId", "sessionId"): + with self.subTest(key): + changed = copy.deepcopy(request) + changed["ownerContext"][key] = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb" + self.assertNotEqual(hashlib.sha256(preimage(changed, candidate)).hexdigest(), candidate["sha256"]) + swapped = copy.deepcopy(request) + context = swapped["ownerContext"] + context["characterId"], context["sessionId"] = context["sessionId"], context["characterId"] + self.assertNotEqual(hashlib.sha256(preimage(swapped, candidate)).hexdigest(), candidate["sha256"]) + def test_rejected_decimal_candidates(self): corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) for candidate in corpus["rejected"]: diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index 4eb6166481..537c57c303 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -183,7 +183,12 @@ public static Result requireResponse( var result = one(wire.getCommitmentList()); clean(result, MAX_RESPONSE_WIRE_BYTES); String expires = one(result.getExpiresAtList()); - Instant instant = Instant.parse(expires); + Instant instant; + try { + instant = Instant.parse(expires); + } catch (java.time.format.DateTimeParseException malformed) { + throw invalid(); + } if (!instant.toString().equals(expires)) throw invalid(); var parsed = new Result( diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index 933cffc97d..d829673131 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -174,6 +174,21 @@ void responseCannotSubstituteAttemptDigestFenceOrEvidenceIdentity() { } } + @Test + void malformedAndOutOfRangeResponseExpiryUseTheInvalidResponseException() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); + for (String expires : + List.of("not-an-instant", "2026-99-02T00:00:00Z", "+1000000001-01-01T00:00:00Z")) { + var malformed = + wire.toBuilder() + .setCommitment(0, wire.getCommitment(0).toBuilder().setExpiresAt(0, expires)) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(request, malformed)) + .isExactlyInstanceOf(IllegalArgumentException.class); + } + } + private static Result result(Request request) { return new Result( request.identity(), 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 9c8b466efe..d4e2ae7484 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 @@ -79,6 +79,18 @@ public final class CanonicalGameplayBindingInventoryRepository { this.dsl = Objects.requireNonNull(dsl, "dsl"); } + /** Handoff reads retain this repository's exact provider and the caller's frozen deadline. */ + T withinTransferRead( + java.time.Clock clock, + long absoluteDeadlineMillis, + java.util.function.Function read) { + requireNoAmbientTransaction(); + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + clock, + absoluteDeadlineMillis, + budget -> read.apply(new CanonicalGameplayBindingInventoryRepository(budget.sql(dsl)))); + } + CanonicalGameplayBindingTransitionSnapshot prepare( CanonicalGameplayBindingTransitionRequest request) { Objects.requireNonNull(request, "request"); 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 641725ccd5..ba07a16f2f 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 @@ -34,6 +34,8 @@ final class CanonicalGameplayOriginalNewCapacityExecutionBudget { static final int MAX_IN_FLIGHT_OPERATIONS = 4; private static final Semaphore OPERATIONS = new Semaphore(MAX_IN_FLIGHT_OPERATIONS); + static final int MAX_BACKGROUND_OPERATIONS = 2; + private static final Semaphore BACKGROUND_OPERATIONS = new Semaphore(MAX_BACKGROUND_OPERATIONS); private static final AtomicInteger RELEASE_FAILURE_RETAINED_OPERATIONS = new AtomicInteger(); static { @@ -46,6 +48,7 @@ final class CanonicalGameplayOriginalNewCapacityExecutionBudget { } private final ThreadFactory cancellationThreads; + private final boolean background; private final AtomicBoolean releaseFailureRecorded = new AtomicBoolean(); private final AtomicInteger outstandingConnections = new AtomicInteger(); private final Context caller; @@ -67,7 +70,8 @@ final class CanonicalGameplayOriginalNewCapacityExecutionBudget { private boolean released; private CanonicalGameplayOriginalNewCapacityExecutionBudget( - Clock clock, long explicitDeadline, ThreadFactory cancellationThreads) { + Clock clock, long explicitDeadline, ThreadFactory cancellationThreads, boolean background) { + this.background = background; this.clock = clock; this.explicitDeadline = explicitDeadline; this.cancellationThreads = Objects.requireNonNull(cancellationThreads); @@ -113,10 +117,37 @@ static T run( long explicitDeadline, Function operation, ThreadFactory cancellationThreads) { + return run(clock, explicitDeadline, operation, cancellationThreads, false); + } + + static T runBackground( + Clock clock, + long explicitDeadline, + Function operation) { + return run( + clock, + explicitDeadline, + operation, + Thread.ofVirtual().name("original-new-capacity-sql-cancel").factory(), + true); + } + + private static T run( + Clock clock, + long explicitDeadline, + Function operation, + ThreadFactory cancellationThreads, + boolean background) { var budget = new CanonicalGameplayOriginalNewCapacityExecutionBudget( - clock, explicitDeadline, cancellationThreads); - if (!OPERATIONS.tryAcquire()) throw unavailable(); + clock, explicitDeadline, cancellationThreads, background); + // Background reads and transfer work share the same four-operation ceiling, but cannot + // consume the two slots reserved for final admission. Neither class waits in a queue. + if (background && !BACKGROUND_OPERATIONS.tryAcquire()) throw unavailable(); + if (!OPERATIONS.tryAcquire()) { + if (background) BACKGROUND_OPERATIONS.release(); + throw unavailable(); + } Context.CancellationListener listener = ignored -> budget.cancel(); budget.caller.addListener(listener, Runnable::run); try { @@ -316,6 +347,7 @@ private void releaseIfFinished() { && (!cancellationStarted || cancellationDone)) { released = true; OPERATIONS.release(); + if (background) BACKGROUND_OPERATIONS.release(); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index e15e90f176..f5977dd991 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -438,7 +438,14 @@ private void retainTerminal(OriginalNewCapacityExecution execution, String statu /** Authenticated transport calls this read-only method. Absence and contradictions throw. */ public Snapshot readExact(Request request, Result reservation) { noSql(); - return within(Long.MAX_VALUE, owner -> owner.readExact(request, reservation, false)); + if (budget != null) return readExact(request, reservation, false); + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + clock, + Long.MAX_VALUE, + scoped -> + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + dsl, redis, scripts, clock, tags, scoped) + .readExact(request, reservation, false)); } private Snapshot readExact(Request request, Result reservation, boolean verifyForRetention) { 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 cf6347055c..d9948d4dd4 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 @@ -88,8 +88,16 @@ Installation installForTransition( requireNoAmbientTransaction(); Objects.requireNonNull(transitionId, "transitionId"); Objects.requireNonNull(worldRequest, "worldRequest"); + // Freeze the existing five-second transfer budget once, not once per inventory read. + final long handoffDeadline = + transferOwner == null + ? absoluteDeadlineMillis + : Math.min(absoluteDeadlineMillis, Math.addExact(clock.millis(), 5_000L)); CanonicalGameplayBindingProvisionalCasEvidence evidence = - readCurrentProvisionalEvidence(transitionId); + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> readCurrentProvisionalEvidence(inventory, transitionId)); ResolvedBridgeSource initialResolved = resolveExactBridgeSource(worldRequest, evidence); CanonicalGameplayRegionRuntimeStatusRepository.Source source = initialResolved.source; CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation = @@ -137,7 +145,10 @@ Installation installForTransition( try (CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization session = redisOwner.prepareTimelineInitialization(preparation, leaseTtl, runtimeIdentity)) { CanonicalGameplayBindingProvisionalCasEvidence beforeClaimEvidence = - readCurrentProvisionalEvidence(transitionId); + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> readCurrentProvisionalEvidence(inventory, transitionId)); bindingInventory.requireSameProvisionalSource(evidence, beforeClaimEvidence); ResolvedBridgeSource beforeClaimWorld = resolveExactBridgeSource(worldRequest, beforeClaimEvidence); @@ -163,7 +174,11 @@ Installation installForTransition( ResolvedBridgeSource afterInitWorld = resolveExactBridgeSource(worldRequest, evidence); requireSameSource(source, afterInitWorld.source); bindingInventory.requireSameProvisionalSource( - evidence, readCurrentProvisionalEvidence(transitionId)); + evidence, + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> readCurrentProvisionalEvidence(inventory, transitionId))); preparation = statusRepository.markRedisInitialized( preparation, @@ -210,19 +225,37 @@ Installation installForTransition( // Preserve ordinary timeline/incarnation qualification before any transfer effect. // A lost completion reply is not permission to freeze/advance its successor again. if (transferOwner.alreadyCompleted( - prior, runtimeIdentity.serviceInstanceId(), absoluteDeadlineMillis)) - throw unavailable(); + prior, runtimeIdentity.serviceInstanceId(), handoffDeadline)) throw unavailable(); + } + // A contender must not freeze a healthy incumbent whose lease is still renewing. + grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); + if (transferOwner != null) { + redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); + requireSameSource( + source, + resolveCurrentInstallationSource( + worldRequest, evidence, null, transferOwner, handoffDeadline)); + requireSameIncarnation(incarnation, readCurrentIncarnation(source)); + redisOwner.verifyInitializedTimeline(grant, preparation); var transferCandidate = - bindingInventory.readRegionTransferOriginalCandidate(transitionId, evidence); - transferId = transferOwner.advance(source, prior, absoluteDeadlineMillis); + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferOriginalCandidate(transitionId, evidence)); + redisOwner.requireCurrent(grant); + transferId = transferOwner.advance(source, prior, handoffDeadline); // Advance may retain a COMMITTED winner and activate its SQL inventory row. Keep that // exact terminal source separate from provisional binding/bridge authority. transferSource = - bindingInventory - .readRegionTransferCommittedSource(transitionId, transferCandidate) + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferCommittedSource( + transitionId, transferCandidate)) .orElse(null); } - grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); } else { requireReusableRegionGrant( existingRegionInstallation, source, incarnation, prior, expectedRegionEpoch); @@ -237,13 +270,15 @@ Installation installForTransition( redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); } CanonicalGameplayRegionRuntimeStatusRepository.Source afterAcquire = - resolveCurrentInstallationSource(worldRequest, evidence, transferSource); + resolveCurrentInstallationSource( + worldRequest, evidence, transferSource, transferOwner, handoffDeadline); requireSameSource(source, afterAcquire); redisOwner.renew(grant, leaseTtl); redisOwner.requireCurrent(grant); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); redisOwner.verifyInitializedTimeline(grant, preparation); + if (transferOwner != null && clock.millis() >= handoffDeadline) throw unavailable(); Instant installedAt = clock.instant(); CanonicalGameplayRegionRuntimeStatus installed = transferId == null @@ -262,7 +297,7 @@ Installation installForTransition( grant.tokenCorrelation(), grant.ownerService(), grant.ownerInstanceId(), - absoluteDeadlineMillis); + handoffDeadline); redisOwner.requireCurrent(grant); redisOwner.verifyInitializedTimeline(grant, preparation); @@ -270,7 +305,8 @@ Installation installForTransition( statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!installed.equals(observed) || observed.paused()) throw unavailable(); CanonicalGameplayRegionRuntimeStatusRepository.Source afterInstall = - resolveCurrentInstallationSource(worldRequest, evidence, transferSource); + resolveCurrentInstallationSource( + worldRequest, evidence, transferSource, transferOwner, handoffDeadline); requireSameSource(source, afterInstall); redisOwner.requireCurrent(grant); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); @@ -280,7 +316,9 @@ Installation installForTransition( redisOwner.verifyInitializedTimeline(grant, preparation); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); requireSameSource( - source, resolveCurrentInstallationSource(worldRequest, evidence, transferSource)); + source, + resolveCurrentInstallationSource( + worldRequest, evidence, transferSource, transferOwner, handoffDeadline)); CanonicalGameplayRegionRuntimeStatus finalStatus = statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!installed.equals(finalStatus) || finalStatus.paused()) throw unavailable(); @@ -692,9 +730,14 @@ private void requireOwnedContext(Installation installation, BridgeContext contex private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvidence( UUID transitionId) { + return readCurrentProvisionalEvidence(bindingInventory, transitionId); + } + + private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvidence( + CanonicalGameplayBindingInventoryRepository inventory, UUID transitionId) { requireNoAmbientTransaction(); CanonicalGameplayBindingProvisionalCasEvidence evidence = - bindingInventory.readProvisionalCasEvidence(transitionId); + inventory.readProvisionalCasEvidence(transitionId); if (evidence.transition().status() != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL || evidence.candidate().lifecycle() @@ -718,17 +761,37 @@ private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveExactSource private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveCurrentInstallationSource( CanonicalInitialPlayerLocationRequest request, CanonicalGameplayBindingProvisionalCasEvidence original, - CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource) { + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource, + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline) { if (transferSource == null) { return resolveExactSource( - request, readCurrentProvisionalEvidence(original.transition().transitionId())); + request, + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + readCurrentProvisionalEvidence(inventory, original.transition().transitionId()))); } var current = - bindingInventory.readRegionTransferOriginalSource( - original.transition().transitionId(), transferSource); + readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferOriginalSource( + original.transition().transitionId(), transferSource)); return resolveExactBridgeSource(request, current.candidate().bindingIdentity()).source; } + private T readInstallationInventory( + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline, + java.util.function.Function read) { + return transferOwner == null + ? read.apply(bindingInventory) + : bindingInventory.withinTransferRead(clock, handoffDeadline, read); + } + private ResolvedBridgeSource resolveExactBridgeSource( CanonicalInitialPlayerLocationRequest request, CanonicalGameplayBindingProvisionalCasEvidence evidence) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index d238fcf447..92305942d2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -60,7 +60,7 @@ T within( long deadline, Function work) { noSql(); if (admitted.get() != null) return work.apply(admitted.get()); - return CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + return CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( clock, deadline, budget -> { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 7e6a22c769..713d72c0f4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -425,6 +425,41 @@ void processStopAfterActualSqlAuthorizationBeforeRedisSendFencesUnknownAndActual .isInstanceOf(IllegalStateException.class); } + @Test + void contenderCannotFreezeRenewingOwnerAndExpiredLeaseStillTransfers() throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var leases = new CanonicalGameplayRegionLeaseRedisOwner(ownerClient, catalog); + String rows = sqlImage(); + Map physical = physicalImage(); + String key = capacityKey(tags.assignmentForTransition(fixture.transitionId())); + for (int attempt = 0; attempt < 2; attempt++) { + leases.renew(original.grant, Duration.ofSeconds(30)); + assertThatThrownBy(this::actualTransferHandoff).isInstanceOf(IllegalStateException.class); + leases.requireCurrent(original.grant); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + assertThat(admin.hget(ascii(key), ascii("state"))).containsExactly(ascii("AUTHORIZED")); + assertThat( + fixture + .dsl() + .fetchCount(org.jooq.impl.DSL.table("game_session_region_owner_transfer"))) + .isZero(); + } + admin.pexpire(ascii(original.grant.key()), 0); + var successor = actualTransferHandoff(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat(admin.hget(ascii(key), ascii("state"))) + .containsExactly(ascii("FENCED_INDETERMINATE")); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT state FROM game_session_region_owner_transfer") + .get(0, String.class)) + .isEqualTo("COMPLETED"); + } + @Test void authorizedUnknownHandoffKeepsOriginalCandidateAndRefusesCompletedMutation() throws Exception { @@ -720,6 +755,125 @@ void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff( .hasMessage("Region transfer changed its original transition"); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(ints = {1, 2}) + void blockedCommittedSelectionOrPreInstallRevalidationCannotOutliveHandoffDeadline( + int blockedRead) throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var ignored = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + // Leave positive SQL retention to the actual transfer, as in the crash-window test. + } + var original = regionBinding.installation(); + var transferRepository = + new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(transferRepository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, transferRepository, capacityOwner(), receiver); + String schema = fixture.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); + var blocked = new java.util.concurrent.atomic.AtomicBoolean(); + var completed = new java.util.concurrent.CountDownLatch(1); + var reads = new java.util.concurrent.atomic.AtomicInteger(); + try (var lock = + java.sql.DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + lock.setSchema(schema); + lock.setAutoCommit(false); + var observer = + new org.jooq.impl.DefaultExecuteListener() { + @Override + public void executeStart(org.jooq.ExecuteContext context) { + if (context.sql() == null + || !context.sql().contains("game_session_canonical_binding_inventory_clock") + || !context.sql().contains("FOR UPDATE")) return; + // This derived observer belongs only to the successor inventory/status context. + // The independently composed transfer has already retained the positive winner. + String status = + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class); + if (!"COMMITTED".equals(status) || reads.incrementAndGet() != blockedRead) return; + try (var statement = lock.createStatement()) { + statement.setQueryTimeout(2); + statement.execute( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock WHERE singleton_id=1 FOR UPDATE"); + blocked.set(true); + } catch (java.sql.SQLException failure) { + throw new IllegalStateException(failure); + } + } + + @Override + public void exception(org.jooq.ExecuteContext context) { + if (blocked.get()) completed.countDown(); + } + + @Override + public void executeEnd(org.jooq.ExecuteContext context) { + if (blocked.get()) completed.countDown(); + } + }; + var successorSql = + org.jooq.impl.DSL.using( + fixture + .dsl() + .configuration() + .derive(new org.jooq.impl.DefaultExecuteListenerProvider(observer))); + admin.pexpire(ascii(original.grant.key()), 0); + long started = System.nanoTime(); + long handoffDeadline = CLOCK.millis() + 4000; + try { + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + successorSql, + ownerClient, + catalog, + original, + sources.resolver, + transfer, + handoffDeadline)) + .isInstanceOf(IllegalStateException.class); + assertThat(blocked).as("exact committed inventory read reached").isTrue(); + assertThat(java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)) + .isLessThan(6500); + assertThat(completed.await(2, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } finally { + lock.rollback(); + } + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT executor_fence FROM game_session_region_runtime_status") + .get(0, BigInteger.class)) + .isEqualTo(original.status.executorFence()); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT state FROM game_session_region_owner_transfer") + .get(0, String.class)) + .isEqualTo("FROZEN"); + } + @Test void committedHashWithoutCompletePositiveServingProofStillBlocksActualTransfer() throws Exception { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index f257bb0539..4eb9ec7675 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -1512,6 +1512,14 @@ void genuineV1064ToV1065TransferFenceUpgradeRetainsOriginalRowsSnapshotsAndEpoch assertThat(f.classificationRows()) .containsAllEntriesOf(classifications) .hasSize(classifications.size() + 2); + assertThat(f.classificationRows().keySet()) + .containsExactlyInAnyOrderElementsOf( + java.util.stream.Stream.concat( + classifications.keySet().stream(), + java.util.stream.Stream.of( + "game_session_region_owner_transfer", + "game_session_region_owner_transfer_item")) + .toList()); assertThat( f.dsl .fetch( @@ -1524,6 +1532,10 @@ void genuineV1064ToV1065TransferFenceUpgradeRetainsOriginalRowsSnapshotsAndEpoch assertThat(f.historyRows(false).subList(0, history.size())).isEqualTo(history); assertThat(f.evidence(original.request())) .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().capture(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); var current = f.owner().capture(request()); assertThat(current.catalog().catalogEpoch()).isEqualTo(9); assertThat(f.owner().readExact(current.request())).isEqualTo(current); @@ -1543,7 +1555,8 @@ void genuineV1064ToV1065TransferFenceUpgradeRetainsOriginalRowsSnapshotsAndEpoch "game_session_region_owner_transfer", "game_session_region_owner_transfer_item")) { assertThat(f.count(table)).isZero(); assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")) - .isInstanceOf(org.jooq.exception.DataAccessException.class); + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Region owner transfer custody is retained"); } migration(f.source, f.schema, f.history, "1065").validate(); } 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 78fba2bfe8..2287685733 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 @@ -364,9 +364,9 @@ private static CanonicalGameplayOriginalNewAuthenticatedSession.Template templat new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result( request.identity(), request.admissionAttemptId(), - 1, + request.capacityRearmFence(), request.mutationDigest(), - request.admissionAttemptId(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), 1, request.evidence().expiresAt(), net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.RESERVED, 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 2743683041..7fd0aac9a9 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 @@ -62,6 +62,18 @@ void awaitResourceAndCancellationWorkerCleanup() throws InterruptedException { .as("resource and cancellation workers restore all operation permits") .isTrue(); permits.release(maximum); + Semaphore background = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, + "BACKGROUND_OPERATIONS")); + int maximumBackground = + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_BACKGROUND_OPERATIONS; + assertThat(background.tryAcquire(maximumBackground, 2, TimeUnit.SECONDS)) + .as("background admission follows the same cleanup lifecycle") + .isTrue(); + background.release(maximumBackground); } @Test @@ -110,6 +122,15 @@ void actualOwnerReadReturnsAtDeadlineAndLateAcquisitionNeverExecutes() throws Ex .isInstanceOf(IllegalStateException.class); assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(3500); assertThat(entered.await(1, TimeUnit.SECONDS)).isTrue(); + Semaphore background = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, + "BACKGROUND_OPERATIONS")); + assertThat(background.availablePermits()) + .isEqualTo( + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_BACKGROUND_OPERATIONS - 1); verifyNoInteractions(connection, redis); release.countDown(); verify(provider, timeout(2000)).release(connection); @@ -121,6 +142,81 @@ void actualOwnerReadReturnsAtDeadlineAndLateAcquisitionNeverExecutes() throws Ex } } + @Test + void actualTransferCommittedReadBoundsAcquisitionAndCannotExecuteAfterItsDeadline() + throws Exception { + ConnectionProvider provider = mock(); + Connection connection = mock(); + CountDownLatch entered = new CountDownLatch(1), release = new CountDownLatch(1); + when(provider.acquire()) + .thenAnswer( + invocation -> { + entered.countDown(); + awaitUninterruptibly(release); + return connection; + }); + var inventory = new CanonicalGameplayBindingInventoryRepository(source(provider)); + var candidate = mock(CanonicalGameplayOriginalNewCandidate.class); + UUID transitionId = UUID.randomUUID(); + when(candidate.bindingDecisionId()).thenReturn(transitionId); + long started = System.nanoTime(); + try { + assertThatThrownBy( + () -> + inventory.withinTransferRead( + CLOCK, + CLOCK.millis() + 1000, + scoped -> scoped.readRegionTransferCommittedSource(transitionId, candidate))) + .isInstanceOf(IllegalStateException.class); + assertThat(entered.await(1, TimeUnit.SECONDS)).isTrue(); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2500); + verifyNoInteractions(connection); + } finally { + release.countDown(); + verify(provider, timeout(2000)).release(connection); + } + } + + @Test + void transferReadDerivesItsOwnTransactionProviderAndKeepsTheOriginalAbsoluteDeadline() { + ConnectionProvider provider = mock(); + Connection connection = mock(); + when(provider.acquire()).thenReturn(connection); + try { + when(connection.getAutoCommit()).thenReturn(true); + } catch (java.sql.SQLException failure) { + throw new AssertionError(failure); + } + var original = source(provider); + var sharedTransactions = mock(org.jooq.TransactionProvider.class); + original.configuration().set(sharedTransactions); + var inventory = new CanonicalGameplayBindingInventoryRepository(original); + AtomicLong wall = new AtomicLong(CLOCK.millis()); + Clock clock = mock(); + when(clock.millis()).thenAnswer(ignored -> wall.get()); + long deadline = wall.get() + 2000; + boolean read = + inventory.withinTransferRead( + clock, + deadline, + scoped -> { + var sql = (DSLContext) ReflectionTestUtils.getField(scoped, "dsl"); + assertThat(sql).isNotNull(); + assertThat(sql.configuration().connectionProvider()).isNotSameAs(provider); + assertThat(sql.configuration().transactionProvider()).isNotSameAs(sharedTransactions); + return sql.transactionResult( + transaction -> DSL.using(transaction).connectionResult(owned -> Boolean.TRUE)); + }); + assertThat(read).isTrue(); + verify(provider).acquire(); + verify(provider).release(connection); + verifyNoInteractions(sharedTransactions); + wall.set(deadline); + assertThatThrownBy(() -> inventory.withinTransferRead(clock, deadline, scoped -> Boolean.TRUE)) + .isInstanceOf(IllegalStateException.class); + verify(provider, org.mockito.Mockito.times(1)).acquire(); + } + @Test void activeStatementCancellationFinishesBeforePoolReturn() throws Exception { ConnectionProvider provider = mock(); @@ -210,12 +306,19 @@ void uncertainProviderReleaseRetainsOnePermitAndExposesItThroughMicrometer() { CanonicalGameplayOriginalNewCapacityExecutionBudget.class, "OPERATIONS"); assertThat(retained).isNotNull(); assertThat(permits).isNotNull(); + Semaphore background = + (Semaphore) + java.util.Objects.requireNonNull( + ReflectionTestUtils.getField( + CanonicalGameplayOriginalNewCapacityExecutionBudget.class, + "BACKGROUND_OPERATIONS")); + int backgroundAvailable = background.availablePermits(); int before = retained.get(); int available = permits.availablePermits(); try { assertThatThrownBy( () -> - CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( CLOCK, Long.MAX_VALUE, budget -> { @@ -234,6 +337,7 @@ void uncertainProviderReleaseRetainsOnePermitAndExposesItThroughMicrometer() { .value()) .isEqualTo(before + 1); assertThat(permits.availablePermits()).isEqualTo(available - 1); + assertThat(background.availablePermits()).isEqualTo(backgroundAvailable - 1); assertThat(ReflectionTestUtils.getField(captured.get(), "released")).isEqualTo(false); assertThat( (AtomicInteger) @@ -248,6 +352,7 @@ void uncertainProviderReleaseRetainsOnePermitAndExposesItThroughMicrometer() { retained.decrementAndGet(); } if (permits.availablePermits() == available - 1) permits.release(); + if (background.availablePermits() == backgroundAvailable - 1) background.release(); } } finally { Metrics.removeRegistry(registry); @@ -332,6 +437,83 @@ void blockedAcquisitionsKeepAllFourSlotsAfterCallerTimeoutAndRejectWithoutQueuei } } + @Test + void backgroundSaturationReservesAdmissionCapacityWithoutExceedingCombinedFourSlots() + throws Exception { + ConnectionProvider provider = mock(); + Connection connection = mock(); + int backgroundMaximum = + CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_BACKGROUND_OPERATIONS; + int maximum = CanonicalGameplayOriginalNewCapacityExecutionBudget.MAX_IN_FLIGHT_OPERATIONS; + CountDownLatch backgroundEntered = new CountDownLatch(backgroundMaximum); + CountDownLatch allEntered = new CountDownLatch(maximum); + CountDownLatch release = new CountDownLatch(1); + when(provider.acquire()) + .thenAnswer( + invocation -> { + backgroundEntered.countDown(); + allEntered.countDown(); + awaitUninterruptibly(release); + return connection; + }); + DSLContext source = source(provider); + var callers = new ArrayList>(); + try { + for (int index = 0; index < backgroundMaximum; index++) + callers.add( + CompletableFuture.runAsync( + () -> + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + CLOCK, + CLOCK.millis() + 1000, + budget -> execute(budget.sql(source)))) + .isInstanceOf(IllegalStateException.class))); + assertThat(backgroundEntered.await(2, TimeUnit.SECONDS)).isTrue(); + var refused = new AtomicBoolean(); + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground( + CLOCK, + Long.MAX_VALUE, + budget -> { + refused.set(true); + return true; + })) + .isInstanceOf(IllegalStateException.class); + assertThat(refused).isFalse(); + boolean admitted = + CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + CLOCK, Long.MAX_VALUE, budget -> Boolean.TRUE); + assertThat(admitted).isTrue(); + for (int index = backgroundMaximum; index < maximum; index++) + callers.add( + CompletableFuture.runAsync( + () -> + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + CLOCK, + CLOCK.millis() + 1000, + budget -> execute(budget.sql(source)))) + .isInstanceOf(IllegalStateException.class))); + assertThat(allEntered.await(2, TimeUnit.SECONDS)).isTrue(); + CompletableFuture.allOf(callers.toArray(CompletableFuture[]::new)).get(2, TimeUnit.SECONDS); + // Callers timed out, but blocked acquisition still owns all four permits. + assertThatThrownBy( + () -> + CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + CLOCK, Long.MAX_VALUE, budget -> execute(budget.sql(source)))) + .isInstanceOf(IllegalStateException.class); + verify(provider, org.mockito.Mockito.times(maximum)).acquire(); + verifyNoInteractions(connection); + } finally { + release.countDown(); + verify(provider, timeout(2000).times(maximum)).release(connection); + } + } + @Test void explicitDeadlineIsOneBudgetAcrossQueriesWithoutGrpcContext() throws Exception { ConnectionProvider provider = mock(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java index e990b39600..cc6221192b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java @@ -134,6 +134,7 @@ void transferSignedPurposeCannotBeReplayedThroughAccountReceiver() { () -> receiver.observeForFenceTarget(context.transferId(), context.targetOrdinal())) .isInstanceOf( CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + assertThat(fixture.channelCalls).hasValue(1); } @Test @@ -169,6 +170,7 @@ void transferSignedPurposeCannotBeReplayedThroughInitialReceiver() { assertThatThrownBy(() -> receiver.observeForInitialAccountBarrier(context.requestId())) .isInstanceOf( CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + assertThat(fixture.channelCalls).hasValue(1); } @ParameterizedTest From 8804433397a30b4cf5adbb8d9d9878f991d96e30 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 12:07:00 +1300 Subject: [PATCH 29/52] Bind nullable SQL observer text before admission assertions --- ...eplayOriginalNewFinalAdmissionOwnerIntegrationTest.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 713d72c0f4..5e3286a5ce 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -798,9 +798,10 @@ void blockedCommittedSelectionOrPreInstallRevalidationCannotOutliveHandoffDeadli new org.jooq.impl.DefaultExecuteListener() { @Override public void executeStart(org.jooq.ExecuteContext context) { - if (context.sql() == null - || !context.sql().contains("game_session_canonical_binding_inventory_clock") - || !context.sql().contains("FOR UPDATE")) return; + String sql = context.sql(); + if (sql == null + || !sql.contains("game_session_canonical_binding_inventory_clock") + || !sql.contains("FOR UPDATE")) return; // This derived observer belongs only to the successor inventory/status context. // The independently composed transfer has already retained the positive winner. String status = From 385e43e77d8c71da012b49a8be2c326511ff111d Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 12:52:35 +1300 Subject: [PATCH 30/52] Make transfer observations unambiguous and retain physical install diagnostics --- ...GameplayRegionOwnerTransferRepository.java | 11 ++++++++-- ...untimeStatusRepositoryIntegrationTest.java | 22 ++++++++++++++++++- ...eplayLoginContextRedisIntegrationTest.java | 1 + 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 92305942d2..1a22c2c478 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -33,6 +33,13 @@ final class CanonicalGameplayRegionOwnerTransferRepository static final int PAGE_SIZE = 32; private static final String TRANSFER = "game_session_region_owner_transfer"; private static final String ITEM = "game_session_region_owner_transfer_item"; + // Join predicates prove the four shared identity fields equal; project them only once. + private static final String CURRENT_PROJECTION = + "SELECT t.*,r.canonical_region_id,r.tenant_region_tag,r.lifecycle_epoch," + + "r.lifecycle_row_version,r.lifecycle_request_bytes,r.capture_id,r.graph_sha256," + + "r.preparation_input_digest,r.executor_fence,r.lease_token_correlation," + + "r.owner_service,r.owner_instance_id,r.paused,r.last_committed_tick_batch_id," + + "r.last_committed_tick_id,r.updated_at FROM "; private static final String PENDING = " FROM game_session_original_new_capacity_execution e" + " JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=e.transition_id" @@ -526,7 +533,7 @@ public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( private static Record observationCurrent(DSLContext tx, UUID id) { Record row = tx.fetchOne( - "SELECT t.*,r.* FROM " + CURRENT_PROJECTION + TRANSFER + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND r.region_epoch=t.region_epoch AND ((t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence) OR (t.state='COMPLETED' AND r.owner_instance_id=t.new_owner_id AND r.executor_fence=t.new_owner_fence AND r.lease_token_correlation=t.new_lease_correlation))", id); @@ -615,7 +622,7 @@ private Item loadItem(DSLContext tx, UUID transferId, long ordinal, String execu private static Record current(DSLContext tx, UUID id, boolean lock) { Record row = tx.fetchOne( - "SELECT t.*,r.* FROM " + CURRENT_PROJECTION + TRANSFER + " t JOIN game_session_region_runtime_status r ON r.tenant_id=t.tenant_id AND r.game_instance_id=t.game_instance_id AND r.region_id=t.region_id WHERE t.transfer_id=? AND t.state='FROZEN' AND r.owner_instance_id=t.old_owner_id AND r.executor_fence=t.old_owner_fence AND r.region_epoch=t.region_epoch" + (lock ? " FOR UPDATE OF r,t" : ""), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 2bfe78fb24..1fd780c820 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -944,7 +944,27 @@ private TransferSqlProof() throws Exception { BigInteger.ONE, BigInteger.valueOf(64)); fixture = new CanonicalGameplayAdmissionAbortCompositionFixture(dataSource, candidate, redis); - sql = fixture.dsl(); + sql = + DSL.using( + fixture + .dsl() + .configuration() + .deriveAppending( + new DefaultExecuteListener() { + @Override + public void resultEnd(ExecuteContext context) { + String query = context.sql(); + var result = context.result(); + if (query != null + && query.contains("JOIN game_session_region_runtime_status r") + && result != null) { + assertThat(result.fields()) + .extracting(org.jooq.Field::getName) + .as("current transfer observation has unambiguous field names") + .doesNotHaveDuplicates(); + } + } + })); tags = new CanonicalGameplayTenantGameplayTagRepository(sql, "test", 1); scripts = RedisScriptCatalog.fromContributions( 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 3db0c1bf41..0c6aea2996 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 @@ -709,6 +709,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); From 06c9ec64e4cdecab6c2a8f178f3d95c9fe78768b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 13:38:30 +1300 Subject: [PATCH 31/52] Prepare isolated proof of frozen transfer replay and contract tests Seven-path candidate based exactly on 385e43e7. Product branch remains unchanged while current Hosted review runs. --- .../CanonicalGameplayRegionLeaseOwner.java | 70 +++++--- ...ameplayRegionOwnerTransferCoordinator.java | 38 ++++- ...GameplayRegionOwnerTransferRepository.java | 48 ++++++ ...NewFinalAdmissionOwnerIntegrationTest.java | 151 ++++++++++++++++++ .../AccountTenantCapacityClientMtlsTest.java | 49 ++++-- ...nOwnerTransferObservationReceiverTest.java | 24 ++- ...wCapacityExecutionReadGrpcServiceTest.java | 2 + 7 files changed, 348 insertions(+), 34 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index d9948d4dd4..42860566d9 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 @@ -93,23 +93,52 @@ Installation installForTransition( transferOwner == null ? absoluteDeadlineMillis : Math.min(absoluteDeadlineMillis, Math.addExact(clock.millis(), 5_000L)); + // A prior advance may have retained the positive SQL result before a later observation + // failed. Recover only its captured original, never synthetic provisional authority. + var frozenOriginal = + transferOwner != null && existingRegionInstallation == null + ? transferOwner.frozenOriginal(transitionId, handoffDeadline) + : null; + var retainedOriginal = + frozenOriginal == null + ? null + : readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferCommittedSource( + transitionId, frozenOriginal.candidate())) + .orElse(null); CanonicalGameplayBindingProvisionalCasEvidence evidence = - readInstallationInventory( - transferOwner, - handoffDeadline, - inventory -> readCurrentProvisionalEvidence(inventory, transitionId)); - ResolvedBridgeSource initialResolved = resolveExactBridgeSource(worldRequest, evidence); + retainedOriginal != null + ? null + : readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> readCurrentProvisionalEvidence(inventory, transitionId)); + ResolvedBridgeSource initialResolved = + retainedOriginal == null + ? resolveExactBridgeSource(worldRequest, evidence) + : resolveExactBridgeSource( + worldRequest, retainedOriginal.candidate().bindingIdentity()); CanonicalGameplayRegionRuntimeStatusRepository.Source source = initialResolved.source; CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation = readCurrentIncarnation(source); long expectedRegionEpoch = - exactExpectedRegionEpoch(evidence.candidate().identity().regionEpoch()); + exactExpectedRegionEpoch( + retainedOriginal == null + ? evidence.candidate().identity().regionEpoch() + : retainedOriginal.candidate().bindingIdentity().regionEpoch()); CanonicalGameplayRegionRuntimeStatus prior = statusRepository.find(source).orElse(null); if (prior == null && expectedRegionEpoch != 1L) throw unavailable(); if (prior != null && prior.regionEpoch() != expectedRegionEpoch) throw unavailable(); + if (retainedOriginal != null) { + if (prior == null || retainedOriginal.finalReceipt().isEmpty()) throw unavailable(); + transferOwner.requireFrozenOriginal(frozenOriginal, source, prior, handoffDeadline); + } UUID transferId = null; CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource = - null; + retainedOriginal; CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; @@ -194,7 +223,7 @@ Installation installForTransition( .findTimelinePreparation(source) .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); boolean sameInitializationAttempt = - preparation.transitionId().equals(evidence.transition().transitionId()); + evidence != null && preparation.transitionId().equals(transitionId); boolean matchesInitialization = sameInitializationAttempt ? statusRepository.matchesTimelinePreparation( @@ -234,17 +263,22 @@ Installation installForTransition( requireSameSource( source, resolveCurrentInstallationSource( - worldRequest, evidence, null, transferOwner, handoffDeadline)); + worldRequest, evidence, transferSource, transferOwner, handoffDeadline)); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); redisOwner.verifyInitializedTimeline(grant, preparation); var transferCandidate = - readInstallationInventory( - transferOwner, - handoffDeadline, - inventory -> - inventory.readRegionTransferOriginalCandidate(transitionId, evidence)); + retainedOriginal != null + ? retainedOriginal.candidate() + : readInstallationInventory( + transferOwner, + handoffDeadline, + inventory -> + inventory.readRegionTransferOriginalCandidate(transitionId, evidence)); redisOwner.requireCurrent(grant); - transferId = transferOwner.advance(source, prior, handoffDeadline); + transferId = + retainedOriginal == null + ? transferOwner.advance(source, prior, handoffDeadline) + : transferOwner.resume(frozenOriginal, source, prior, handoffDeadline); // Advance may retain a COMMITTED winner and activate its SQL inventory row. Keep that // exact terminal source separate from provisional binding/bridge authority. transferSource = @@ -371,7 +405,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); @@ -404,7 +438,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 = @@ -779,7 +813,7 @@ private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveCurrentInst handoffDeadline, inventory -> inventory.readRegionTransferOriginalSource( - original.transition().transitionId(), transferSource)); + transferSource.candidate().bindingDecisionId(), transferSource)); return resolveExactBridgeSource(request, current.candidate().bindingIdentity()).source; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java index ce3eaca3df..8c5247d97c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java @@ -36,15 +36,51 @@ boolean alreadyCompleted( return repository.completedForCurrent(prior, requestingOwner, deadline); } + CanonicalGameplayRegionOwnerTransferRepository.Item frozenOriginal( + UUID transitionId, long deadline) { + return repository.within(deadline, ignored -> repository.frozenOriginal(transitionId)); + } + + void requireFrozenOriginal( + CanonicalGameplayRegionOwnerTransferRepository.Item original, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + long deadline) { + repository.within( + deadline, + ignored -> { + repository.requireFrozenOriginal(original, source, prior); + return null; + }); + } + + UUID resume( + CanonicalGameplayRegionOwnerTransferRepository.Item original, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + long deadline) { + return advance(source, prior, deadline, original); + } + /** A bounded step; incomplete progress remains durable and the caller must resume this intent. */ UUID advance( CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior, long deadline) { + return advance(source, prior, deadline, null); + } + + private UUID advance( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior, + long deadline, + CanonicalGameplayRegionOwnerTransferRepository.Item original) { return repository.within( deadline, budget -> { - UUID transfer = repository.begin(source, prior); + if (original != null) repository.requireFrozenOriginal(original, source, prior); + UUID transfer = + original == null ? repository.begin(source, prior) : original.transferId(); if (transfer == null) return null; var owner = capacity.forTransferBudget(budget); for (var item : repository.capture(transfer)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 1a22c2c478..1827841346 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -86,6 +86,54 @@ DSLContext sql() { return budget.sql(dsl); } + /** Read only an already captured original under its still-current frozen old owner. */ + Item frozenOriginal(UUID transitionId) { + noSql(); + Record row = + sql() + .fetchOne( + "SELECT i.transfer_id,i.target_ordinal,i.execution_digest FROM " + + ITEM + + " i JOIN " + + TRANSFER + + " t ON t.transfer_id=i.transfer_id" + + " JOIN game_session_original_new_capacity_execution e ON e.execution_digest=i.execution_digest" + + " WHERE e.transition_id=? AND t.state='FROZEN'", + transitionId); + if (row == null) return null; + UUID id = row.get("transfer_id", UUID.class); + current(sql(), id, false); + return loadItem( + sql(), + id, + row.get("target_ordinal", Long.class), + row.get("execution_digest", String.class)); + } + + /** Revalidate a pinned continuation without creating a replacement transfer intent. */ + void requireFrozenOriginal( + Item original, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus prior) { + noSql(); + sql() + .transaction( + configuration -> { + var tx = DSL.using(configuration); + requireOldOwner(tx, source, prior); + var row = current(tx, original.transferId(), true); + if (!sourceDigest(source, prior).equals(row.get("source_digest", String.class))) + throw unavailable(); + var actual = + loadItem( + tx, original.transferId(), original.ordinal(), original.execution().digest()); + if (!actual.candidate().equals(original.candidate()) + || !Arrays.equals( + actual.execution().canonicalBytes(), original.execution().canonicalBytes())) + throw unavailable(); + }); + } + UUID begin( CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 5e3286a5ce..21f0ed2780 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -755,6 +755,157 @@ void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff( .hasMessage("Region transfer changed its original transition"); } + @Test + void frozenTransferResumesSameCommittedOriginalAfterFenceRetentionFailure() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + byte[] committed; + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var ignored = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + committed = admin.get(ascii(installation.sessionKey())); + } + var original = regionBinding.installation(); + var failRetention = new java.util.concurrent.atomic.AtomicBoolean(true); + var failed = new java.util.concurrent.atomic.AtomicBoolean(); + var observer = + new org.jooq.impl.DefaultExecuteListener() { + @Override + public void executeStart(org.jooq.ExecuteContext context) { + String query = context.sql(); + if (query == null || !query.contains(" SET fence_readback=")) return; + if (!failRetention.get()) return; + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("COMMITTED"); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT original_new_final_session_sha256 FROM game_session_canonical_binding_transition WHERE transition_id=?", + fixture.transitionId()) + .get(0, String.class)) + .isNotBlank(); + failed.set(true); + throw new IllegalStateException("Controlled failure after positive SQL retention"); + } + }; + var observedSql = + org.jooq.impl.DSL.using(fixture.dsl().configuration().deriveAppending(observer)); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(observedSql, CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + observedSql, CLOCK, repository, capacityOwner(), receiver); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + catalog, + original, + sources.resolver, + transfer, + deadline())) + .isInstanceOf(RuntimeException.class); + assertThat(failed).isTrue(); + var frozen = fixture.dsl().fetchSingle("SELECT * FROM game_session_region_owner_transfer"); + UUID transferId = frozen.get("transfer_id", UUID.class); + String intent = frozen.get("intent_digest", String.class); + assertThat(frozen.get("state", String.class)).isEqualTo("FROZEN"); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(original.status); + var retained = inventory.readRegionTransferOriginalSource(fixture.transitionId(), source); + assertThat(retained.transitionStatus()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED); + assertThat(retained.finalReceipt()).isPresent(); + String executionImage = + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(e)::text FROM game_session_original_new_capacity_execution e WHERE execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class); + long sequence = + fixture + .dsl() + .fetchSingle("SELECT last_value FROM game_session_region_executor_fence_seq") + .get(0, Long.class); + failRetention.set(false); + // Controlled expiry of the failed contender's grant, not a bypass of a live incumbent. + admin.pexpire(ascii(original.grant.key()), 0); + var successor = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), ownerClient, catalog, original, sources.resolver, transfer, deadline()); + assertThat(successor.status.ownerInstanceId()).isEqualTo("final-owner-handoff"); + var completed = fixture.dsl().fetchSingle("SELECT * FROM game_session_region_owner_transfer"); + assertThat(completed.get("transfer_id", UUID.class)).isEqualTo(transferId); + assertThat(completed.get("intent_digest", String.class)).isEqualTo(intent); + assertThat(completed.get("state", String.class)).isEqualTo("COMPLETED"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT last_value FROM game_session_region_executor_fence_seq") + .get(0, Long.class)) + .isEqualTo(sequence + 1); + assertThat( + inventory + .readRegionTransferOriginalSource(fixture.transitionId(), retained) + .finalReceipt()) + .isEqualTo(retained.finalReceipt()); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(e)::text FROM game_session_original_new_capacity_execution e WHERE execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo(executionImage); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); + assertThat(successor.evidence) + .as("committed continuation grants no provisional bridge authority") + .isNull(); + assertThatThrownBy( + () -> + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), + ownerClient, + catalog, + original, + sources.resolver, + transfer, + deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(successor.status); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT last_value FROM game_session_region_executor_fence_seq") + .get(0, Long.class)) + .isEqualTo(sequence + 1); + } + @org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.ValueSource(ints = {1, 2}) void blockedCommittedSelectionOrPreInstallRevalidationCannotOutliveHandoffDeadline( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index d13d56873b..6dfc209023 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -42,6 +42,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** Real loopback mTLS with a controlled Account result; not Account sources or final admission. */ @Timeout(90) @@ -137,13 +139,43 @@ void changedResponseFenceCannotSubstituteForOriginalCommitment() throws Exceptio } } + @ParameterizedTest + @CsvSource({"3000, 60000, 3000", "60000, 3000, 3000", "60000, 60000, 5000"}) + void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( + long explicitMillis, long incomingMillis, long expectedMaximumMillis) throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicLong observedNanos = new AtomicLong(); + // Each case owns one server and one successful RPC, so no other call can supply its sample. + Server server = server("account", calls, false, observedNanos, new AtomicBoolean(true)); + var scheduler = Executors.newSingleThreadScheduledExecutor(); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + try (var context = + Context.current().withDeadlineAfter(incomingMillis, TimeUnit.MILLISECONDS, scheduler)) { + var result = + context.call( + () -> + client.commit( + request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + explicitMillis)); + assertThat(result.identity()).isEqualTo(request.identity()); + } + assertThat(calls).hasValue(1); + assertThat(observedNanos.get()) + .isPositive() + .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis)); + } finally { + scheduler.shutdownNow(); + stop(server); + } + } + @Test void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() throws Exception { AtomicInteger calls = new AtomicInteger(); - AtomicLong observedNanos = new AtomicLong(); AtomicBoolean respond = new AtomicBoolean(true); - Server server = server("account", calls, false, observedNanos, respond); + Server server = server("account", calls, false, new AtomicLong(), respond); try (var client = client(server)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(); @@ -158,29 +190,23 @@ void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); - assertThat(observedNanos.get()) - .isPositive() - .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(200)); respond.set(true); assertThat(client.commit(request, deadline())).isEqualTo(first); - assertThat(calls).hasValue(3); } finally { stop(server); } } @Test - void incomingDeadlineAndFiveSecondMaximumAlsoCapTheAccountCall() throws Exception { + void incomingDeadlineBoundsAStalledAccountCall() throws Exception { AtomicInteger calls = new AtomicInteger(); - AtomicLong observedNanos = new AtomicLong(); AtomicBoolean respond = new AtomicBoolean(true); - Server server = server("account", calls, false, observedNanos, respond); + Server server = server("account", calls, false, new AtomicLong(), respond); var scheduler = Executors.newSingleThreadScheduledExecutor(); try (var client = client(server)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(); client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 60_000L); - assertThat(observedNanos.get()).isPositive().isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(5)); respond.set(false); long started = System.nanoTime(); assertThatThrownBy( @@ -194,9 +220,6 @@ void incomingDeadlineAndFiveSecondMaximumAlsoCapTheAccountCall() throws Exceptio assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); - assertThat(observedNanos.get()) - .isPositive() - .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(200)); } finally { scheduler.shutdownNow(); stop(server); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java index cc6221192b..6a329f07e4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java @@ -405,7 +405,14 @@ void retainedOwnerLengthUsesThePostgresCharacterBound() { @ParameterizedTest @ValueSource( - strings = {"issued", "observed-before", "observed-after", "expires", "expired", "clock-back"}) + strings = { + "issued", + "observed-before", + "observed-after-expiry", + "expires", + "expired", + "clock-back" + }) void timeWindowMismatchOrDeadlineExpiryRefuses(String mode) { var fixture = new Fixture(); switch (mode) { @@ -413,7 +420,7 @@ void timeWindowMismatchOrDeadlineExpiryRefuses(String mode) { fixture.mutation = root -> root.put("observationIssuedAtEpochMillis", NOW - 1L); case "observed-before" -> fixture.mutation = root -> root.put("observationObservedAtEpochMillis", NOW - 1L); - case "observed-after" -> + case "observed-after-expiry" -> fixture.mutation = root -> root.put("observationObservedAtEpochMillis", NOW + 1_001L); case "expires" -> fixture.mutation = root -> root.put("observationExpiresAtEpochMillis", NOW + 999L); @@ -424,6 +431,19 @@ void timeWindowMismatchOrDeadlineExpiryRefuses(String mode) { assertRejected(fixture); } + @Test + void futureObservationWithinSignedExpiryReachesCurrentClockRefusal() { + var fixture = new Fixture(); + fixture.mutation = root -> root.put("observationObservedAtEpochMillis", NOW + 1L); + assertThatThrownBy(() -> fixture.observe(NOW + 1_000L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class) + .hasMessage("Protected observation is expired or out of window"); + // A second source read occurs only after the signed payload and its time window are verified. + assertThat(fixture.sourceReads).hasValue(2); + assertThat(fixture.channelCalls).hasValue(1); + } + @Test void expiredOperationNeverReadsSourceOrCallsChannel() { var fixture = new Fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayOriginalNewCapacityExecutionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayOriginalNewCapacityExecutionReadGrpcServiceTest.java index e3e3134b9b..98bcdca7db 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayOriginalNewCapacityExecutionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayOriginalNewCapacityExecutionReadGrpcServiceTest.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import io.grpc.Context; @@ -96,6 +97,7 @@ private static CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService serv private static void assertStatus(StreamObserver observer, Status.Code code) { ArgumentCaptor error = ArgumentCaptor.forClass(Throwable.class); verify(observer).onError(error.capture()); + verifyNoMoreInteractions(observer); assertThat(Status.fromThrowable(error.getValue()).getCode()).isEqualTo(code); } } From bbec21ebcf1cd99299048c3c7e5ccd964ecdb29b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 14:22:58 +1300 Subject: [PATCH 32/52] Fix canonical vectors, workload metadata and physical expiry evidence --- .../test_capacity_admission_vectors.py | 21 +++++++++++++++ ...NewCapacityExecutionReadWorkloadGuard.java | 7 +++++ ...NewFinalAdmissionOwnerIntegrationTest.java | 27 ++++++++++++++++++- ...NewFinalAdmissionPhysicalImageFixture.java | 6 ++--- ...apacityExecutionReadWorkloadGuardTest.java | 20 +++++++++++--- 5 files changed, 73 insertions(+), 8 deletions(-) diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py index 8581399ca5..877b98acf1 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -62,6 +62,8 @@ def reject_duplicates(pairs): def evidence(encoded, variant="TENANT_OPERATION"): raw = base64.b64decode(encoded, validate=True) + if base64.b64encode(raw).decode("ascii") != encoded: + raise ValueError("canonical padded base64 required") if not 0 < len(raw) <= 262144: raise ValueError("evidence bound") parsed = json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=reject_duplicates) @@ -145,6 +147,25 @@ def test_player_golden_preimage_and_each_player_identity(self): context["characterId"], context["sessionId"] = context["sessionId"], context["characterId"] self.assertNotEqual(hashlib.sha256(preimage(swapped, candidate)).hexdigest(), candidate["sha256"]) + def test_rejects_nonzero_unused_base64_pad_bits(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + parsed = json.loads(base64.b64decode(corpus["request"]["canonicalAccountEvidenceBase64"])) + alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + for padding in (1, 2): + # Valid JSON evidence with each padding width isolates the base64 spelling check. + for width in range(3): + parsed["padBitTest"] = "x" * width + raw = json.dumps(parsed, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + canonical = base64.b64encode(raw).decode("ascii") + if canonical.endswith("=" * padding) and not canonical.endswith("=" * (padding + 1)): + break + self.assertEqual(evidence(canonical), canonical) + index = len(canonical) - padding - 1 + alternate = canonical[:index] + alphabet[alphabet.index(canonical[index]) + 1] + canonical[index + 1:] + self.assertEqual(base64.b64decode(alternate, validate=True), raw) + with self.subTest(padding=padding), self.assertRaisesRegex(ValueError, "canonical padded base64"): + evidence(alternate) + def test_rejected_decimal_candidates(self): corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) for candidate in corpus["rejected"]: diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard.java index c0297a51b1..54c06a36a6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard.java @@ -14,6 +14,8 @@ /** Exact same-namespace Account-only guard for the ORIGINAL_NEW final-result read. */ public final class CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard implements ServerInterceptor { + private static final Metadata.Key AUTHORIZATION_KEY = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); private final String workloadNamespace; public CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard(String workloadNamespace) { @@ -63,6 +65,11 @@ public ServerCall.Listener interceptCall( call.close(Status.fromCode(denied.getStatus().getCode()), new Metadata()); return new ServerCall.Listener<>() {}; } + if (headers.containsKey(AUTHORIZATION_KEY)) { + call.close( + Status.PERMISSION_DENIED.withDescription("End-user token not permitted"), new Metadata()); + return new ServerCall.Listener<>() {}; + } return next.startCall(call, headers); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 21f0ed2780..c606436746 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -83,6 +83,30 @@ class CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest { controlledCapacity; private CanonicalGameplayRegionOwnerCompositionFixture.ExistingBinding regionBinding; + @Test + void physicalImageRetainsAbsoluteExpiryRatherThanOnlyItsPresence() { + byte[] key = "physical-image-expiry".getBytes(StandardCharsets.US_ASCII); + admin.set(key, "unchanged".getBytes(StandardCharsets.US_ASCII)); + byte[] persistent = + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key); + long expiresAt = System.currentTimeMillis() + 60_000L; + admin.pexpireat(key, expiresAt); + byte[] expiring = + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key); + assertThat(expiring).isNotEqualTo(persistent); + assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) + .isEqualTo(expiring); + admin.pexpireat(key, expiresAt + 600_000L); + assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) + .isNotEqualTo(expiring); + admin.persist(key); + assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) + .isEqualTo(persistent); + admin.del(key); + assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) + .isNotEqualTo(persistent); + } + @BeforeEach void setUp() throws Exception { administrator = client(null, null); @@ -894,7 +918,8 @@ public void executeStart(org.jooq.ExecuteContext context) { sources.resolver, transfer, deadline())) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("A first binding cannot proceed while an active controller exists"); assertThat( new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) .contains(successor.status); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.java index 9a994988f0..34a37cd16c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.java @@ -15,10 +15,8 @@ static byte[] image(RedisCommands commands, byte[] key) { var output = new ByteArrayOutputStream(); String type = commands.type(key); append(output, type.getBytes(StandardCharsets.US_ASCII)); - long ttl = commands.pttl(key); - // Persistent/missing keys stay exact. Expiring fault fixtures retain a positive-TTL marker; - // their separate assertions check expiry without comparing a naturally decreasing duration. - append(output, Long.toString(ttl > 0 ? 1 : ttl).getBytes(StandardCharsets.US_ASCII)); + long expiresAt = commands.pexpiretime(key); + append(output, Long.toString(expiresAt).getBytes(StandardCharsets.US_ASCII)); switch (type) { case "none" -> {} case "string" -> append(output, commands.get(key)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuardTest.java index dab283f3a0..a0c10d3070 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuardTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuardTest.java @@ -66,17 +66,31 @@ void refusesMissingForeignAndPlayerOrSyntheticCallerContexts() { assertDenied(invoke(method, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED); } + @Test + void refusesForwardedAuthorizationMetadataFromAnOtherwiseValidAccountPeer() { + var method = + OriginalNewCapacityExecutionReadServiceGrpc.getReadOriginalNewCapacityExecutionMethod(); + for (String authorization : List.of("Bearer player-token", "")) { + Metadata headers = new Metadata(); + headers.put( + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), authorization); + assertDenied( + invokeTyped(method, peer(NAMESPACE, "account-service"), headers), + Status.Code.PERMISSION_DENIED); + } + } + private static void assertDenied(Invocation invocation, Status.Code code) { assertThat(invocation.nextStarts()).isZero(); assertThat(invocation.status().getCode()).isEqualTo(code); } private Invocation invoke(MethodDescriptor method, GrpcPeerIdentity peer) { - return invokeTyped(method, peer); + return invokeTyped(method, peer, new Metadata()); } @SuppressWarnings({"rawtypes", "unchecked"}) - private Invocation invokeTyped(MethodDescriptor method, GrpcPeerIdentity peer) { + private Invocation invokeTyped(MethodDescriptor method, GrpcPeerIdentity peer, Metadata headers) { ServerCall call = mock(ServerCall.class); org.mockito.Mockito.when(call.getMethodDescriptor()).thenReturn(method); AtomicInteger starts = new AtomicInteger(); @@ -87,7 +101,7 @@ private Invocation invokeTyped(MethodDescriptor method, GrpcPeerIdentity peer) { }; Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run(() -> guard.interceptCall(call, new Metadata(), next)); + .run(() -> guard.interceptCall(call, headers, next)); ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); org.mockito.Mockito.verify(call, org.mockito.Mockito.atMostOnce()) .close(status.capture(), any(Metadata.class)); From 7a525379c9a7544d37771f597e518bd3d719ff5b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 14:35:41 +1300 Subject: [PATCH 33/52] Retain exact aborted originals through frozen owner transfer --- .../game-session-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 2 + ...playOriginalNewCapacityExecutionOwner.java | 26 +- ...GameplayRegionOwnerTransferRepository.java | 7 +- ...alGameplayTenantGameplayTagRepository.java | 50 +++- ...NewFinalAdmissionOwnerIntegrationTest.java | 266 ++++++++++++++++++ 6 files changed, 342 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index ac117d27ed..4094365ff0 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -22,6 +22,8 @@ The protected receiver has a separate `REGION_OWNER_TRANSFER` purpose and signed An observed `COMMITTED` hash is not a transfer exemption: the existing positive continuation must verify the complete serving/session/index outcome, persist any missing final SQL receipt and retain immutable `COMMITTED` evidence before that item is handled. Missing positive proof blocks transfer. Existing exact `CLOSED` evidence likewise follows the existing independent closure-retention path. Neither terminal record is overwritten. Only the privately constructed current fencing capability and complete locked inventory check permit the actual acquire/install/revalidate path to install the successor and immutable transfer completion in one transaction. The original attempts remain fenced and non-admitting. A completed transfer supports a separately phase-bound signed currentness read only while its immutable successor still matches the actual current region source; completed observations cannot enroll items, change receipts or authorize another installation. Loss of the original completion reply does not grant a fresh transfer or recreate a private lease handle. +An exact retained first-NEW Account-aborted original remains part of the transfer inventory, whether abort preceded capture or completed while the transfer was frozen. Its topology lookup verifies the retained definitive abort and existing immutable mapping without restoring provisional admission authority. First negative closure still requires the complete physical candidate/index proof; already-retained CLOSED replay uses its exact permanent tombstone. Unknown history remains fenced and indeterminate, never discarded because Account or SQL records an abort. + V1065 retains the transfer control and per-original receipt families, their immutable source and completion guards, and the next owner catalog epoch. Their retention hold is not a cleanup horizon. The composition remains manual and unregistered. Controlled signed-source fixtures do not establish operational attestor custody, storage continuity, deployed recovery, runtime activation or player admission. ## Runtime Model 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 001b77a5a5..a05b544b76 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -28,6 +28,8 @@ The Account source/transport foundation contains unregistered TENANT_OPERATION a ### Strict tenant-capacity owner preparation +The pending transfer review repair retains exact Account-aborted originals for transfer observation, whether abort precedes capture or completes while frozen, and fences them without interpreting abort as non-execution. Source and focused regression definitions are prepared. Canonical Java formatting and focused four-source Java compilation pass; physical transfer proof is not yet run. Existing SQL CLOSED and permanent Redis tombstone requirements remain unchanged, as does unavailable/quarantined treatment of a missing execution row. + 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. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index f5977dd991..6411504847 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -294,12 +294,21 @@ public void closeOriginalAttempt(Request request, Result reservation) { // Successful positive reconciliation never authorizes the requested negative closure. throw unavailable(); } - if (!"PROVISIONAL".equals(transition.get("status", String.class)) - || transition.get("original_new_final_session_sha256") != null) throw unavailable(); + requireClosedTransition(transition); + if ("ABORTED".equals(transition.get("status", String.class))) { + var abort = + CanonicalGameplayBindingInventoryRepository + .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( + sql(), execution.transitionId(), false); + if (!abort.isAccountAborted()) throw unavailable(); + } var candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical( transition.get("original_new_candidate_bytes", byte[].class)); - var assignment = scopedTags().assignmentForTransition(execution.transitionId()); + var assignment = + "ABORTED".equals(transition.get("status", String.class)) + ? scopedTags().assignmentForRetainedCapacityExecution(execution.transitionId()) + : scopedTags().assignmentForTransition(execution.transitionId()); if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class))) throw unavailable(); long result = @@ -622,7 +631,11 @@ TransferFence fenceForTransfer( // Merely seeing a COMMITTED hash must not release old-generation custody. retainCommittedBeforeCleanup(execution.request(), execution.reservation(), deadline); } else if (result == 4) { - closeOriginalAttempt(execution.request(), execution.reservation()); + if ("CLOSED".equals(row.get("status", String.class))) { + readExact(execution.request(), execution.reservation(), false); + } else { + closeOriginalAttempt(execution.request(), execution.reservation()); + } } else if (result != 5) throw unavailable(); return readTransferFence(item, deadline); } @@ -730,7 +743,10 @@ private void requireCandidateAndIndexes( CanonicalGameplayOriginalNewCandidate candidate, String expectedFinalDigest, OriginalNewCapacityExecution execution) { - var assignment = scopedTags().assignmentForTransition(execution.transitionId()); + var assignment = + "ABORTED".equals(transition(execution).get("status", String.class)) + ? scopedTags().assignmentForRetainedCapacityExecution(execution.transitionId()) + : scopedTags().assignmentForTransition(execution.transitionId()); if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class))) throw unavailable(); var binding = candidate.bindingIdentity(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 1827841346..79e67a2c04 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -575,7 +575,9 @@ public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( UUID transitionId, CanonicalGameplayTenantGameplayTagRepository sourceTags) { if (admitted.get() == null) return within(Long.MAX_VALUE, ignored -> readAssignment(transitionId, sourceTags)); - return sourceTags.withCapacityExecutionDsl(sql()).assignmentForTransition(transitionId); + return sourceTags + .withCapacityExecutionDsl(sql()) + .assignmentForRetainedCapacityExecution(transitionId); } private static Record observationCurrent(DSLContext tx, UUID id) { @@ -632,7 +634,8 @@ private Item loadItem(DSLContext tx, UUID transferId, long ordinal, String execu .admissionAttemptId() .equals(row.get("admission_attempt_id", UUID.class))) throw unavailable(); var assignment = - tags.withCapacityExecutionDsl(sql()).assignmentForTransition(execution.transitionId()); + tags.withCapacityExecutionDsl(sql()) + .assignmentForRetainedCapacityExecution(execution.transitionId()); if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class))) throw unavailable(); var binding = candidate.bindingIdentity(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index d0d528d1d8..96d077c0eb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -64,6 +64,38 @@ public Assignment assignmentForTransition(UUID transitionId) { }); } + /** Retained topology for capacity handoff; never grants provisional admission authority. */ + Assignment assignmentForRetainedCapacityExecution(UUID transitionId) { + requireNonNil(transitionId, "transitionId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + Record transition = + transaction.fetchOne( + "SELECT status FROM game_session_canonical_binding_transition WHERE transition_id=?", + transitionId); + boolean aborted = + transition != null && "ABORTED".equals(transition.get("status", String.class)); + if (aborted) { + var retained = + CanonicalGameplayBindingInventoryRepository + .readRetainedDefinitiveFirstNewAccountAbortSourceInTransaction( + transaction, transitionId, false); + if (!retained.isAccountAborted()) + throw conflict("Exact retained Account abort required"); + } + BindingTarget source = loadBindingTarget(transaction, transitionId, null, aborted); + requireTenantClaim(transaction, source.tenantId()); + // A retained execution cannot allocate replacement topology after loss of its mapping. + if (transaction.fetchOne( + "SELECT 1 FROM " + MAPPING + " WHERE tenant_id=?", source.tenantId()) + == null) throw conflict("Retained capacity execution mapping is unavailable"); + return resolveMapping( + transaction, source, allocationVersion, tagFor(source.tenantId(), allocationVersion)); + }); + } + /** Topology-only retained lookup for one irreversibly selected original negative continuation. */ Assignment assignmentForOriginalNewAbandonment(UUID transitionId, UUID abandonmentId) { requireNonNil(transitionId, "transitionId"); @@ -264,6 +296,11 @@ private BindingTarget loadBindingTarget(DSLContext transaction, UUID transitionI private BindingTarget loadBindingTarget( DSLContext transaction, UUID transitionId, UUID abandonmentId) { + return loadBindingTarget(transaction, transitionId, abandonmentId, false); + } + + private BindingTarget loadBindingTarget( + DSLContext transaction, UUID transitionId, UUID abandonmentId, boolean retainedAbort) { boolean negative = abandonmentId != null; String negativeSelector = negative @@ -323,10 +360,15 @@ private BindingTarget loadBindingTarget( .equals(requiredUuid(row, "account_index_fence")) || !requiredUuid(row, "transition_reservation_id") .equals(requiredUuid(row, "inventory_reservation_id")) - || !(negative ? Set.of("PREPARED", "ABORTED") : TRANSITION_STATES).contains(transitionState) - || !(negative - ? Set.of("CANDIDATE_PREPARED", "TERMINAL_UNRESOLVED", "TERMINAL") - : INVENTORY_STATES) + || !(retainedAbort + ? Set.of("ABORTED") + : negative ? Set.of("PREPARED", "ABORTED") : TRANSITION_STATES) + .contains(transitionState) + || !(retainedAbort + ? Set.of("TERMINAL_UNRESOLVED", "TERMINAL") + : negative + ? Set.of("CANDIDATE_PREPARED", "TERMINAL_UNRESOLVED", "TERMINAL") + : INVENTORY_STATES) .contains(inventoryState) || !transitionRefMatches( transitionRefBytes, inventoryRefBytes, tenantId, gameInstanceId, sessionId) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index c606436746..e9060099d6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -83,6 +83,272 @@ class CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest { controlledCapacity; private CanonicalGameplayRegionOwnerCompositionFixture.ExistingBinding regionBinding; + @Test + void committedCapacityWithoutExecutionCustodyRemainsIndeterminate() throws Exception { + repairAccountMember(); + bridge(false); + var before = physicalImage(); + assertThat( + fixture + .dsl() + .fetchCount( + org.jooq.impl.DSL.table("game_session_original_new_capacity_execution"))) + .isZero(); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + capacityOwner() + .closeOriginalAttempt( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + assertThat( + fixture + .dsl() + .fetchCount( + org.jooq.impl.DSL.table("game_session_original_new_capacity_execution"))) + .isZero(); + assertThat(physicalImage()).isEqualTo(before); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "false,false", + "false,true", + "true,false", + "true,true" + }) + void exactAbortedOriginalCompletesSameTransferBeforeAndAfterCapture( + boolean abortAfterCapture, boolean originalReservationExpired) throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + Clock transferClock = + originalReservationExpired ? Clock.offset(CLOCK, Duration.ofHours(1)) : CLOCK; + if (originalReservationExpired) + assertThat(controlledCapacity.reservation().expiresAt()).isBefore(transferClock.instant()); + var repository = + new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), transferClock, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture(transferClock) + .receiver(repository, tags); + var capacity = + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + fixture.dsl(), ownerClient, catalog, transferClock, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), transferClock, repository, capacity, receiver); + UUID transferId = null; + if (abortAfterCapture) { + transferId = + repository.within( + transferClock.millis() + 5000L, + ignored -> repository.begin(original.source, original.status)); + UUID capturedId = transferId; + var captured = + repository.within( + transferClock.millis() + 5000L, ignored -> repository.capture(capturedId)); + assertThat(captured).hasSize(1); + } + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + byte[] candidate = admin.get(ascii(installation.sessionKey())); + UUID resumed = + transfer.advance(original.source, original.status, transferClock.millis() + 5000L); + if (transferId != null) assertThat(resumed).isEqualTo(transferId); + String intent = + fixture + .dsl() + .fetchSingle( + "SELECT intent_digest FROM game_session_region_owner_transfer WHERE transfer_id=?", + resumed) + .get(0, String.class); + // Real expiry of the incumbent Redis lease, followed by actual grant acquisition and protected + // installation. + admin.pexpire(ascii(original.grant.key()), 0); + var installed = installAbortedTransferSuccessor(transfer, original, resumed, transferClock); + assertThat(installed.ownerInstanceId()).isEqualTo("aborted-original-successor"); + assertThat(installed.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(installed); + var completed = + fixture + .dsl() + .fetchSingle( + "SELECT transfer_id,intent_digest,state FROM game_session_region_owner_transfer"); + assertThat(completed.get("transfer_id", UUID.class)).isEqualTo(resumed); + assertThat(completed.get("intent_digest", String.class)).isEqualTo(intent); + assertThat(completed.get("state", String.class)).isEqualTo("COMPLETED"); + assertThat( + receiver + .observeForRegionOwnerTransfer(resumed, 0, transferClock.millis() + 5000L) + .regionOwnerTransferContext() + .controlState()) + .isEqualTo("COMPLETED"); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(candidate); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition WHERE transition_id=?", + fixture.transitionId()) + .get(0, String.class)) + .isEqualTo("ABORTED"); + assertThatThrownBy(() -> tags.assignmentForTransition(fixture.transitionId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy( + () -> + capacity.readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + String terminalRows = sqlImage(); + assertThatThrownBy( + () -> + transfer.advance(original.source, original.status, transferClock.millis() + 5000L)) + .isInstanceOf(IllegalStateException.class); + assertThat(sqlImage()).isEqualTo(terminalRows); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(strings = {"missing", "binding", "ttl"}) + void abortedTransferCannotInstallWithMissingOrChangedRetainedFence(String fault) + throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var assignment = tags.assignmentForTransition(fixture.transitionId()); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + UUID id = transfer.advance(original.source, original.status, deadline()); + byte[] key = ascii(capacityKey(assignment)); + if (fault.equals("missing")) admin.del(key); + else if (fault.equals("binding")) admin.hset(key, ascii("binding"), ascii("changed")); + else admin.pexpire(key, 60_000L); + byte[] altered = + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key); + String retained = sqlImage(); + admin.pexpire(ascii(original.grant.key()), 0); + assertThatThrownBy(() -> installAbortedTransferSuccessor(transfer, original, id, CLOCK)) + .isInstanceOf(IllegalStateException.class); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(original.status); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT state FROM game_session_region_owner_transfer") + .get(0, String.class)) + .isEqualTo("FROZEN"); + assertThat(sqlImage()).isEqualTo(retained); + assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) + .containsExactly(altered); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void abortedCapturedOriginalRetainsPhysicalClosureBeforeSuccessorInstallation( + boolean closeBeforeAbort) throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + UUID id = + repository.within( + deadline(), ignored -> repository.begin(original.source, original.status)); + var captured = repository.within(deadline(), ignored -> repository.capture(id)); + assertThat(captured).hasSize(1); + if (closeBeforeAbort) + capacityOwner() + .closeOriginalAttempt(controlledCapacity.request(), controlledCapacity.reservation()); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + if (!closeBeforeAbort) + capacityOwner() + .closeOriginalAttempt(controlledCapacity.request(), controlledCapacity.reservation()); + var proof = + capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); + assertThat(proof.disposition()).isEqualTo("NOT_EXECUTED_AFTER_AUTHORIZATION"); + byte[] tombstone = + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( + admin, + ascii( + capacityKey(tags.assignmentForRetainedCapacityExecution(fixture.transitionId())))); + assertThat(transfer.advance(original.source, original.status, deadline())).isEqualTo(id); + admin.pexpire(ascii(original.grant.key()), 0); + var installed = installAbortedTransferSuccessor(transfer, original, id, CLOCK); + assertThat(installed.executorFence()).isGreaterThan(original.status.executorFence()); + assertThat( + receiver + .observeForRegionOwnerTransfer(id, 0, deadline()) + .regionOwnerTransferContext() + .controlState()) + .isEqualTo("COMPLETED"); + assertThat( + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation()) + .canonicalReadback()) + .containsExactly(proof.canonicalReadback()); + assertThat( + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image( + admin, + ascii( + capacityKey( + tags.assignmentForRetainedCapacityExecution(fixture.transitionId()))))) + .containsExactly(tombstone); + } + + private net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus + installAbortedTransferSuccessor( + CanonicalGameplayRegionOwnerTransferCoordinator transfer, + CanonicalGameplayRegionLeaseOwner.Installation original, + UUID transferId, + Clock transferClock) { + var identity = + new net.firedevops.firemud.common.runtime.RuntimeIdentity( + "game-session-service", + "aborted-original-successor", + "localhost", + transferClock.instant(), + "test", + "test", + "controlled-test-image"); + var leases = new CanonicalGameplayRegionLeaseRedisOwner(ownerClient, catalog); + var grant = + leases.acquire( + original.source, original.status.regionEpoch(), Duration.ofSeconds(30), identity); + leases.requireGrantScope(grant, original.source, original.status.regionEpoch(), identity); + var preparation = + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .findTimelinePreparation(original.source) + .orElseThrow(); + leases.verifyInitializedTimeline(grant, preparation); + leases.requireCurrent(grant); + var installed = + transfer.install( + transferId, + original.source, + original.status, + grant.tokenCorrelation(), + identity.service(), + identity.serviceInstanceId(), + transferClock.millis() + 5000L); + leases.requireCurrent(grant); + return installed; + } + @Test void physicalImageRetainsAbsoluteExpiryRatherThanOnlyItsPresence() { byte[] key = "physical-image-expiry".getBytes(StandardCharsets.US_ASCII); From 10240ff427ec9a8eed1dd44ac03f05831cacbb54 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 14:47:32 +1300 Subject: [PATCH 34/52] Allow bounded replica fsync in positive login composition proof --- .../InitialGameplayLoginContextRedisIntegrationTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 0c6aea2996..43fd728dc9 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 @@ -653,7 +653,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); From 72b9b4580adeaa44a8261dd35c2c44b02c84c953 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 15:24:15 +1300 Subject: [PATCH 35/52] Align capacity bridge lock ordering and prove physical predecessor refusal --- ...calGameplayBindingInventoryRepository.java | 8 +- ...GameplayRegionOwnerTransferRepository.java | 5 +- ...NewFinalAdmissionOwnerIntegrationTest.java | 30 +++- ...untimeStatusRepositoryIntegrationTest.java | 143 +++++++++++++++++- 4 files changed, 176 insertions(+), 10 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index d4e2ae7484..89f806a455 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 @@ -1218,6 +1218,9 @@ CanonicalGameplayBindingRegionBridgeObligation prepareRegionBridge( expectedEvidence.transition().transitionId(), expectedEvidence.candidate().bindingRef().bytes(), null); + // Region authorization locks region before transition; retain runtime-before-region + // ordering and never hold the transition while waiting for the current region owner. + requireCurrentRegionOwner(transaction, ownerStatus); CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = loadProvisionalCasEvidence( transaction, expectedEvidence.transition().transitionId(), true); @@ -1228,7 +1231,6 @@ CanonicalGameplayBindingRegionBridgeObligation prepareRegionBridge( if (!inputs.equals(currentInputs) || currentEvidence.expectedPrior() != null) { throw conflict("Region bridge source changed or is not a first-NEW transition"); } - requireCurrentRegionOwner(transaction, ownerStatus); Record regionRow = transaction.fetchOne( "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE", @@ -1301,6 +1303,9 @@ RegionBridgeAcknowledgement acknowledgeRegionBridge( prepared.transitionId(), expectedEvidence.candidate().bindingRef().bytes(), null); + // Region authorization locks region before transition; retain runtime-before-region + // ordering and never hold the transition while waiting for the current region owner. + requireCurrentRegionOwner(transaction, ownerStatus); CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = loadProvisionalCasEvidence(transaction, prepared.transitionId(), true); requireSameProvisionalOperation(expectedEvidence, currentEvidence); @@ -1310,7 +1315,6 @@ RegionBridgeAcknowledgement acknowledgeRegionBridge( if (!inputs.equals(currentInputs) || currentEvidence.expectedPrior() != null) { throw conflict("Region bridge sources changed before durable acknowledgement"); } - requireCurrentRegionOwner(transaction, ownerStatus); Record regionRow = transaction.fetchOne( "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 79e67a2c04..48ed47c9d8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -120,6 +120,9 @@ void requireFrozenOriginal( .transaction( configuration -> { var tx = DSL.using(configuration); + // Bridge retries take inventory before region. Retained tag validation below must + // join this transaction, so no separate connection waits behind our own clock lock. + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(tx); requireOldOwner(tx, source, prior); var row = current(tx, original.transferId(), true); if (!sourceDigest(source, prior).equals(row.get("source_digest", String.class))) @@ -634,7 +637,7 @@ private Item loadItem(DSLContext tx, UUID transferId, long ordinal, String execu .admissionAttemptId() .equals(row.get("admission_attempt_id", UUID.class))) throw unavailable(); var assignment = - tags.withCapacityExecutionDsl(sql()) + tags.withCapacityExecutionDsl(tx) .assignmentForRetainedCapacityExecution(execution.transitionId()); if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class))) throw unavailable(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index e9060099d6..7baffc353e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -1419,6 +1419,8 @@ private void delayedPredecessorAfterHandoff(boolean installAction) throws Except var entered = new java.util.concurrent.CountDownLatch(1); var release = new java.util.concurrent.CountDownLatch(1); var calls = new java.util.concurrent.atomic.AtomicInteger(); + var redisReply = new java.util.concurrent.CompletableFuture(); + var dispatchedAt = new java.util.concurrent.atomic.AtomicLong(); String action = installAction ? "INSTALL" : "FINAL"; RedisClient delayed = mock(RedisClient.class); when(delayed.connect(ByteArrayCodec.INSTANCE)) @@ -1430,7 +1432,9 @@ private void delayedPredecessorAfterHandoff(boolean installAction) throws Except action, entered, release, - calls)); + calls, + redisReply, + dispatchedAt)); try (var credential = new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); var raw = credential.template(); @@ -1478,11 +1482,16 @@ private void delayedPredecessorAfterHandoff(boolean installAction) throws Except frozenDeadline); assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); assertThat(CLOCK.millis()).isLessThan(frozenDeadline); + var fencedPhysical = physicalImage(); release.countDown(); + assertThat(redisReply.get(2, java.util.concurrent.TimeUnit.SECONDS)).isEqualTo(-1L); + assertThat(dispatchedAt.get()).isPositive().isLessThan(frozenDeadline); + assertThat(CLOCK.millis()).isLessThan(frozenDeadline); assertThatThrownBy(() -> old.get(2, java.util.concurrent.TimeUnit.SECONDS)) .isInstanceOf(java.util.concurrent.ExecutionException.class) .hasCauseInstanceOf(IllegalStateException.class); assertThat(calls.get()).isOne(); + assertThat(physicalImage()).isEqualTo(fencedPhysical); assertThat(admin.get(ascii(installation.sessionKey()))) .containsExactly(source.candidate().canonicalBytes()); assertThat( @@ -1508,7 +1517,9 @@ private static StatefulRedisConnection delayedConnection( String action, java.util.concurrent.CountDownLatch entered, java.util.concurrent.CountDownLatch release, - java.util.concurrent.atomic.AtomicInteger calls) { + java.util.concurrent.atomic.AtomicInteger calls, + java.util.concurrent.CompletableFuture redisReply, + java.util.concurrent.atomic.AtomicLong dispatchedAt) { var commands = actual.async(); Object delayedCommands = java.lang.reflect.Proxy.newProxyInstance( @@ -1520,14 +1531,21 @@ private static StatefulRedisConnection delayedConnection( && args[3] instanceof byte[][] values && values.length == 19 && action.equals(new String(values[17], StandardCharsets.US_ASCII))) { - calls.incrementAndGet(); entered.countDown(); - if (!release.await(4, java.util.concurrent.TimeUnit.SECONDS)) - throw new IllegalStateException("Delayed old invocation not released"); + if (!release.await(10, java.util.concurrent.TimeUnit.SECONDS)) + throw new AssertionError("Delayed old invocation not released to Redis"); Object[] original = args.clone(); original[0] = predecessorSha; try { - return method.invoke(commands, original); + dispatchedAt.set(CLOCK.millis()); + var reply = (io.lettuce.core.RedisFuture) method.invoke(commands, original); + calls.incrementAndGet(); + reply.whenComplete( + (value, failure) -> { + if (failure == null) redisReply.complete(value); + else redisReply.completeExceptionally(failure); + }); + return reply; } catch (java.lang.reflect.InvocationTargetException failure) { throw failure.getCause(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 1fd780c820..e47c9bd3cd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -470,6 +470,84 @@ void freezeHoldingRegionRowMakesActualAuthorizationWaitThenRefuseBeforeDispatch( } } + @Test + void acknowledgedBridgeRetryWaitsBeforeTransitionWhileAuthorizationOwnsRegion() throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), Clock.systemUTC()); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution); + var gate = new RegionRowLockGate(); + ExecutorService executor = Executors.newFixedThreadPool(2)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + Future authorization = + executor.submit( + () -> + proof + .capacity(gate.attach(proof.sql)) + .authorize( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline())); + gate.awaitLock(); + Future replay = executor.submit(proof::replayBridge); + try { + assertDatabaseWaitsFor(proof.sql, gate.backendPid()); + assertThat(replay.isDone()).isFalse(); + } finally { + gate.release(); + } + authorization.get(10, TimeUnit.SECONDS); + replay.get(10, TimeUnit.SECONDS); + assertThat(proof.executionState(proof.execution)).isEqualTo("AUTHORIZED"); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + } + } + + @Test + void frozenContinuationWaitsBeforeRegionWhileAcknowledgedBridgeOwnsInventory() throws Exception { + try (var gate = new InventoryRowLockGate(); + var proof = new TransferSqlProof(gate); + ExecutorService executor = Executors.newFixedThreadPool(2)) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var original = + proof + .transfers + .within(transferDeadline(), ignored -> proof.transfers.capture(id)) + .getFirst(); + String before = proof.transferImage(id); + gate.arm(); + Future replay = executor.submit(proof::replayBridge); + gate.awaitLock(); + Future continuation = + executor.submit( + () -> + proof.transfers.within( + transferDeadline(), + ignored -> { + proof.transfers.requireFrozenOriginal(original, proof.scope, proof.prior); + return null; + })); + try { + assertDatabaseWaitsFor(proof.sql, gate.backendPid()); + assertThat(continuation.isDone()).isFalse(); + } finally { + gate.release(); + } + replay.get(10, TimeUnit.SECONDS); + continuation.get(10, TimeUnit.SECONDS); + assertThat(proof.transferImage(id)).isEqualTo(before); + assertThat(proof.executionState(proof.execution)).isEqualTo("INSTALL_DISPATCHED"); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + } + } + @Test void competingTransferCreatorsAndLostBeginReplyKeepOneOriginalIntent() throws Exception { try (var proof = new TransferSqlProof(); @@ -850,6 +928,58 @@ public void close() { } } + /** Stops a real bridge transaction only after its inventory-clock lock was granted. */ + private static final class InventoryRowLockGate extends DefaultExecuteListener + implements AutoCloseable { + private final AtomicBoolean armed = new AtomicBoolean(); + private final AtomicInteger pid = new AtomicInteger(); + private final CountDownLatch locked = new CountDownLatch(1); + private final CountDownLatch resume = new CountDownLatch(1); + + void arm() { + armed.set(true); + } + + @Override + public void executeEnd(ExecuteContext context) { + String statement = context.sql(); + if (statement == null + || !statement.contains("game_session_canonical_binding_inventory_clock") + || !statement.contains("FOR UPDATE") + || !armed.compareAndSet(true, false)) return; + try (var query = context.connection().createStatement(); + var result = query.executeQuery("SELECT pg_backend_pid()")) { + assertThat(result.next()).isTrue(); + pid.set(result.getInt(1)); + locked.countDown(); + if (!resume.await(4, TimeUnit.SECONDS)) + throw new AssertionError("Inventory-row test gate was not released"); + } catch (java.sql.SQLException failure) { + throw new IllegalStateException("Could not observe actual inventory lock owner", failure); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Inventory-row test gate was interrupted", interrupted); + } + } + + void awaitLock() throws InterruptedException { + assertThat(locked.await(3, TimeUnit.SECONDS)).isTrue(); + } + + int backendPid() { + return pid.get(); + } + + void release() { + resume.countDown(); + } + + @Override + public void close() { + release(); + } + } + /** * Actual SQL, candidate/issuer/region and capacity/transfer owners over physical PostgreSQL and * Redis. Account lease/reservation/OPEN, World/Entity RPC content, grant and attestor custody are @@ -870,11 +1000,16 @@ private final class TransferSqlProof implements AutoCloseable { private final CanonicalGameplayRegionRuntimeStatusRepository.Source scope; private final CanonicalGameplayRegionRuntimeStatus prior; private final OriginalNewCapacityExecution execution; + private final CanonicalGameplayRegionOwnerCompositionFixture.ExistingBinding region; private CanonicalGameplayRegionOwnerTransferRepository transfers; private CanonicalGameplayProtectedIncarnationReceiver receiver; private CanonicalGameplayRegionOwnerTransferCoordinator coordinator; private TransferSqlProof() throws Exception { + this(new DefaultExecuteListener()); + } + + private TransferSqlProof(DefaultExecuteListener listener) throws Exception { String password = UUID.randomUUID().toString(); try (var administrator = RedisClient.create(RedisURI.create(REDIS.getHost(), REDIS.getMappedPort(6379))); @@ -950,6 +1085,7 @@ private TransferSqlProof() throws Exception { .dsl() .configuration() .deriveAppending( + listener, new DefaultExecuteListener() { @Override public void resultEnd(ExecuteContext context) { @@ -987,7 +1123,7 @@ public void resultEnd(ExecuteContext context) { fixture.acknowledgeOriginalIssuer(); new CanonicalGameplayAccountMemberRepairOwner(sql, redis, scripts) .repair(fixture.transitionId()); - var region = + region = CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate( sql, redis, @@ -1002,6 +1138,11 @@ public void resultEnd(ExecuteContext context) { recreateTransferOwners(); } + private void replayBridge() { + var replayed = region.owner().bridge(region.installation()); + assertThat(replayed.obligation()).isEqualTo(region.acknowledgement().obligation()); + } + private OriginalNewCapacityExecution newControlledExecution() { var controlled = CanonicalGameplayOriginalNewFinalAdmissionTestFixture.controlledCapacity( From 1b062efd5e09874d5e0aadfe7c63deeca48d5f14 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 15:49:30 +1300 Subject: [PATCH 36/52] Fix binary-key cleanup varargs in final admission integration tests --- ...GameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 7baffc353e..e71323f827 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -229,7 +229,7 @@ void abortedTransferCannotInstallWithMissingOrChangedRetainedFence(String fault) fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); UUID id = transfer.advance(original.source, original.status, deadline()); byte[] key = ascii(capacityKey(assignment)); - if (fault.equals("missing")) admin.del(key); + if (fault.equals("missing")) admin.del(java.util.List.of(key).toArray(byte[][]::new)); else if (fault.equals("binding")) admin.hset(key, ascii("binding"), ascii("changed")); else admin.pexpire(key, 60_000L); byte[] altered = @@ -368,7 +368,7 @@ void physicalImageRetainsAbsoluteExpiryRatherThanOnlyItsPresence() { admin.persist(key); assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) .isEqualTo(persistent); - admin.del(key); + admin.del(java.util.List.of(key).toArray(byte[][]::new)); assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) .isNotEqualTo(persistent); } From 742cbb827103edd8f439ff1ade47aa0bdbe34c93 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 15:57:32 +1300 Subject: [PATCH 37/52] Export physical image fixture for Account capacity composition proof --- ...alAdmissionCompositionIntegrationTest.java | 33 +++++++++++++++++++ .../game-session-service/build.gradle.kts | 1 + ...alNewFinalAdmissionCompositionFixture.java | 15 ++++++++- 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 1e0e6bfd17..cf321463f4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -341,6 +341,39 @@ void missingCapacityInputRefusesBeforeAnyFinalSessionOrReservationMutation() thr } } + @Test + void capacityStateImageDetectsTtlOnlyChangeAndMissingCapacityRefusalPreservesIt() + throws Exception { + try (Session session = session()) { + byte[] candidate = session.gs.physicalSession(); + var before = new java.util.TreeMap<>(session.gs.capacityStateImage()); + String changedKey = session.gs.setPhysicalSessionExpiryForFault(); + var after = new java.util.TreeMap<>(session.gs.capacityStateImage()); + assertThat(session.gs.physicalSession()).containsExactly(candidate); + assertThat(after.get(changedKey)).isNotEqualTo(before.get(changedKey)); + before.remove(changedKey); + after.remove(changedKey); + assertThat(after).isEqualTo(before); + + var physical = session.gs.capacityStateImage(); + String capacity = session.capacityImage(); + assertThatThrownBy( + () -> + session.gs.complete( + session.client, + session.jwks, + session.jwt, + System.currentTimeMillis() + 10_000L, + session.capacityClient, + null)) + .isInstanceOf(IllegalStateException.class); + assertThat(session.gs.capacityStateImage()).isEqualTo(physical); + assertThat(session.capacityImage()).isEqualTo(capacity); + assertThat(session.gs.physicalSession()).containsExactly(candidate); + assertThat(session.gs.finalReadCalls()).isZero(); + } + } + @Test void changedCatalogRevisionRefusesBeforeAccountCapacityCommitment() throws Exception { try (Session session = session()) { diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 7ca1e44b0f..0c3eec1698 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -187,6 +187,7 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture*.class") + include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalPublishedAdmissionActualOwnerCompositionFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledInitialObservationFixture*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledRegionTransferObservationFixture*.class") 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 bb4d8f52b0..2e7c6a013e 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 @@ -828,11 +828,24 @@ public java.util.Map capacityStateImage() { result.put( "redis:" + new String(key, StandardCharsets.UTF_8), net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution.sha256( - commands.dump(key))); + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(commands, key))); } return java.util.Map.copyOf(result); } + /** Controlled TTL-only fault used to prove the composition image observes absolute expiry. */ + public String setPhysicalSessionExpiryForFault() { + var commands = administration.sync(); + byte[] key = ascii(candidateInstallation.sessionKey()); + long expiresAt = Math.addExact(CLOCK.millis(), 60_000L); + if (commands.pexpiretime(key) != -1L + || !commands.pexpireat(key, expiresAt) + || commands.pexpiretime(key) != expiresAt) + throw new IllegalStateException( + "Expected a persistent candidate with only its expiry changed"); + return "redis:" + candidateInstallation.sessionKey(); + } + /** Controlled post-retention serving loss only, not proof of actual runtime teardown ordering. */ public void removeServingIndexesAfterCapacityRetentionForFault() { String state = From 94bece10818d8c9e84cf81d5d10467dca39ca67b Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Thu, 12 Nov 2026 17:06:43 +1300 Subject: [PATCH 38/52] test: preserve historical FINAL through native Account fencing --- ...NewFinalAdmissionOwnerIntegrationTest.java | 125 ++++++++++++++++++ 1 file changed, 125 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index e71323f827..626c0e833f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -1876,6 +1876,131 @@ void recreatedCapacityOwnerRetainsCommittedSqlBeforeServingCleanup() throws Exce .containsExactly(retained.canonicalReadback()); } + @Test + void actualFinalBeforeAccountFenceRetainsPhysicalPositiveButRecoveryRemainsIndeterminate() + throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var actual = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + // This is the real physical FINAL, not an injected SQL or Redis positive receipt. + byte[] finalBytes = admin.get(ascii(installation.sessionKey())); + assertThat(finalBytes).containsExactly(actual.exactCanonicalBytes()); + assertThat( + net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution.sha256( + finalBytes)) + .isEqualTo(actual.finalSessionSha256()); + var pending = + fixture + .dsl() + .fetchSingle( + "SELECT status, original_new_final_session_sha256 FROM game_session_canonical_binding_transition WHERE transition_id=?", + fixture.transitionId()); + assertThat(pending.get("status", String.class)).isEqualTo("PROVISIONAL"); + assertThat(pending.get("original_new_final_session_sha256", String.class)).isNull(); + // The crash window intentionally precedes SQL commit. Physical FINAL is positive evidence, + // but the Account-facing reader requires COMMITTED and must not expose it as final-readable. + String beforeReader = sqlImage(); + var physicalBeforeFence = physicalImage(); + assertThatThrownBy( + () -> reader().readActualOriginalFinalAdmission(credential.selector(), "test")) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("Original NEW transition is not final-readable"); + assertThat(sqlImage()).isEqualTo(beforeReader); + assertThat(physicalImage()).isEqualTo(physicalBeforeFence); + assertThat(inventory.readOriginalNewFinalAdmissionSource(decision).transitionStatus()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL); + var barrier = new CanonicalGameplayAccountAdmissionBarrierRepository(fixture.dsl()); + var intent = + barrier.beginFenceIntent( + source.candidate().bindingIdentity().accountId(), UUID.randomUUID()); + assertThat(intent.state().name()).isEqualTo("ACQUISITION_INTENT"); + assertThat(intent.cohortRows()) + .filteredOn( + row -> + row.kind() == CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.TRANSITION + && row.sourceKey().equals(fixture.transitionId().toString())) + .hasSize(1); + assertThat(physicalImage()).isEqualTo(physicalBeforeFence); + String rows = sqlImage(); + var physical = physicalImage(); + for (int attempt = 0; attempt < 2; attempt++) { + // Current authority deliberately cannot promote this historical positive through a + // newer frozen Account cohort. A future receipt-only recovery owner needs its own proof. + assertThatThrownBy( + () -> + new CanonicalGameplayBindingInventoryRepository(fixture.dsl()) + .commitOriginalNewFinalAdmission(actual)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("Account-fence acquisition intent blocks a new binding transition"); + assertThatThrownBy( + () -> + new CanonicalGameplayBindingInventoryRepository(fixture.dsl()) + .readOriginalNewFinalAdmissionSource(decision)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("Account-fence acquisition intent blocks a new binding transition"); + assertThatThrownBy( + () -> + capacityOwner() + .retainCommittedBeforeCleanup( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy( + () -> + capacityOwner() + .closeOriginalAttempt( + controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + // This remains the SQL-commit guard; the source/commit assertions above independently + // prove that the newer Account fence prevents reconciliation of the physical positive. + assertThatThrownBy( + () -> reader().readActualOriginalFinalAdmission(credential.selector(), "test")) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("Original NEW transition is not final-readable"); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(finalBytes); + var frozen = barrier.readCurrentFenceIntent(intent.operationId()); + assertThat(frozen.state()).isEqualTo(intent.state()); + assertThat(frozen.inventorySnapshotRevision()) + .isEqualTo(intent.inventorySnapshotRevision()); + assertThat(frozen.cohortDigest()).isEqualTo(intent.cohortDigest()); + assertThat(frozen.operationFence()).isEqualTo(intent.operationFence()); + assertThat(frozen.plannedAccountAdmissionFence()) + .isEqualTo(intent.plannedAccountAdmissionFence()); + assertThat(frozen.cohortRows()).usingRecursiveComparison().isEqualTo(intent.cohortRows()); + assertThat(frozen.barrierTargetDigest()).isEqualTo(intent.barrierTargetDigest()); + assertThat(frozen.barrierTargets()) + .usingRecursiveComparison() + .isEqualTo(intent.barrierTargets()); + } + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest=?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("AUTHORIZED"); + } + } + @Test void recreatedCapacityOwnerRecoversCommittedRedisWithoutOriginalCredentialOrGrant() throws Exception { From 5d640e1bc0ebc63f266c51cea24aaf81aa849c14 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:29:48 +1300 Subject: [PATCH 39/52] Retry serialized capacity commits and tighten evidence fixtures --- .../service/AccountTenantCapacityOwner.java | 26 ++- .../AccountTenantCapacityOwnerTest.java | 19 +++ .../test_capacity_admission_vectors.py | 15 +- ...ayOriginalNewAuthenticatedSessionTest.java | 157 ++++++++++-------- 4 files changed, 147 insertions(+), 70 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 99bb1e414d..48802ed7e3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -6,7 +6,9 @@ import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; import java.sql.Connection; +import java.sql.SQLException; import java.time.Clock; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -31,6 +33,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.jooq.DSLContext; import org.jooq.Record; +import org.springframework.dao.CannotSerializeTransactionException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -85,7 +88,7 @@ public AccountTenantCapacityOwner( public Result commit(Request request, String authenticatedCaller) { requireCaller(request, authenticatedCaller); request.requireStructurallyValid(); - return inTransaction( + return commitWithFreshSnapshot( () -> { lockPlayerAccount(request); Record existing = capacity.find(request.identity()); @@ -274,6 +277,27 @@ static void requireClaim(Record row, UUID owner, long fence, Instant now) { throw conflict(); } + private Result commitWithFreshSnapshot(Supplier action) { + try { + return inTransaction(action); + } catch (RuntimeException failure) { + // PostgreSQL has rolled back this serialization failure. The whole next transaction needs + // a new snapshot so a concurrent first attempt can become exact replay or conflict. + if (!serializationFailure(failure) || Context.current().isCancelled()) throw failure; + return inTransaction(action); + } + } + + private static boolean serializationFailure(RuntimeException failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof CannotSerializeTransactionException + || cause instanceof org.jooq.exception.DataAccessException jooq + && "40001".equals(jooq.sqlState()) + || cause instanceof SQLException sql && "40001".equals(sql.getSQLState())) return true; + } + return false; + } + T inTransaction(Supplier action) { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 8c196691af..a2c2f40578 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -7,11 +7,13 @@ import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.sql.Connection; +import java.sql.SQLException; import java.time.Clock; import java.time.ZoneOffset; import java.util.Map; @@ -100,6 +102,23 @@ void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void serializationFailureRetriesOnceAndReplaysInAFreshTransaction() throws Exception { + var f = new Fixture(true); + var aborted = + new org.jooq.exception.DataAccessException( + "concurrent reservation", new SQLException("serialization failure", "40001")); + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenThrow(aborted) + .thenReturn(Optional.of(new Account())); + + assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload()).reservationId()) + .isEqualTo(f.reservation); + verify(f.accounts, times(2)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + @Test void changedAttemptOrPayloadOrFenceConflictsBeforeAnyCurrentSourceOrUsageMutation() throws Exception { diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py index 877b98acf1..6aa871584f 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -60,13 +60,18 @@ def reject_duplicates(pairs): return result +def reject_nonfinite(token): + raise ValueError("non-finite JSON constant") + + def evidence(encoded, variant="TENANT_OPERATION"): raw = base64.b64decode(encoded, validate=True) if base64.b64encode(raw).decode("ascii") != encoded: raise ValueError("canonical padded base64 required") if not 0 < len(raw) <= 262144: raise ValueError("evidence bound") - parsed = json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=reject_duplicates) + parsed = json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=reject_duplicates, + parse_constant=reject_nonfinite) canonical = json.dumps(parsed, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8") if raw != canonical or parsed["schema"] != "account-auth-evidence-bundle/v1" or parsed["variant"] != variant: raise ValueError("exact canonical variant required") @@ -177,6 +182,14 @@ def test_rejected_evidence_candidates(self): for candidate in corpus["rejectedEvidence"]: with self.subTest(candidate["name"]), self.assertRaises(ValueError): evidence(candidate["canonicalAccountEvidenceBase64"]) + parsed = json.loads(base64.b64decode(corpus["request"]["canonicalAccountEvidenceBase64"])) + for token, constant in (("NaN", float("nan")), ("Infinity", float("inf")), + ("-Infinity", float("-inf"))): + with self.subTest(token), self.assertRaisesRegex(ValueError, "non-finite JSON constant"): + parsed["nonFinite"] = constant + raw = json.dumps(parsed, sort_keys=True, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + evidence(base64.b64encode(raw).decode("ascii")) # Shape/absence and usage expectations are separate from this encoding corpus: # CapacityAdmissionDigestTest and AccountTenantCapacityOwnerTest invoke their real owners. 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 2287685733..8f8df214ce 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 @@ -26,6 +26,9 @@ import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +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; @@ -341,25 +344,7 @@ private static void assertVerifierDenies(Fixture fixture) { private static CanonicalGameplayOriginalNewAuthenticatedSession.Template template( Fixture fixture) { - var original = - net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.playerRequest(); - var request = - new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( - new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity( - original.identity().tenantId(), - original.identity().requestId(), - fixture.candidate.bindingDecisionId()), - original.admissionAttemptId(), - original.capacityRearmFence(), - original.targetNamespace(), - original.context(), - original.operation(), - original.priorShape(), - original.requestedShape(), - original.evidence(), - original.capacityDelta(), - null) - .withDigest(); + var request = fixture.capacityRequest; var reservation = new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result( request.identity(), @@ -427,8 +412,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); @@ -446,11 +433,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, @@ -468,40 +455,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( @@ -527,7 +480,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"); @@ -555,14 +580,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", @@ -572,7 +590,7 @@ private static AccountGameplayAdmissionLeaseEvidence lease() { "membershipVersion", Map.of(TENANT_ID.toString(), "9"), "membershipAuthorityGeneration", - "3")); + capacityRequest.evidence().fields().get("membershipAuthorityGeneration"))); value.put("outboxCheckpoints", checkpoints()); value.put( "tokenIdentityEvidence", @@ -607,7 +625,7 @@ private static List> checkpoints() { "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", - suffix.startsWith("membership/") || suffix.startsWith("tenant/") ? "9" : "0")); + suffix.startsWith("membership/") ? "9" : suffix.startsWith("tenant/") ? "1" : "0")); } return List.copyOf(result); } @@ -730,16 +748,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; From f7d51937a4a81e9b235d1edb63024fb1c5a887ea Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:30:45 +1300 Subject: [PATCH 40/52] Resume completed region handoffs with the same live private grant --- .../game-session-service/runtime-and-data.md | 2 +- .../CanonicalGameplayRegionLeaseOwner.java | 161 +++++++++++++++--- ...ameplayRegionOwnerTransferCoordinator.java | 31 ++++ ...GameplayRegionOwnerTransferRepository.java | 26 +++ ...GameplayRegionRuntimeStatusRepository.java | 6 + ...NewFinalAdmissionOwnerIntegrationTest.java | 96 +++++++++++ 6 files changed, 300 insertions(+), 22 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 4094365ff0..5790324cb1 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -20,7 +20,7 @@ After the ordinary timeline/incarnation qualification and lost-completion checks The protected receiver has a separate `REGION_OWNER_TRANSFER` purpose and signed schema. Its actual SQL source binds the frozen transfer, original execution, immutable tenant-tag assignment and complete protected deployment/registry/ACL/configuration/storage/AOF identity. Nonce, signature, exact carrier, time and two-source-read checks apply to each observation. Before and after fencing, and around a complete streamed physical verification before owner installation, fresh purpose-correct observations must agree with the transfer's retained incarnation. Historical SQL receipts alone cannot qualify a missing marker or a changed, unavailable, reset, restored or rolled-back store. Verification never recreates a previously retained missing fence. An inventory which cannot be completely re-read within the operation deadline remains frozen rather than dropping the currentness requirement. Normal handoff does not authorize adoption across storage loss; the owning reset/recovery qualification remains required. -An observed `COMMITTED` hash is not a transfer exemption: the existing positive continuation must verify the complete serving/session/index outcome, persist any missing final SQL receipt and retain immutable `COMMITTED` evidence before that item is handled. Missing positive proof blocks transfer. Existing exact `CLOSED` evidence likewise follows the existing independent closure-retention path. Neither terminal record is overwritten. Only the privately constructed current fencing capability and complete locked inventory check permit the actual acquire/install/revalidate path to install the successor and immutable transfer completion in one transaction. The original attempts remain fenced and non-admitting. A completed transfer supports a separately phase-bound signed currentness read only while its immutable successor still matches the actual current region source; completed observations cannot enroll items, change receipts or authorize another installation. Loss of the original completion reply does not grant a fresh transfer or recreate a private lease handle. +An observed `COMMITTED` hash is not a transfer exemption: the existing positive continuation must verify the complete serving/session/index outcome, persist any missing final SQL receipt and retain immutable `COMMITTED` evidence before that item is handled. Missing positive proof blocks transfer. Existing exact `CLOSED` evidence likewise follows the existing independent closure-retention path. Neither terminal record is overwritten. Only the privately constructed current fencing capability and complete locked inventory check permit the actual acquire/install/revalidate path to install the successor and immutable transfer completion in one transaction. The original attempts remain fenced and non-admitting. A completed transfer supports a separately phase-bound signed currentness read only while its immutable successor still matches the actual current region source; completed observations cannot enroll items, change receipts or authorize another installation. If confirmation fails after SQL commits, the same process can use its retained live grant to recheck the exact completed successor and its retained physical fences before completing installation. A lost or expired grant leaves this continuation held. The original completion reply supplies no authority to recreate a grant or advance another transfer. An exact retained first-NEW Account-aborted original remains part of the transfer inventory, whether abort preceded capture or completed while the transfer was frozen. Its topology lookup verifies the retained definitive abort and existing immutable mapping without restoring provisional admission authority. First negative closure still requires the complete physical candidate/index proof; already-retained CLOSED replay uses its exact permanent tombstone. Unknown history remains fenced and indeterminate, never discarded because Account or SQL records an abort. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 42860566d9..a6d9a882ae 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 @@ -3,7 +3,6 @@ import java.math.BigInteger; import java.time.Clock; import java.time.Duration; -import java.time.Instant; import java.util.Arrays; import java.util.Objects; import java.util.Optional; @@ -313,26 +312,120 @@ Installation installForTransition( redisOwner.verifyInitializedTimeline(grant, preparation); if (transferOwner != null && clock.millis() >= handoffDeadline) throw unavailable(); - Instant installedAt = clock.instant(); - CanonicalGameplayRegionRuntimeStatus installed = - transferId == null - ? statusRepository.installOwner( - source, - expectedRegionEpoch, - prior, - grant.tokenCorrelation(), - grant.ownerService(), - grant.ownerInstanceId(), - installedAt) - : transferOwner.install( - transferId, - source, - prior, - grant.tokenCorrelation(), - grant.ownerService(), - grant.ownerInstanceId(), - handoffDeadline); + if (transferId == null) { + var installed = + statusRepository.installOwner( + source, + expectedRegionEpoch, + prior, + grant.tokenCorrelation(), + grant.ownerService(), + grant.ownerInstanceId(), + clock.instant()); + return verifyInstallation( + transitionId, + worldRequest, + evidence, + source, + incarnation, + preparation, + grant, + installed, + transferSource, + transferOwner, + handoffDeadline); + } + var pending = + new PendingTransfer( + this, + transferId, + transferOwner, + transitionId, + worldRequest, + evidence, + source, + incarnation, + preparation, + expectedRegionEpoch, + grant, + transferSource); + try { + var installed = + transferOwner.install( + transferId, + source, + prior, + grant.tokenCorrelation(), + grant.ownerService(), + grant.ownerInstanceId(), + handoffDeadline); + return verifyInstallation( + transitionId, + worldRequest, + evidence, + source, + incarnation, + preparation, + grant, + installed, + transferSource, + transferOwner, + handoffDeadline); + } catch (RuntimeException failure) { + throw new TransferCompletionUnconfirmed(pending, failure); + } + } + + /** + * Resumes only the same process's still-current grant after an unconfirmed transfer completion. + */ + Installation resumeCompletedTransfer( + TransferCompletionUnconfirmed interrupted, long absoluteDeadlineMillis) { + requireNoAmbientTransaction(); + var pending = Objects.requireNonNull(interrupted, "interrupted").pending; + if (pending == null || pending.owner() != this) throw unavailable(); + long deadline = Math.min(absoluteDeadlineMillis, Math.addExact(clock.millis(), 5_000L)); + if (clock.millis() >= deadline) throw unavailable(); + redisOwner.requireGrantScope( + pending.grant(), pending.source(), pending.expectedRegionEpoch(), runtimeIdentity); + redisOwner.requireCurrent(pending.grant()); + redisOwner.verifyInitializedTimeline(pending.grant(), pending.preparation()); + requireSameIncarnation(pending.incarnation(), readCurrentIncarnation(pending.source())); + var installed = + pending + .transferOwner() + .recoverCompleted( + pending.transferId(), + pending.grant().ownerInstanceId(), + pending.grant().tokenCorrelation(), + deadline); + if (clock.millis() >= deadline) throw unavailable(); + return verifyInstallation( + pending.transitionId(), + pending.worldRequest(), + pending.evidence(), + pending.source(), + pending.incarnation(), + pending.preparation(), + pending.grant(), + installed, + pending.transferSource(), + pending.transferOwner(), + deadline); + } + private Installation verifyInstallation( + UUID transitionId, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatus installed, + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource, + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + long handoffDeadline) { redisOwner.requireCurrent(grant); redisOwner.verifyInitializedTimeline(grant, preparation); CanonicalGameplayRegionRuntimeStatus observed = @@ -355,7 +448,9 @@ Installation installForTransition( worldRequest, evidence, transferSource, transferOwner, handoffDeadline)); CanonicalGameplayRegionRuntimeStatus finalStatus = statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); - if (!installed.equals(finalStatus) || finalStatus.paused()) throw unavailable(); + if (!installed.equals(finalStatus) + || finalStatus.paused() + || transferOwner != null && clock.millis() >= handoffDeadline) throw unavailable(); return new Installation( transitionId, worldRequest, evidence, source, incarnation, preparation, grant, installed); } @@ -927,6 +1022,30 @@ private static IllegalStateException unavailable() { "Canonical Game Session region owner requires current exact assignment and lease evidence"); } + private record PendingTransfer( + CanonicalGameplayRegionLeaseOwner owner, + UUID transferId, + CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, + UUID transitionId, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + long expectedRegionEpoch, + CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant, + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource transferSource) {} + + static final class TransferCompletionUnconfirmed extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final transient PendingTransfer pending; + + private TransferCompletionUnconfirmed(PendingTransfer pending, RuntimeException cause) { + super("Normal region handoff completion requires current exact verification", cause); + this.pending = pending; + } + } + /** Private construction prevents caller-created installation/readback objects. */ final class Installation { private final CanonicalGameplayRegionLeaseOwner owner; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java index 8c5247d97c..9970b94a02 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java @@ -167,6 +167,37 @@ CanonicalGameplayRegionRuntimeStatus install( }); } + /** Rechecks the exact completed successor. This path cannot enroll, fence or install. */ + CanonicalGameplayRegionRuntimeStatus recoverCompleted( + UUID transferId, String ownerInstance, String correlation, long deadline) { + return repository.within( + deadline, + budget -> { + var completed = repository.completedSuccessor(transferId, ownerInstance, correlation); + var page = repository.completedPage(transferId, -1); + if (page.isEmpty()) throw held(); + var first = page.getFirst(); + var before = observe(first, budget.absoluteDeadlineMillis()); + if (!before.incarnationDigest().equals(completed.incarnationDigest())) throw held(); + var owner = capacity.forTransferBudget(budget); + while (!page.isEmpty()) { + for (var item : page) { + budget.check(); + repository.requireRetainedPhysical( + item, owner.readTransferFence(item, budget.absoluteDeadlineMillis())); + } + page = repository.completedPage(transferId, page.getLast().ordinal()); + } + var after = observe(first, budget.absoluteDeadlineMillis()); + if (!after.incarnationDigest().equals(completed.incarnationDigest()) + || !completed.equals( + repository.completedSuccessor(transferId, ownerInstance, correlation))) { + throw held(); + } + return completed.status(); + }); + } + private CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observe( CanonicalGameplayRegionOwnerTransferRepository.Item item, long deadline) { var value = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 48ed47c9d8..5b12e8f5cc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -280,6 +280,32 @@ List capture(UUID transferId) { List page(UUID transferId, long afterOrdinal) { current(sql(), transferId, false); + return readPage(transferId, afterOrdinal); + } + + List completedPage(UUID transferId, long afterOrdinal) { + requireCompleted(transferId); + return readPage(transferId, afterOrdinal); + } + + CompletedTransfer completedSuccessor(UUID transferId, String ownerInstance, String correlation) { + Record completed = requireCompleted(transferId); + var status = CanonicalGameplayRegionRuntimeStatusRepository.toStatus(completed); + if (status.paused() + || !ownerInstance.equals(status.ownerInstanceId()) + || !correlation.equals(status.leaseTokenCorrelation())) throw unavailable(); + return new CompletedTransfer(status, completed.get("incarnation_digest", String.class)); + } + + private Record requireCompleted(UUID transferId) { + Record completed = observationCurrent(sql(), transferId); + if (!"COMPLETED".equals(completed.get("state", String.class))) throw unavailable(); + return completed; + } + + record CompletedTransfer(CanonicalGameplayRegionRuntimeStatus status, String incarnationDigest) {} + + private List readPage(UUID transferId, long afterOrdinal) { List result = new ArrayList<>(); for (Record row : sql() 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 decf04fdc3..a2797db79f 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 @@ -416,6 +416,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 = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 626c0e833f..7bef165e64 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -780,6 +780,102 @@ void authorizedUnknownHandoffKeepsOriginalCandidateAndRefusesCompletedMutation() assertThat(successor.status.ownerInstanceId()).isEqualTo("final-owner-handoff"); } + @Test + void completedTransferResumesOnlyWithTheSameLivePrivateGrant() throws Exception { + repairAccountMember(); + bridge(); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var failAfterCommit = new java.util.concurrent.atomic.AtomicBoolean(true); + var observationSource = + new CanonicalGameplayRegionOwnerTransferObservationSource() { + @Override + public Context readCurrent(UUID transferId, long targetOrdinal) { + var context = repository.readCurrent(transferId, targetOrdinal); + if ("COMPLETED".equals(context.controlState()) && failAfterCommit.getAndSet(false)) { + throw new IllegalStateException("Controlled completed observation failure"); + } + return context; + } + + @Override + public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository sourceTags) { + return repository.readAssignment(transitionId, sourceTags); + } + }; + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(observationSource, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + var identity = + new net.firedevops.firemud.common.runtime.RuntimeIdentity( + "game-session-service", + "final-owner-handoff", + "localhost", + CLOCK.instant(), + "test", + "test", + "controlled-test-image"); + CanonicalGameplayRegionIncarnationSource incarnation = + scope -> { + assertThat(scope).isEqualTo(original.incarnation.scope()); + return original.incarnation; + }; + var successor = + CanonicalGameplayRegionLeaseOwnerFactory.compose( + fixture.dsl(), + ownerClient, + catalog, + incarnation, + sources.resolver, + identity, + java.time.Duration.ofSeconds(30), + CLOCK); + admin.pexpire(ascii(original.grant.key()), 0); + var failure = + org.junit.jupiter.api.Assertions.assertThrows( + CanonicalGameplayRegionLeaseOwner.TransferCompletionUnconfirmed.class, + () -> + successor.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline())); + assertThat(failAfterCommit).isFalse(); + var durable = + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) + .find(original.source) + .orElseThrow(); + assertThat(durable.executorFence()).isGreaterThan(original.status.executorFence()); + var completed = + fixture + .dsl() + .fetchSingle("SELECT state, transfer_id FROM game_session_region_owner_transfer"); + assertThat(completed.get("state", String.class)).isEqualTo("COMPLETED"); + assertThatThrownBy( + () -> + successor.installForTransition( + null, original.transitionId, original.worldRequest, transfer, deadline())) + .isInstanceOf(IllegalStateException.class); + var recovered = successor.resumeCompletedTransfer(failure, deadline()); + assertThat(recovered.status).isEqualTo(durable); + assertThat(recovered.grant.tokenCorrelation()).isEqualTo(durable.leaseTokenCorrelation()); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT state, transfer_id FROM game_session_region_owner_transfer")) + .isEqualTo(completed); + var completedSql = sqlImage(); + assertThat(successor.resumeCompletedTransfer(failure, deadline()).status).isEqualTo(durable); + assertThat(sqlImage()).isEqualTo(completedSql); + admin.pexpire(ascii(recovered.grant.key()), 0); + assertThatThrownBy(() -> successor.resumeCompletedTransfer(failure, deadline())) + .isInstanceOf(IllegalStateException.class); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(durable); + } + @Test void retainedTransferFenceLossCannotBeReinstalledOrQualifyHandoff() throws Exception { repairAccountMember(); From 595d20db182014811a9eecd1f0eb7ab592fecb11 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:57:41 +1300 Subject: [PATCH 41/52] Close CLI review gaps in capacity custody and transfer proof --- .../game-session-service/runtime-and-data.md | 2 +- .../AccountTenantCapacityRepository.java | 13 +++- .../service/AccountTenantCapacityOwner.java | 10 ++- .../AccountTenantCapacityRecoveryWorker.java | 24 +++++++ .../AccountTenantCapacityGrpcService.java | 3 - ...tionCompletionPostgresIntegrationTest.java | 65 ++++++++++++++++- .../AccountTenantCapacityOwnerTest.java | 29 +++++++- .../AccountTenantCapacityGrpcServiceTest.java | 26 ++++++- ...playOriginalNewCapacityExecutionOwner.java | 25 +++++-- ...ayOriginalNewFinalAdmissionRedisOwner.java | 68 ++++++++++++++---- ...ameplayRegionOwnerTransferCoordinator.java | 4 +- ...GameplayRegionOwnerTransferRepository.java | 7 +- ...alGameplayTenantGameplayTagRepository.java | 22 ++++++ ...equire_current_capacity_dispatch_owner.sql | 71 +++++++++++++++++++ ...e-session-original-new-final-admission.lua | 17 +++-- ...-session-original-new-final-admission.json | 24 ++++++- ...alNewFinalAdmissionLuaIntegrationTest.java | 37 +++++----- ...NewFinalAdmissionOwnerIntegrationTest.java | 40 ++++++++++- ...untimeStatusRepositoryIntegrationTest.java | 3 + ...eFamilyCatalogPostgresIntegrationTest.java | 30 ++++---- ...riginalNewCapacityExecutionBudgetTest.java | 13 +++- ...nOwnerTransferObservationReceiverTest.java | 16 +++-- 22 files changed, 461 insertions(+), 88 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.1__require_current_capacity_dispatch_owner.sql diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 5790324cb1..02fae68589 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -16,7 +16,7 @@ The capacity execution owner uses one absolute budget for each complete operatio Game Session may exclude an unresolved original from future execution while its historical outcome remains indeterminate. This normal-handoff operation is separate from original-attempt closure, reservation recovery and cleanup. Its permanent tenant-slot `FENCED_INDETERMINATE` hash contains only the exact retained execution binding, digest and denying state. It may be created when the execution key is absent or replace the state of an exact persistent `AUTHORIZED` hash; neither action establishes that an earlier effect did not happen. The existing `INSTALL`, `FINAL` and `CLOSE` arms, including the predecessor script, reject that state. It never creates an authorization, session candidate, session or index, and supplies no `NOT_EXECUTED_AFTER_AUTHORIZATION` evidence. The Account reservation, original attempt/fence and complete capacity hold remain pending or quarantined under Account's existing recovery policy. -After the ordinary timeline/incarnation qualification and lost-completion checks, the contender must acquire the successor Redis grant before freezing the current generation. A still-renewing incumbent therefore rejects the contender without transfer or execution-fence mutation. Before freezing, the contender rechecks the exact source, protected incarnation, initialized timeline and current grant; after fencing it renews and revalidates the grant before protected installation. Grant acquisition does not replace the transfer proof. The handoff freezes one absolute deadline before inventory selection, capped at five seconds and the incoming deadline. Initial provisional/candidate selection, exact committed-source selection and every later installation source revalidation use that same deadline and the original inventory provider through the existing bounded resource worker. Each scoped SQL context owns its derived connection and transaction provider; blocked acquisition, query cancellation and uncertain release retain their existing custody rules. An expired read cannot authorize successor installation. Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The frozen generation refuses new dispatch markers, including through the database guard. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. +After the ordinary timeline/incarnation qualification and lost-completion checks, the contender must acquire the successor Redis grant before freezing the current generation. A still-renewing incumbent therefore rejects the contender without transfer or execution-fence mutation. Before freezing, the contender rechecks the exact source, protected incarnation, initialized timeline and current grant; after fencing it renews and revalidates the grant before protected installation. Grant acquisition does not replace the transfer proof. The handoff freezes one absolute deadline before inventory selection, capped at five seconds and the incoming deadline. Initial provisional/candidate selection, exact committed-source selection and every later installation source revalidation use that same deadline and the original inventory provider through the existing bounded resource worker. Each scoped SQL context owns its derived connection and transaction provider; blocked acquisition, query cancellation and uncertain release retain their existing custody rules. An expired read cannot authorize successor installation. Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The database dispatch guard locks the same runtime row and verifies the exact active selected owner. Both a frozen generation and the completed predecessor refuse new dispatch markers, including during the transaction that installs the successor. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. The protected receiver has a separate `REGION_OWNER_TRANSFER` purpose and signed schema. Its actual SQL source binds the frozen transfer, original execution, immutable tenant-tag assignment and complete protected deployment/registry/ACL/configuration/storage/AOF identity. Nonce, signature, exact carrier, time and two-source-read checks apply to each observation. Before and after fencing, and around a complete streamed physical verification before owner installation, fresh purpose-correct observations must agree with the transfer's retained incarnation. Historical SQL receipts alone cannot qualify a missing marker or a changed, unavailable, reset, restored or rolled-back store. Verification never recreates a previously retained missing fence. An inventory which cannot be completely re-read within the operation deadline remains frozen rather than dropping the currentness requirement. Normal handoff does not authorize adoption across storage loss; the owning reset/recovery qualification remains required. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java index 6c67a69c23..275bc5920a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -1,9 +1,11 @@ package net.firedevops.firemud.accountservice.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Clock; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Objects; import java.util.UUID; @@ -130,8 +132,9 @@ public void requirePriorHistory(Request prior, Request next) { || history.get("owner_readback", byte[].class) == null) throw conflict(); } - public Result create(Request request, Instant expiresAt) { + public Result create(Request request, Instant expiresAt, Clock clock) { Record usage = usage(request); + requireCurrentLifetime(request.evidence(), clock.instant()); long delta = Objects.requireNonNull(request.capacityDelta()); long occupied = Math.addExact(number(usage, "held_units"), number(usage, "used_units")); if (delta > request.evidence().quota() - occupied) @@ -161,6 +164,14 @@ public Result create(Request request, Instant expiresAt) { return exact(request, Objects.requireNonNull(find(request.identity()))); } + public static void requireCurrentLifetime(Evidence evidence, Instant now) { + // PostgreSQL stores microseconds. Floor the bound, never round an expiry forward. + if (now.isBefore(evidence.evaluatedAt()) + || !now.isBefore(evidence.expiresAt().truncatedTo(ChronoUnit.MICROS))) { + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + } + } + public void updateUsage(Request request, Record before, long held, long used) { transaction(); if (held < 0 || used < 0 || Math.addExact(held, used) < 0) throw unavailable(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 48802ed7e3..c42a5e6434 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -3,6 +3,7 @@ import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.number; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.requireCurrentLifetime; import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -11,7 +12,6 @@ import java.sql.SQLException; import java.time.Clock; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.Map; import java.util.Objects; import java.util.UUID; @@ -99,7 +99,7 @@ public Result commit(Request request, String authenticatedCaller) { requireSupportedShape(request); if (!request.evidence().permitsCreation()) throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); - return capacity.create(request, request.evidence().expiresAt()); + return capacity.create(request, request.evidence().expiresAt(), clock); }); } @@ -135,6 +135,7 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { || row.get("owner_readback", byte[].class) == null) throw conflict(); current(next); requireSupportedShape(next); + requireCurrentLifetime(next.evidence(), clock.instant()); int history = dsl.execute( "INSERT INTO account_tenant_capacity_attempt_history " @@ -178,10 +179,7 @@ private void current(Request request) { var evidence = request.evidence(); capacity.requireRetained(evidence); Instant now = clock.instant(); - // PostgreSQL stores microseconds. Floor the bound, never round an expiry forward. - if (now.isBefore(evidence.evaluatedAt()) - || !now.isBefore(evidence.expiresAt().truncatedTo(ChronoUnit.MICROS))) - throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + requireCurrentLifetime(evidence, now); if (!(request.context() instanceof PlayerContext player)) throw unavailable(); var parsed = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java index fca009081f..11997dbb02 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java @@ -13,10 +13,14 @@ import java.util.Arrays; import java.util.HexFormat; import java.util.Objects; +import java.util.Set; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; @@ -102,6 +106,7 @@ public String toString() { private final ExecutionReadClient source; private final Clock clock; private final UUID workerId = UUID.randomUUID(); + private final Set inFlight = ConcurrentHashMap.newKeySet(); public AccountTenantCapacityRecoveryWorker( AccountTenantCapacityOwner owner, DSLContext dsl, ExecutionReadClient source, Clock clock) { @@ -116,6 +121,11 @@ public AccountTenantCapacityRecoveryWorker( public Result reconcile(Request request, NoCommitAction noCommitAction) { Objects.requireNonNull(noCommitAction); request.requireCommittable(); + return withExclusiveOperation( + request.identity(), () -> reconcileClaim(request, noCommitAction)); + } + + private Result reconcileClaim(Request request, NoCommitAction noCommitAction) { Claim claim = claim(request); if (claim.reservation().state() != State.RESERVED) return claim.reservation(); if (claim.noCommitProof() != null) { @@ -274,6 +284,10 @@ private void moveUsage(Request request, boolean committed) { public Result rearm(Request prior, Request next) { prior.requireCommittable(); next.requireCommittable(); + return withExclusiveOperation(prior.identity(), () -> rearmClaim(prior, next)); + } + + private Result rearmClaim(Request prior, Request next) { java.util.Optional replay = owner.inTransaction( () -> { @@ -291,6 +305,16 @@ public Result rearm(Request prior, Request next) { return owner.rearm(prior, next, workerId, claim.fence()); } + private Result withExclusiveOperation(Identity identity, Supplier operation) { + // This worker can advance its own live claim for a sequential retry or rearm. + if (!inFlight.add(identity)) throw unavailable(); + try { + return operation.get(); + } finally { + inFlight.remove(identity); + } + } + private Claim claim(Request request) { return owner.inTransaction( () -> { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index 7af0c6ad42..22a326f5f3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -88,9 +88,6 @@ public void commitTenantCapacityAdmission( | org.springframework.transaction.TransactionException unavailable) { observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); return; - } catch (IllegalArgumentException | ArithmeticException ownerEvidence) { - observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); - return; } catch (RuntimeException internal) { observer.onError(Status.INTERNAL.asRuntimeException()); return; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 421d4c6c0f..784a2fa95f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -25,6 +25,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; @@ -57,11 +58,13 @@ import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountTenantCreationAdmissionRepository.Admitted; import net.firedevops.firemud.accountservice.service.session.AccountTenantCreationIntentRepository.OriginalIntent; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; @@ -409,6 +412,63 @@ void capacityOwnerPersistenceFinalizesOneOriginalReservationAndUsageExactlyOnce( .isEqualTo(17); } + @Test + void overlappingRecoveryCallsCannotInvalidateTheSameWorkersLiveClaim() throws Exception { + var f = capacityPersistenceFixture(); + var next = + new TenantCapacityAdmission.Request( + f.request.identity(), + UUID.randomUUID(), + f.request.capacityRearmFence() + 1, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(); + var readStarted = new CountDownLatch(1); + var resumeRead = new CountDownLatch(1); + var calls = new AtomicInteger(); + var recovery = + new AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + if (calls.incrementAndGet() == 1) { + readStarted.countDown(); + try { + assertThat(resumeRead.await(10, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("Interrupted while waiting to resume read", interrupted); + } + } + return capacityObservation( + request, reservation, AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED); + }, + Clock.fixed(Instant.now(), ZoneOffset.UTC)); + var action = AccountTenantCapacityRecoveryWorker.NoCommitAction.RELEASE; + try (var executor = Executors.newSingleThreadExecutor()) { + var pending = executor.submit(() -> recovery.reconcile(f.request, action)); + try { + assertThat(readStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> recovery.reconcile(f.request, action)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> recovery.rearm(f.request, next)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + } finally { + resumeRead.countDown(); + } + var result = pending.get(10, TimeUnit.SECONDS); + assertThat(result.state()).isEqualTo(TenantCapacityAdmission.State.FINALIZED); + assertThat(recovery.reconcile(f.request, action)).isEqualTo(result); + assertThat(calls).hasValue(1); + } + } + @Test void capacityIndeterminateReadbackCannotReleaseAndTerminalNoCommitReleasesSameHold() { var f = capacityPersistenceFixture(); @@ -786,7 +846,10 @@ private static CapacityPersistenceFixture capacityPersistenceFixture(boolean exp .at(evidence.evaluatedAt()), net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository .at(evidence.expiresAt())); - return repository.create(request, evidence.expiresAt()); + return repository.create( + request, + evidence.expiresAt(), + Clock.fixed(evidence.evaluatedAt(), ZoneOffset.UTC)); }); var owner = new net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index a2c2f40578..58751d1b71 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -80,7 +80,10 @@ void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throw assertThatThrownBy( () -> new AccountTenantCapacityRepository(dsl) - .create(request, request.evidence().expiresAt())) + .create( + request, + request.evidence().expiresAt(), + Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC))) .as(vector.path("name").asText()) .hasMessage(vector.path("expected").asText()); verify(dsl, never()).execute(anyString(), any(Object[].class)); @@ -91,6 +94,30 @@ void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throw } } + @Test + void expiryWhileWaitingForUsageDoesNotReserveCapacity() { + var request = CapacityAdmissionTestFixture.playerRequest(); + DSLContext dsl = mock(DSLContext.class); + Clock clock = mock(Clock.class); + when(clock.instant()).thenThrow(new AssertionError("read before acquiring usage row")); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + org.mockito.Mockito.doReturn(request.evidence().expiresAt()).when(clock).instant(); + return mock(Record.class); + }); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + new AccountTenantCapacityRepository(dsl) + .create(request, request.evidence().expiresAt(), clock)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + @Test void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index abf683a4b8..052e448105 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -15,6 +15,7 @@ import java.util.stream.Stream; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; @@ -53,8 +54,7 @@ void malformedWireAndStructurallyInvalidRequestsRefuseBeforeOwner() { @ParameterizedTest @MethodSource("ownerEvidenceFailures") - void retainedOwnerParseEnumAndArithmeticFailuresAreEntitlementUnavailable( - RuntimeException cause) { + void unexpectedOwnerFailuresAreSanitizedInternal(RuntimeException cause) { var request = CapacityAdmissionTestFixture.playerRequest(); try (var guards = authenticatedCaller()) { AccountTenantCapacityOwner owner = mock(); @@ -65,11 +65,31 @@ void retainedOwnerParseEnumAndArithmeticFailuresAreEntitlementUnavailable( .commitTenantCapacityAdmission( TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); - assertFailure(observer, Failure.ENTITLEMENT_UNAVAILABLE); + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + assertThat(Status.fromThrowable(error.getValue())).isEqualTo(Status.INTERNAL); + assertThat(error.getValue().getCause()).isNull(); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); verify(owner).commit(request, CapacityAdmissionTestFixture.PEER); } } + @Test + void typedOwnerEvidenceUnavailableKeepsItsPublicFailure() { + var request = CapacityAdmissionTestFixture.playerRequest(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) + .thenThrow(new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE)); + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + assertFailure(observer, Failure.ENTITLEMENT_UNAVAILABLE); + } + } + private static Stream ownerEvidenceFailures() { return Stream.of( new NumberFormatException("Controlled retained billing parse failure"), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 6411504847..7bf0f01b87 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -1,5 +1,13 @@ package net.firedevops.firemud.gamesession.repository; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_AUTHORIZED; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_AUTHORIZED_OBSERVED; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_CLOSED; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_CLOSED_OBSERVED; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_COMMITTED_OBSERVED; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_FENCED_INDETERMINATE; +import static net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED; + import io.lettuce.core.RedisClient; import io.lettuce.core.RedisFuture; import io.lettuce.core.api.StatefulRedisConnection; @@ -174,6 +182,7 @@ void authorize( return; } budget.check(); + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.requireExecutionBinding(source, execution); var assignment = scopedTags().assignmentForTransition(execution.transitionId()); boolean dispatch = sql() @@ -237,7 +246,9 @@ void authorize( execution, "INSTALL", budget.absoluteDeadlineMillis()); - if (result != 3) throw unavailable(); + if (result != CAPACITY_EXECUTION_AUTHORIZED + && result != CAPACITY_EXECUTION_AUTHORIZED_OBSERVED + && result != CAPACITY_EXECUTION_COMMITTED_OBSERVED) throw unavailable(); } Map physical = readExecution(execution, assignment.tenantGameplayTag()); String state = text(physical.get("state")); @@ -315,11 +326,12 @@ public void closeOriginalAttempt(Request request, Result reservation) { scopedFinalOwner() .closeCapacityExecutionOnce( execution, candidate, assignment, budget.absoluteDeadlineMillis()); - if (result == 2) { + if (result == CAPACITY_EXECUTION_COMMITTED_OBSERVED) { retainCommittedBeforeCleanup(request, reservation, budget.absoluteDeadlineMillis()); throw unavailable(); } - if (result != 4) throw unavailable(); + if (result != CAPACITY_EXECUTION_CLOSED && result != CAPACITY_EXECUTION_CLOSED_OBSERVED) + throw unavailable(); Map physical = readExecution(execution, assignment.tenantGameplayTag()); exactPhysicalBinding(physical, execution, "CLOSED"); requireCandidateAndIndexes(row, candidate, null, execution); @@ -627,16 +639,17 @@ TransferFence fenceForTransfer( scopedFinalOwner() .fenceCapacityExecutionOnce( execution, item.candidate(), item.assignment(), budget.absoluteDeadlineMillis()); - if (result == 2) { + if (result == CAPACITY_EXECUTION_COMMITTED_OBSERVED) { // Merely seeing a COMMITTED hash must not release old-generation custody. retainCommittedBeforeCleanup(execution.request(), execution.reservation(), deadline); - } else if (result == 4) { + } else if (result == CAPACITY_EXECUTION_CLOSED_OBSERVED) { if ("CLOSED".equals(row.get("status", String.class))) { readExact(execution.request(), execution.reservation(), false); } else { closeOriginalAttempt(execution.request(), execution.reservation()); } - } else if (result != 5) throw unavailable(); + } else if (result != CAPACITY_EXECUTION_FENCED_INDETERMINATE + && result != CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED) throw unavailable(); return readTransferFence(item, deadline); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index a3f4184d04..eff8c0bfda 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -42,6 +42,14 @@ * issuer flow. */ final class CanonicalGameplayOriginalNewFinalAdmissionRedisOwner { + static final long CAPACITY_EXECUTION_AUTHORIZED = 3L; + static final long CAPACITY_EXECUTION_CLOSED = 4L; + static final long CAPACITY_EXECUTION_FENCED_INDETERMINATE = 5L; + static final long CAPACITY_EXECUTION_AUTHORIZED_OBSERVED = 6L; + static final long CAPACITY_EXECUTION_CLOSED_OBSERVED = 7L; + static final long CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED = 8L; + static final long CAPACITY_EXECUTION_COMMITTED_OBSERVED = 9L; + private static final String PRINCIPAL = "gamesession_coord_app"; private static final int MAX_SCRIPT_BYTES = 48 * 1024; private static final int MAX_BARRIER_JSON_BYTES = 16 * 1024; @@ -114,6 +122,22 @@ final class CanonicalGameplayOriginalNewFinalAdmissionRedisOwner { "CAPACITY_EXECUTION_FENCED_INDETERMINATE", RedisScriptDescriptor.OutcomeCategory.SUCCESS, RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "CAPACITY_EXECUTION_AUTHORIZED_OBSERVED", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "CAPACITY_EXECUTION_CLOSED_OBSERVED", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "CAPACITY_EXECUTION_COMMITTED_OBSERVED", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), outcome( "CURRENT_PHYSICAL_STATE_REFUSED", RedisScriptDescriptor.OutcomeCategory.STALE, @@ -186,6 +210,7 @@ Readback finalizeOriginalNewOnce( CanonicalGameplayOriginalNewAuthenticatedSession.Finalized finalized = null; try { CanonicalGameplayOriginalNewCandidate candidate = requireSource(source); + requireExecutionBinding(source, execution); CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = tenantTags.assignmentForTransition(candidate.transition().transitionId()); requireAssignment(assignment, candidate); @@ -309,10 +334,7 @@ Readback readCommittedForRetention( OriginalNewCapacityExecution execution) { requireNoAmbientTransaction(); var candidate = requireSource(source); - if (!candidate.transition().transitionId().equals(execution.transitionId()) - || !source.candidateDigest().equals(execution.candidateDigest()) - || execution.selectedOwnerFence() - != source.regionAcknowledgement().executorFence().longValueExact()) throw unavailable(); + requireExecutionBinding(source, execution); var assignment = tenantTags.assignmentForTransition(execution.transitionId()); requireAssignment(assignment, candidate); String accountKey = @@ -329,11 +351,7 @@ Readback readCommittedForRetention( CanonicalGameplayOriginalNewAuthenticatedSession.Finalized finalized = null; try { finalized = CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized(bytes, clock); - if (!candidate.equals(finalized.candidate()) - || !execution - .digest() - .equals(JSON.readTree(bytes).get("capacityExecutionDigest").textValue())) - throw unavailable(); + if (!candidate.equals(finalized.candidate())) throw unavailable(); Readback readback = new Readback(source, finalized, execution); finalized = null; return readback; @@ -361,12 +379,7 @@ long fenceCapacityExecutionOnce( long absoluteDeadlineMillis) { requireNoAmbientTransaction(); requireAssignment(assignment, candidate); - if (!candidate.bindingDecisionId().equals(execution.transitionId()) - || !candidate.bindingIdentity().tenantId().equals(execution.request().identity().tenantId()) - || !execution - .candidateDigest() - .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(candidate.canonicalBytes()))) - throw unavailable(); + requireExecutionBinding(candidate, execution); String accountKey = ACCOUNT_PREFIX + "{" @@ -405,6 +418,7 @@ long closeCapacityExecutionOnce( long absoluteDeadlineMillis) { requireNoAmbientTransaction(); requireAssignment(assignment, candidate); + requireExecutionBinding(candidate, execution); String accountKey = ACCOUNT_PREFIX + "{" @@ -447,6 +461,7 @@ long dispatchCapacityAction( requireNoAmbientTransaction(); if (!"INSTALL".equals(action)) throw unavailable(); var candidate = requireSource(source); + requireExecutionBinding(source, execution); var assignment = tenantTags.assignmentForTransition(candidate.transition().transitionId()); requireAssignment(assignment, candidate); Keys keys = requireKeys(candidate, assignment, accountOpen.key(), execution); @@ -477,6 +492,25 @@ long dispatchCapacityAction( } } + static void requireExecutionBinding( + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, + OriginalNewCapacityExecution execution) { + requireExecutionBinding(source.candidate(), execution); + if (!source.candidateDigest().equals(execution.candidateDigest()) + || execution.selectedOwnerFence() + != source.regionAcknowledgement().executorFence().longValueExact()) throw unavailable(); + } + + private static void requireExecutionBinding( + CanonicalGameplayOriginalNewCandidate candidate, OriginalNewCapacityExecution execution) { + if (!candidate.bindingDecisionId().equals(execution.transitionId()) + || !candidate.bindingIdentity().tenantId().equals(execution.request().identity().tenantId()) + || !execution + .candidateDigest() + .equals(CanonicalGameplayIssuerMemberV2Codec.sha256(candidate.canonicalBytes()))) + throw unavailable(); + } + private CanonicalGameplayOriginalNewCandidate requireSource( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source) { CanonicalGameplayOriginalNewCandidate candidate = source.candidate(); @@ -1116,6 +1150,10 @@ private Readback( this.session = Objects.requireNonNull(session, "finalized session"); byte[] exact = session.canonicalBytes(); try { + if (!execution + .digest() + .equals(JSON.readTree(exact).get("capacityExecutionDigest").textValue())) + throw unavailable(); this.finalSessionSha256 = digest("SHA-256", exact); } finally { wipe(exact); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java index 9970b94a02..74733c8f83 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java @@ -162,7 +162,9 @@ CanonicalGameplayRegionRuntimeStatus install( observations.observeForRegionOwnerTransfer( transferId, first.getFirst().ordinal(), budget.absoluteDeadlineMillis()); if (!after.incarnationDigest().equals(completed.incarnationDigest())) throw held(); - owner.readTransferFence(first.getFirst(), budget.absoluteDeadlineMillis()); + repository.requireRetainedPhysical( + first.getFirst(), + owner.readTransferFence(first.getFirst(), budget.absoluteDeadlineMillis())); return installed; }); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 5b12e8f5cc..c32431c434 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -244,7 +244,10 @@ List capture(UUID transferId) { var execution = decode(retained.get("canonical_execution", byte[].class)); ordinal = Math.incrementExact(ordinal); String tag = retained.get("tenant_gameplay_tag", String.class); - int allocation = Integer.parseInt(tag.substring(1, tag.indexOf('-'))); + String namespace = execution.request().targetNamespace(); + int allocation = + tags.requireRetainedAllocation( + tx, execution.request().identity().tenantId(), tag, namespace); tx.execute( "INSERT INTO " + ITEM @@ -255,7 +258,7 @@ List capture(UUID transferId) { execution.canonicalBytes(), execution.candidateDigest(), tag, - execution.request().targetNamespace(), + namespace, allocation); } }); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index 96d077c0eb..9e99ca8152 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -96,6 +96,28 @@ Assignment assignmentForRetainedCapacityExecution(UUID transitionId) { }); } + /** Reads the immutable allocation without changing the transfer's region-lock order. */ + int requireRetainedAllocation( + DSLContext transaction, UUID tenantId, String expectedTag, String expectedNamespace) { + if (!workloadNamespace.equals(expectedNamespace)) { + throw conflict("Retained capacity execution workload namespace differs"); + } + Record mapping = + transaction.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + + MAPPING + + " WHERE tenant_id = ?", + tenantId); + if (mapping == null || !expectedTag.equals(mapping.get("tenant_gameplay_tag", String.class))) { + throw conflict("Retained capacity execution mapping is unavailable"); + } + Integer version = mapping.get("allocation_version", Integer.class); + if (version == null || !tagFor(tenantId, version).equals(expectedTag)) { + throw conflict("Retained capacity execution allocation differs"); + } + return version; + } + /** Topology-only retained lookup for one irreversibly selected original negative continuation. */ Assignment assignmentForOriginalNewAbandonment(UUID transitionId, UUID abandonmentId) { requireNonNil(transitionId, "transitionId"); diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.1__require_current_capacity_dispatch_owner.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.1__require_current_capacity_dispatch_owner.sql new file mode 100644 index 0000000000..c623c8f285 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.1__require_current_capacity_dispatch_owner.sql @@ -0,0 +1,71 @@ +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION fence_gs_capacity_dispatch_during_transfer() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE scope RECORD; current_owner RECORD; +BEGIN + SELECT DISTINCT tenant_id,game_instance_id,region_id INTO STRICT scope + FROM game_session_canonical_binding_region_bridge_obligation WHERE transition_id=NEW.transition_id; + SELECT r.owner_instance_id,r.executor_fence,r.owner_service,r.paused INTO current_owner + FROM game_session_region_runtime_status r + WHERE r.tenant_id=scope.tenant_id AND r.game_instance_id=scope.game_instance_id AND r.region_id=scope.region_id + FOR UPDATE; + IF NOT FOUND OR scope.tenant_id IS DISTINCT FROM NEW.tenant_id + OR current_owner.owner_service IS DISTINCT FROM 'game-session-service' + OR current_owner.paused IS DISTINCT FROM false + OR current_owner.owner_instance_id IS DISTINCT FROM NEW.selected_owner_id + OR current_owner.executor_fence IS DISTINCT FROM NEW.selected_owner_fence THEN + RAISE EXCEPTION 'Region dispatch requires the exact current selected owner' USING ERRCODE='23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_session_region_owner_transfer t WHERE t.tenant_id=scope.tenant_id + AND t.game_instance_id=scope.game_instance_id AND t.region_id=scope.region_id AND t.state='FROZEN') THEN + RAISE EXCEPTION 'Region dispatch is frozen for normal owner transfer' USING ERRCODE='23514'; + END IF; + -- A single owner transaction records completion before changing the runtime row. The + -- completed predecessor cannot acquire a dispatch in between those two durable writes. + IF EXISTS (SELECT 1 FROM game_session_region_owner_transfer t WHERE t.tenant_id=scope.tenant_id + AND t.game_instance_id=scope.game_instance_id AND t.region_id=scope.region_id AND t.state='COMPLETED' + AND t.old_owner_id=NEW.selected_owner_id AND t.old_owner_fence=NEW.selected_owner_fence) THEN + RAISE EXCEPTION 'Completed region predecessor cannot acquire dispatch' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + -- Insert before the existing final clause so later origin/receipt migrations retain their + -- exact forward anchors at the last current catalog frontier. + original := $needle$WHERE version='1064' + ) AND ($needle$; + replacement := $replacement$WHERE version='1064' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.1__require_current_capacity_dispatch_owner.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.1' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1064'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.1'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1064','V1064__restore_final_human_completion_lower_bound.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.1'',''V1065.0.1__require_current_capacity_dispatch_owner.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua index f903e14e90..21ea5bff33 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua @@ -123,12 +123,12 @@ if action == 'FENCE' then if fields ~= 6 or type(sessionSha1) ~= 'string' or #sessionSha1 ~= 40 or not string.match(sessionSha1, '^[0-9a-f]+$') or not admissionAt or not continuity or continuity <= admissionAt or continuity - admissionAt > 300000 then return -1 end - return 2 + return 9 end if fields ~= 3 then return -1 end -- Completed exact outcomes are read-only, even after the operation deadline. - if state == 'FENCED_INDETERMINATE' then return 5 end - if state == 'CLOSED' then return 4 end + if state == 'FENCED_INDETERMINATE' then return 8 end + if state == 'CLOSED' then return 7 end if state ~= 'AUTHORIZED' then return -1 end end local fenceTime = redis.call('TIME') @@ -153,8 +153,8 @@ if action == 'CLOSE' then or redis.call('HGET', KEYS[7], 'binding') ~= capacityBytes or redis.call('HGET', KEYS[7], 'digest') ~= capacityDigest then return -1 end local state = redis.call('HGET', KEYS[7], 'state') - if state == 'CLOSED' and redis.call('HLEN', KEYS[7]) == 3 then return 4 end - if state == 'COMMITTED' and redis.call('HLEN', KEYS[7]) == 6 then return 2 end + if state == 'CLOSED' and redis.call('HLEN', KEYS[7]) == 3 then return 7 end + if state == 'COMMITTED' and redis.call('HLEN', KEYS[7]) == 6 then return 9 end if state ~= 'AUTHORIZED' or redis.call('HLEN', KEYS[7]) ~= 3 or redis.call('TYPE', KEYS[1]).ok ~= 'string' or redis.call('PTTL', KEYS[1]) ~= -1 or redis.call('GET', KEYS[1]) ~= candidateBytes @@ -256,11 +256,14 @@ if capacityType ~= 'hash' or redis.call('PTTL', KEYS[7]) ~= -1 or redis.call('HGET', KEYS[7], 'binding') ~= capacityBytes or redis.call('HGET', KEYS[7], 'digest') ~= capacityDigest then return -1 end local capacityState = redis.call('HGET', KEYS[7], 'state') -if capacityState == 'CLOSED' then return 4 end +if capacityState == 'CLOSED' then return 7 end if capacityState ~= 'AUTHORIZED' and capacityState ~= 'COMMITTED' then return -1 end if (capacityState == 'AUTHORIZED' and redis.call('HLEN', KEYS[7]) ~= 3) or (capacityState == 'COMMITTED' and redis.call('HLEN', KEYS[7]) ~= 6) then return -1 end -if action == 'INSTALL' then return 3 end +if action == 'INSTALL' then + if capacityState == 'AUTHORIZED' then return 6 end + return 9 +end local observed = redis.call('GET', KEYS[1]) if observed ~= candidateBytes then diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json index 9ea8d50009..d87f69ca05 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.original-new-final-admission.v1", "resourcePath": "redis/lua/game-session-original-new-final-admission.lua", - "sha256": "0ed090df2d591f1d9001f812ce0ffe23a9de2916c17423834f7ced02bb6fbcc9", + "sha256": "d6e268e1bbe91255f82714646f4051eee9424da1949fa806a1a431d21096c427", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", @@ -128,6 +128,26 @@ "category": "SUCCESS", "effect": "MUTATING" }, + { + "code": "CAPACITY_EXECUTION_AUTHORIZED_OBSERVED", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "CAPACITY_EXECUTION_CLOSED_OBSERVED", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "CAPACITY_EXECUTION_FENCED_INDETERMINATE_OBSERVED", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "CAPACITY_EXECUTION_COMMITTED_OBSERVED", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, { "code": "CURRENT_PHYSICAL_STATE_REFUSED", "category": "STALE", @@ -141,7 +161,7 @@ ], "resetSensitivity": "CLUSTER", "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", - "tailLossBehavior": "Missing capacity execution remains historically indeterminate and cannot be reinstalled as AUTHORIZED by retry. Under separately qualified current-incarnation normal owner handoff only, FENCE creates or retains an exact persistent FENCED_INDETERMINATE deny, excluding delayed INSTALL/FINAL without claiming no earlier execution, permitting reset adoption, or authorizing Account release/rearm. FENCE preserves exact COMMITTED and CLOSED outcomes; first mutation must meet the frozen Redis TIME deadline and completed exact replay is read-only. CLOSED is irreversible and fences every delayed same-attempt FINAL. Account alone consumes exact terminal evidence to mutate capacity. A missing or changed candidate, tenant index, OPEN barrier, or Redis state fails closed for admission. Exact final retry is read-only and preserves the first Redis TIME values; the script never repairs indexes, recreates barriers, transfers a controller, or claims that the supplied OPEN sources establish the complete admission flow. The owner returns evidence only after independent exact physical readback. Reset-sensitive state requires its owning recovery before the final consumer can proceed.", + "tailLossBehavior": "Missing capacity execution remains historically indeterminate. The owner commits SQL INSTALL dispatch custody before the first submission and only inspects Redis on retry, so a lost hash is never reinstalled by the owner. Under separately qualified current-incarnation normal owner handoff only, FENCE creates or retains an exact persistent FENCED_INDETERMINATE deny, excluding delayed INSTALL/FINAL without claiming no earlier execution, permitting reset adoption, or authorizing Account release/rearm. FENCE preserves exact COMMITTED and CLOSED outcomes. First mutation must meet the frozen Redis TIME deadline and completed exact replay is read-only. CLOSED is irreversible and fences every delayed same-attempt FINAL. INSTALL, CLOSE and FENCE may report a read-only COMMITTED hash observation. Only FINAL's exact replay verifies the finalized session against its template in Lua. The owner returns evidence only after independent exact physical readback. Account alone consumes exact terminal evidence to mutate capacity. A missing or changed candidate, tenant index, OPEN barrier, or Redis state fails closed for admission. Exact final retry preserves the first Redis TIME values. The script never repairs indexes, recreates barriers, transfers a controller, or claims that the supplied OPEN sources establish the complete admission flow. Reset-sensitive state requires its owning recovery before the final consumer can proceed.", "compatibilityLevel": "REQUIRES_CLUSTER_RESET", "supportedCoexistence": [ { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java index 1c5efd647e..df3f56920e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java @@ -357,7 +357,7 @@ void absentExecutionFenceInstallsOnlyTheExactPersistentDenyWithoutRecreatingRunt assertPhysicalImage(original, before, 6); Map denied = physicalImage(original); - assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(5L); + assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(8L); assertPhysicalImage(original, denied, 7); } @@ -367,6 +367,8 @@ void authorizedFenceChangesOnlyStateAndEveryDelayedCurrentOrPinnedOldCallRefuses ScriptCase original = seed(); Map before = physicalImage(original); + assertThat(eval(action(original, "INSTALL"))).isEqualTo(6L); + assertPhysicalImage(original, before, 7); assertThat(eval(action(original, "FENCE"))).isEqualTo(5L); assertHash(original.keys()[6], capacityPhysicalFields(original, "FENCED_INDETERMINATE")); assertPhysicalImage(original, before, 6); @@ -378,8 +380,8 @@ void authorizedFenceChangesOnlyStateAndEveryDelayedCurrentOrPinnedOldCallRefuses assertThat(eval(action(original, "INSTALL"))).isEqualTo(-1L); assertThat(eval(original)).isEqualTo(-1L); assertThat(eval(action(original, "CLOSE"))).isEqualTo(-1L); - assertThat(eval(action(original, "FENCE"))).isEqualTo(5L); - assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(5L); + assertThat(eval(action(original, "FENCE"))).isEqualTo(8L); + assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(8L); assertPhysicalImage(original, denied, 7); for (String key : original.keys()) assertThat(admin.pttl(ascii(key))).isEqualTo(-1L); } @@ -403,12 +405,13 @@ void finalBeforeFencePreservesEveryCommittedByteHashAndControllerTimeIncludingEx assertThat(eval(original)).isEqualTo(1L); Map committed = physicalImage(original); - assertThat(eval(action(original, "FENCE"))).isEqualTo(2L); - assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(2L); + assertThat(eval(action(original, "INSTALL"))).isEqualTo(9L); + assertThat(eval(action(original, "FENCE"))).isEqualTo(9L); + assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(9L); byte[][] credentialFree = action(original, "FENCE").arguments().clone(); credentialFree[11] = ascii("1"); - assertThat(eval(new ScriptCase(original.keys(), credentialFree))).isEqualTo(2L); - assertThat(eval(expired(new ScriptCase(original.keys(), credentialFree)))).isEqualTo(2L); + assertThat(eval(new ScriptCase(original.keys(), credentialFree))).isEqualTo(9L); + assertThat(eval(expired(new ScriptCase(original.keys(), credentialFree)))).isEqualTo(9L); assertThat(eval(preFenceScriptSha, original)).isEqualTo(2L); assertPhysicalImage(original, committed, 7); assertThat(admin.hlen(ascii(original.keys()[6]))).isEqualTo(6L); @@ -421,8 +424,8 @@ void alreadyClosedFenceIsReadOnlyAndNeverReclassifiesTheHistoricalOutcome() thro assertThat(eval(action(original, "CLOSE"))).isEqualTo(4L); Map closed = physicalImage(original); - assertThat(eval(action(original, "FENCE"))).isEqualTo(4L); - assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(4L); + assertThat(eval(action(original, "FENCE"))).isEqualTo(7L); + assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(7L); assertPhysicalImage(original, closed, 7); assertHash(original.keys()[6], capacityPhysicalFields(original, "CLOSED")); } @@ -749,7 +752,7 @@ void lostFinalReplyReplaysTheActualSessionHashAndControllerTimesWithoutNegativeC .containsExactly(ascii(HexFormatHolder.sha1(actual))); byte[][] expiredClose = action(original, "CLOSE").arguments().clone(); expiredClose[14] = ascii(Long.toString(System.currentTimeMillis() - 1L)); - assertThat(eval(new ScriptCase(original.keys(), expiredClose))).isEqualTo(2L); + assertThat(eval(new ScriptCase(original.keys(), expiredClose))).isEqualTo(9L); assertThat(eval(original)).isEqualTo(2L); assertThat(admin.get(ascii(original.keys()[0]))).containsExactly(actual); assertThat(admin.hget(ascii(original.keys()[6]), ascii("admissionAt"))) @@ -784,7 +787,7 @@ void expiredCloseCannotMutateButFreshClosureAndExpiredReplayRemainAvailable() th assertThat(eval(new ScriptCase(original.keys(), fresh))).isEqualTo(4L); execution.put("state", ascii("CLOSED")); assertHash(original.keys()[6], execution); - assertThat(eval(late)).isEqualTo(4L); + assertThat(eval(late)).isEqualTo(7L); assertHash(original.keys()[6], execution); assertThat(admin.get(ascii(original.keys()[0]))).containsExactly(original.arguments()[8]); } @@ -795,9 +798,9 @@ void permanentClosureSurvivesLostReplyAndPreventsEveryDelayedSameAttemptFinal() eval(action(original, "CLOSE")); // Lose the successful reply deliberately. assertThat(admin.hget(ascii(original.keys()[6]), ascii("state"))) .containsExactly(ascii("CLOSED")); - assertThat(eval(action(original, "CLOSE"))).isEqualTo(4L); - assertThat(eval(action(original, "INSTALL"))).isEqualTo(4L); - assertThat(eval(original)).isEqualTo(4L); + assertThat(eval(action(original, "CLOSE"))).isEqualTo(7L); + assertThat(eval(action(original, "INSTALL"))).isEqualTo(7L); + assertThat(eval(original)).isEqualTo(7L); assertThat(admin.get(ascii(original.keys()[0]))).containsExactly(original.arguments()[8]); assertThat(admin.hlen(ascii(original.keys()[6]))).isEqualTo(3L); } @@ -832,17 +835,17 @@ void concurrentFinalAndIrreversibleClosureHaveExactlyOneDecisiveWinner() throws long finalResult = finalized.get(5, java.util.concurrent.TimeUnit.SECONDS); long closeResult = closed.get(5, java.util.concurrent.TimeUnit.SECONDS); if (finalResult == 1L) { - assertThat(closeResult).isEqualTo(2L); + assertThat(closeResult).isEqualTo(9L); assertThat(admin.hget(ascii(original.keys()[6]), ascii("state"))) .containsExactly(ascii("COMMITTED")); assertThat(eval(original)).isEqualTo(2L); assertThat(admin.hget(ascii(original.keys()[6]), ascii("sessionSha1"))) .containsExactly(ascii(HexFormatHolder.sha1(admin.get(ascii(original.keys()[0]))))); } else { - assertThat(finalResult).isEqualTo(4L); + assertThat(finalResult).isEqualTo(7L); assertThat(closeResult).isEqualTo(4L); assertThat(admin.get(ascii(original.keys()[0]))).containsExactly(original.arguments()[8]); - assertThat(eval(original)).isEqualTo(4L); + assertThat(eval(original)).isEqualTo(7L); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 7bef165e64..d288e43fe1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -651,6 +651,40 @@ void transferFenceRejectsChangedCandidateDigestBeforeSubmittingRedis() throws Ex assertThat(physicalImage()).isEqualTo(physical); } + @Test + void changedExecutionCandidateRefusesBeforeCreatingSqlDispatchCustody() throws Exception { + repairAccountMember(); + bridge(false); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var changed = + new net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution( + controlledCapacity.request(), + controlledCapacity.reservation(), + controlledCapacity.transitionId(), + "sha256:" + "0".repeat(64), + controlledCapacity.selectedOwnerId(), + controlledCapacity.selectedOwnerFence()); + var sqlBefore = sqlImage(); + var physicalBefore = physicalImage(); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template()) { + assertThatThrownBy( + () -> + capacityOwner() + .authorize( + source, + template, + controlledAccountOpen(), + issuerOpen(), + changed, + deadline())) + .isInstanceOf(IllegalStateException.class); + } + assertThat(sqlImage()).isEqualTo(sqlBefore); + assertThat(physicalImage()).isEqualTo(physicalBefore); + } + @Test void processStopAfterActualSqlAuthorizationBeforeRedisSendFencesUnknownAndActuallyHandsOff() throws Exception { @@ -966,7 +1000,8 @@ else if (fault.equals("type")) { admin.del(keysToDelete); admin.set(key, ascii("wrong-type")); } else admin.hset(key, ascii("binding"), ascii("{}")); - byte[] physical = admin.dump(key); + byte[] physical = + CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key); admin.pexpire(ascii(original.grant.key()), 0); assertThatThrownBy( () -> @@ -979,7 +1014,8 @@ else if (fault.equals("type")) { transfer, deadline())) .isInstanceOf(IllegalStateException.class); - assertThat(admin.dump(key)).containsExactly(physical); + assertThat(CanonicalGameplayOriginalNewFinalAdmissionPhysicalImageFixture.image(admin, key)) + .containsExactly(physical); assertThat( new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()) .find(original.source) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index e47c9bd3cd..74f1ded699 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -742,6 +742,9 @@ void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throw var installed = proof.install(id); String completed = proof.transferImage(id); assertSqlGuard(() -> proof.rawReplaceOwner("different-successor", "f".repeat(64))); + assertThatThrownBy(() -> proof.seedUndeliveredDispatch(proof.newControlledExecution())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Region dispatch requires the exact current selected owner"); assertThat(proof.currentOwner()).isEqualTo(installed); assertThat(proof.transferImage(id)).isEqualTo(completed); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 4eb9ec7675..a8c0998997 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(9); + assertThat(catalog.catalogEpoch()).isEqualTo(10); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -188,7 +188,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1062", "catalog-installation:1063", "catalog-installation:1064", - "catalog-installation:1065") + "catalog-installation:1065", + "catalog-installation:1065.0.1") .noneMatch( identity -> identity.contains(":1057:") @@ -199,7 +200,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1062:") || identity.contains(":1063:") || identity.contains(":1064:") - || identity.contains(":1065:")); + || identity.contains(":1065:") + || identity.contains(":1065.0.1:")); assertThat( f.dsl .fetchSingle( @@ -742,7 +744,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(9); + assertThat(original.catalog().catalogEpoch()).isEqualTo(10); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -785,7 +787,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow assertThat(f.evidence(original.request())) .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); assertThat(f.count(SNAPSHOTS)).isEqualTo(1); - assertThat(f.count(EPOCHS)).isEqualTo(9); + assertThat(f.count(EPOCHS)).isEqualTo(original.catalog().catalogEpoch()); } } } @@ -877,7 +879,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } for (String version : - List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065")) { + List.of( + "1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065", "1065.0.1")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -905,7 +908,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } for (String version : - List.of("1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065")) { + List.of( + "1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065", "1065.0.1")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -926,12 +930,12 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip try (Fixture f = fixture(null)) { var original = f.owner().capture(request()); f.addComponent(); - for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 11}) { + for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12}) { assertThatThrownBy(() -> f.installEpoch(invalid)) .hasMessageContaining("exact classified installed schema"); } // Controlled explicit owner revision, not an exposed registry/runtime mutation API. - f.installEpoch(10); + f.installEpoch(11); assertThatThrownBy(() -> f.owner().capture(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().readExact(original.request())) @@ -939,9 +943,9 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip assertThat(f.evidence(original.request())) .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().capture(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(10); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(11); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count(EPOCHS)).isEqualTo(10); + assertThat(f.count(EPOCHS)).isEqualTo(11); } } @@ -978,9 +982,9 @@ void metadataEpochAndSnapshotGuardsRefuseMutationStaleBytesAndChangedExactSqlFra "INSERT INTO " + EPOCHS + "(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 10,catalog_bytes,catalog_digest FROM " + + " SELECT 11,catalog_bytes,catalog_digest FROM " + EPOCHS - + " WHERE catalog_epoch=9")) + + " WHERE catalog_epoch=10")) .hasMessageContaining("exact classified installed schema"); assertThatThrownBy( () -> 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 7fd0aac9a9..a622986aa6 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 @@ -410,6 +410,7 @@ void blockedAcquisitionsKeepAllFourSlotsAfterCallerTimeoutAndRejectWithoutQueuei }); DSLContext source = source(provider); var callers = new ArrayList>(); + var executor = Executors.newFixedThreadPool(maximum); try { for (int index = 0; index < maximum; index++) callers.add( @@ -421,7 +422,8 @@ void blockedAcquisitionsKeepAllFourSlotsAfterCallerTimeoutAndRejectWithoutQueuei CLOCK, CLOCK.millis() + 300, budget -> execute(budget.sql(source)))) - .isInstanceOf(IllegalStateException.class))); + .isInstanceOf(IllegalStateException.class), + executor)); assertThat(entered.await(2, TimeUnit.SECONDS)).isTrue(); CompletableFuture.allOf(callers.toArray(CompletableFuture[]::new)).get(2, TimeUnit.SECONDS); assertThatThrownBy( @@ -433,6 +435,7 @@ void blockedAcquisitionsKeepAllFourSlotsAfterCallerTimeoutAndRejectWithoutQueuei verifyNoInteractions(connection); } finally { release.countDown(); + executor.shutdownNow(); verify(provider, timeout(2000).times(maximum)).release(connection); } } @@ -458,6 +461,7 @@ void backgroundSaturationReservesAdmissionCapacityWithoutExceedingCombinedFourSl }); DSLContext source = source(provider); var callers = new ArrayList>(); + var executor = Executors.newFixedThreadPool(maximum); try { for (int index = 0; index < backgroundMaximum; index++) callers.add( @@ -469,7 +473,8 @@ void backgroundSaturationReservesAdmissionCapacityWithoutExceedingCombinedFourSl CLOCK, CLOCK.millis() + 1000, budget -> execute(budget.sql(source)))) - .isInstanceOf(IllegalStateException.class))); + .isInstanceOf(IllegalStateException.class), + executor)); assertThat(backgroundEntered.await(2, TimeUnit.SECONDS)).isTrue(); var refused = new AtomicBoolean(); assertThatThrownBy( @@ -497,7 +502,8 @@ void backgroundSaturationReservesAdmissionCapacityWithoutExceedingCombinedFourSl CLOCK, CLOCK.millis() + 1000, budget -> execute(budget.sql(source)))) - .isInstanceOf(IllegalStateException.class))); + .isInstanceOf(IllegalStateException.class), + executor)); assertThat(allEntered.await(2, TimeUnit.SECONDS)).isTrue(); CompletableFuture.allOf(callers.toArray(CompletableFuture[]::new)).get(2, TimeUnit.SECONDS); // Callers timed out, but blocked acquisition still owns all four permits. @@ -510,6 +516,7 @@ void backgroundSaturationReservesAdmissionCapacityWithoutExceedingCombinedFourSl verifyNoInteractions(connection); } finally { release.countDown(); + executor.shutdownNow(); verify(provider, timeout(2000).times(maximum)).release(connection); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java index 6a329f07e4..c973960ce6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationReceiverTest.java @@ -34,6 +34,10 @@ class CanonicalGameplayRegionOwnerTransferObservationReceiverTest { private static final String KEY_ID = "controlled-transfer-key"; private static final String DIGEST = "sha256:" + "a".repeat(64); private static final String OTHER_DIGEST = "sha256:" + "e".repeat(64); + private static final String TRANSFER_INTENT_DIGEST = "sha256:" + "1".repeat(64); + private static final String FROZEN_SOURCE_DIGEST = "sha256:" + "2".repeat(64); + private static final String EXECUTION_DIGEST = "sha256:" + "3".repeat(64); + private static final String CANDIDATE_DIGEST = "sha256:" + "4".repeat(64); private static final long NOW = 1_794_355_200_000L; private static final JsonMapper JSON = JsonMapper.builder().build(); private static final KeyPair KEYS = controlledKeys(); @@ -46,6 +50,10 @@ void verifiesExactFrozenItemTwiceWithRealSignatureAndCapsAtOperationDeadline() { assertThat(proof.ownerKind()) .isEqualTo(CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER); assertThat(proof.regionOwnerTransferContext()).isSameAs(fixture.original); + assertThat(fixture.original.transferIntentDigest()).isEqualTo(TRANSFER_INTENT_DIGEST); + assertThat(fixture.original.frozenSourceDigest()).isEqualTo(FROZEN_SOURCE_DIGEST); + assertThat(fixture.original.executionDigest()).isEqualTo(EXECUTION_DIGEST); + assertThat(fixture.original.candidateDigest()).isEqualTo(CANDIDATE_DIGEST); assertThat(proof.operationId()).isEqualTo(fixture.original.transferId()); assertThat(proof.requestId()).isEqualTo(fixture.original.requestId()); assertThat(proof.accountId()).isEqualTo(fixture.original.accountId()); @@ -687,8 +695,8 @@ private Fixture(String ownerId, String controlState, String completionDigest) { new CanonicalGameplayRegionOwnerTransferObservationSource.Context( UUID.randomUUID(), 3L, - DIGEST, - DIGEST, + TRANSFER_INTENT_DIGEST, + FROZEN_SOURCE_DIGEST, ownerId, 7L, tenant, @@ -699,8 +707,8 @@ private Fixture(String ownerId, String controlState, String completionDigest) { UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), - DIGEST, - DIGEST, + EXECUTION_DIGEST, + CANDIDATE_DIGEST, "g1-" + tenant.toString().replace("-", ""), "test-workload", 1, From ea92f492ecd448ae1686eba847cbaa3f1916e654 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:31:03 +1300 Subject: [PATCH 42/52] Retain the verified final admission receipt and execution outcome atomically --- .../game-session-service/runtime-and-data.md | 2 +- dev-tools/evidence_digest.py | 20 ++- ...acityMigrationPostgresIntegrationTest.java | 116 +++++++++++++- .../test_capacity_admission_vectors.py | 34 +++- ...calGameplayBindingInventoryRepository.java | 75 +++++++-- ...playOriginalNewCapacityExecutionOwner.java | 91 +++++++---- ...yOriginalNewFinalAdmissionCoordinator.java | 7 +- ...alNewFinalAdmissionLuaIntegrationTest.java | 3 + ...NewFinalAdmissionOwnerIntegrationTest.java | 145 +++++++++++++++++- 9 files changed, 426 insertions(+), 67 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 02fae68589..e95f76f1b1 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -8,7 +8,7 @@ The seven-key tenant-slot final script atomically serializes `FINAL` against per The finalized schema-2 reader requires `capacityExecutionDigest`; predecessor finalized values without it are unsupported by this unregistered preproduction cutover. Before activation or reuse of predecessor-populated storage, establish and resolve retained-data and active original-confirmation or recovery obligations while preserving immutable historical evidence. The [owning tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records this cutover limitation and the unknown inventory of earlier manually persisted data. -Positive SQL terminal retention follows actual persistent session/index/atomic-outcome and final-receipt verification. That retained result survives later serving-index retirement. Retained negative replay requires the already-verified immutable SQL CLOSED proof, full original identity, exact persistent Redis CLOSED tombstone, absence of contradictory final SQL receipt/state and a fresh actual current-owner observation. Serving-index absence is never negative evidence. Missing tombstones and closure before SQL proof retention remain indeterminate. The credential-free owner-local continuation independently verifies an already-committed tenant-slot effect and persists any missing final SQL receipt before retaining terminal evidence. The existing original-attempt closure entry point invokes that positive reconciliation before refusing negative closure; it does not need the original LOGIN, credential, live grant or fresh OPEN barriers, and it never dispatches a new final effect. Serving retirement must wait for retained positive evidence or independently retained exact closure. Capacity authorization locks and checks the durable region owner before creating dispatch custody; ordinary owner replacement takes that same lock and refuses unresolved installation or authorization unless the normal-handoff evidence below is complete. Lease expiry alone never satisfies this gate. The coordinator revalidates its grant immediately before final dispatch and preserves verified positive receipt/retention before a later currentness failure can withhold success. The existing never-admitted cleanup owner accepts only untouched PREPARED dispatches; cleanup of this already-acknowledged PROVISIONAL final-admission boundary and finalized-usage retirement on real runtime teardown remain separate unfinished Account/owner work. No default owner, receiver, recovery scheduler or source custody is registered by this slice. +The Game Session owner verifies the actual persistent session, indexes and atomic Redis outcome before committing the positive SQL terminal evidence and final admission receipt in one transaction. That retained result survives later serving-index retirement. Retained negative replay requires the already-verified immutable SQL CLOSED proof, full original identity, exact persistent Redis CLOSED tombstone, absence of contradictory final SQL receipt/state and a fresh actual current-owner observation. Serving-index absence is never negative evidence. Missing tombstones and closure before SQL proof retention remain indeterminate. The credential-free owner-local continuation independently verifies an already-committed tenant-slot effect and commits any missing final SQL receipt with its terminal evidence. A previously committed receipt without retained terminal evidence still requires exact physical proof before retention. The existing original-attempt closure entry point invokes that positive reconciliation before refusing negative closure; it does not need the original LOGIN, credential, live grant or fresh OPEN barriers, and it never dispatches a new final effect. Serving retirement must wait for retained positive evidence or independently retained exact closure. Capacity authorization locks and checks the durable region owner before creating dispatch custody; ordinary owner replacement takes that same lock and refuses unresolved installation or authorization unless the normal-handoff evidence below is complete. Lease expiry alone never satisfies this gate. The coordinator revalidates its grant immediately before final dispatch and preserves verified positive receipt/retention before a later currentness failure can withhold success. The existing never-admitted cleanup owner accepts only untouched PREPARED dispatches; cleanup of this already-acknowledged PROVISIONAL final-admission boundary and finalized-usage retirement on real runtime teardown remain separate unfinished Account/owner work. No default owner, receiver, recovery scheduler or source custody is registered by this slice. The capacity execution owner uses one absolute budget for each complete operation: the earlier incoming gRPC or explicit coordinator deadline, capped at five seconds. Its local SQL connection provider and transaction provider derive from the existing configuration without changing shared datasource settings. Four resource operations are admitted without a waiting queue. Public Account recovery reads and transfer operations share a two-operation sublimit inside that same four-operation ceiling, preserving two slots for final admission even when background work is saturated. Both limits remain held until the admitted resource and cancellation workers finish; uncertain release retains both permits. Acquisition, SQL and cleanup stay in the admitted worker; cancellation requests the active JDBC statement's cancellation, while a late acquisition cannot execute SQL. Statement close and pool return detach the statement under the same monitor as cancellation. A blocked driver cancellation or acquisition retains its admission slot until it exits. A throwing pool return preserves uncertain connection ownership and retains the slot rather than blindly retrying or claiming disposal. The JVM-wide Micrometer gauge `original_new_capacity_sql_release_failure_retained_operations`, exposed through the existing Prometheus actuator path, counts retained operation slots once per affected operation, even if several connections fail to return. A nonzero value identifies lost local admission capacity; four retained slots exhaust this SQL boundary. Investigate the provider failure before a controlled process restart. Restart recovers local admission slots only and supplies no reservation or selected-owner outcome proof. JDBC query timeouts back up cancellation; neither cancellation nor deadline return proves driver termination or an owner outcome. The separate four-slot Redis connector, scoped capacity INSTALL/CLOSE writes and all successive Redis commands consume the same remaining operation budget. INSTALL and the first CLOSE mutation carry that operation's frozen absolute deadline, enforced by Redis time; completed CLOSE replay remains read-only. Other final-admission callers retain their existing connection and command policy. diff --git a/dev-tools/evidence_digest.py b/dev-tools/evidence_digest.py index 19ad420d04..9020866943 100644 --- a/dev-tools/evidence_digest.py +++ b/dev-tools/evidence_digest.py @@ -7,12 +7,12 @@ from typing import Any -def canonical_evidence_digest(record: dict[str, Any]) -> str: - """Hash a record, excluding only its top-level immutableArtifactId field. +def canonical_json_bytes(value: Any) -> bytes: + """Encode the restricted RFC 8785 evidence subset as canonical UTF-8 bytes. - Nested immutableArtifactId occurrences remain part of the canonical payload. + Evidence records intentionally reject floating-point values and integers outside + the interoperable range rather than applying JavaScript number rounding. """ - payload = {key: value for key, value in record.items() if key != "immutableArtifactId"} def encode(value: Any) -> str: if value is None: @@ -38,5 +38,15 @@ def encode(value: Any) -> str: return "[" + ",".join(encode(nested) for nested in value) + "]" raise TypeError(f"unsupported evidence value type: {type(value).__name__}") - encoded = encode(payload).encode("utf-8") + return encode(value).encode("utf-8") + + +def canonical_evidence_digest(record: dict[str, Any]) -> str: + """Hash a record, excluding only its top-level immutableArtifactId field. + + Nested immutableArtifactId occurrences remain part of the canonical payload. + """ + payload = {key: value for key, value in record.items() if key != "immutableArtifactId"} + + encoded = canonical_json_bytes(payload) return f"sha256:{hashlib.sha256(encoded).hexdigest()}" diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 5eaa18c30a..7f67a85b2e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -2,10 +2,22 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; import org.jooq.SQLDialect; @@ -34,7 +46,7 @@ static void stop() { } @Test - void existingTenantStaysUninitializedAndAPlainNewImportCannotInitializeCapacity() { + void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { String schema = "capacity_migration_" + UUID.randomUUID().toString().replace("-", ""); new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); var data = POSTGRES.dataSource(schema); @@ -51,8 +63,17 @@ void existingTenantStaysUninitializedAndAPlainNewImportCannotInitializeCapacity( var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); var repository = new FreshTenantIdentityAssociationRepository(dsl, "prod"); + var operations = new AccountTenantCreationBootstrapOperationRepository(dsl); var existing = source(); - transaction.executeWithoutResult(status -> repository.importVerified(existing)); + var historical = + Objects.requireNonNull( + transaction.execute( + status -> { + repository.importVerified(existing); + return claimBootstrap( + operations, new AccountRepository(dsl).save(creator()), existing); + })); + assertThat(historical.status()).isEqualTo("IN_PROGRESS"); Flyway.configure() .dataSource(data) .schemas(schema) @@ -70,6 +91,19 @@ void existingTenantStaysUninitializedAndAPlainNewImportCannotInitializeCapacity( existing.canonicalTenantId())) .get("capacity_birth_transaction")) .isNull(); + var completed = + Objects.requireNonNull( + transaction.execute( + status -> { + var operation = operations.findForUpdate(historical.requestId()).orElseThrow(); + assertThat(operation.status()).isEqualTo("IN_PROGRESS"); + assertThat(operation.creationOperationId()).isEqualTo(existing.operationId()); + assertThat(operation.requestPayload()).isEqualTo(historical.requestPayload()); + return operations.complete(operation.requestId(), completion(operation)); + })); + assertThat(completed.status()).isEqualTo("COMMITTED"); + assertThat(completed.tenantUuid()).isEqualTo(existing.canonicalTenantId()); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); var later = source(); transaction.executeWithoutResult(status -> repository.importVerified(later)); assertThat( @@ -86,6 +120,84 @@ void existingTenantStaysUninitializedAndAPlainNewImportCannotInitializeCapacity( } } + private static Account creator() { + String suffix = UUID.randomUUID().toString().replace("-", ""); + var account = new Account(); + account.setUsername("capacity-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("test-only-password-hash"); + account.setRole("player"); + return account; + } + + private static StoredOperation claimBootstrap( + AccountTenantCreationBootstrapOperationRepository operations, + Account creator, + FreshTenantCreationEvidence creation) { + UUID accountId = creator.getAccountUuid(); + UUID authorizationId = UUID.randomUUID(); + String authorizationDigest = + AccountTenantCreationBootstrapDigest.sha256( + "fixture authorization".getBytes(StandardCharsets.UTF_8)); + var evidence = + new FreshTenantCreatorEvidence( + 1, + creation, + accountId, + authorizationId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, accountId, authorizationId, authorizationDigest)); + byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + byte[] sourcePayload = "fixture source snapshot".getBytes(StandardCharsets.UTF_8); + byte[] requestPayload = + AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); + var claim = + operations.claim( + evidence, + creatorPayload, + sourcePayload, + AccountTenantCreationBootstrapDigest.sha256(sourcePayload), + requestPayload, + AccountTenantCreationBootstrapDigest.sha256(requestPayload), + 1, + 1); + assertThat(claim.claimed()).isTrue(); + return claim.operation(); + } + + private static Completion completion(StoredOperation operation) { + // Controlled completion receipts exercise the real storage owner's guarded transition. + byte[] event = "fixture membership event".getBytes(StandardCharsets.UTF_8); + byte[] audit = "fixture bootstrap audit".getBytes(StandardCharsets.UTF_8); + byte[] result = "fixture bootstrap result".getBytes(StandardCharsets.UTF_8); + return new Completion( + 1, + operation.baselineMembershipVersion() + 1, + operation.baselineMembershipAuthorityGeneration(), + "ACTIVE", + false, + "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + operation.initiatingAccountUuid() + + "/" + + operation.tenantUuid(), + operation.requestId().toString(), + 1, + "fixture-membership-event", + AccountTenantCreationBootstrapDigest.sha256(event), + false, + event, + UUID.randomUUID(), + "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", + Instant.now().truncatedTo(ChronoUnit.MICROS), + AccountTenantCreationBootstrapDigest.sha256(audit), + audit, + result, + AccountTenantCreationBootstrapDigest.sha256(result)); + } + private static FreshTenantCreationEvidence source() { UUID request = UUID.randomUUID(), operation = UUID.randomUUID(), tenant = UUID.randomUUID(); String slug = "capacity-" + UUID.randomUUID().toString().substring(0, 8); diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py index 6aa871584f..f1eed0afad 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -4,11 +4,16 @@ import hashlib import json import re +import sys import unicodedata import unittest from pathlib import Path MAX = 9223372036854775807 +REPOSITORY = Path(__file__).resolve().parents[6] +sys.path.insert(0, str(REPOSITORY / "dev-tools")) + +from evidence_digest import canonical_json_bytes def decimal(value): @@ -72,7 +77,10 @@ def evidence(encoded, variant="TENANT_OPERATION"): raise ValueError("evidence bound") parsed = json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=reject_duplicates, parse_constant=reject_nonfinite) - canonical = json.dumps(parsed, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + try: + canonical = canonical_json_bytes(parsed) + except TypeError as error: + raise ValueError("canonical evidence values required") from error if raw != canonical or parsed["schema"] != "account-auth-evidence-bundle/v1" or parsed["variant"] != variant: raise ValueError("exact canonical variant required") tenant = parsed["tenantId"] @@ -122,6 +130,30 @@ def preimage(request, candidate): class CapacityAdmissionVectors(unittest.TestCase): + def test_evidence_uses_restricted_jcs_bytes(self): + # UTF-16 ordering places the supplementary key before U+E000, unlike code-point sorting. + value = {"\ue000": "bmp", "\U00010000": "supplementary"} + self.assertEqual(canonical_json_bytes(value), + '{"\U00010000":"supplementary","\ue000":"bmp"}'.encode("utf-8")) + + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + parsed = json.loads(base64.b64decode(corpus["request"]["canonicalAccountEvidenceBase64"])) + parsed["fractional"] = 1.0 + noncanonical_numeric = json.dumps(parsed, sort_keys=True, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + encoded = base64.b64encode(noncanonical_numeric).decode("ascii") + with self.assertRaisesRegex(ValueError, "canonical evidence values"): + evidence(encoded) + + parsed.pop("fractional") + parsed["\ue000"] = "bmp" + parsed["\U00010000"] = "supplementary" + codepoint_ordered = json.dumps(parsed, sort_keys=True, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + encoded = base64.b64encode(codepoint_ordered).decode("ascii") + with self.assertRaisesRegex(ValueError, "exact canonical variant"): + evidence(encoded) + def test_shared_golden_preimages_and_digests(self): corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) digests = [] 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 89f806a455..2fcb3cd2b1 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 @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.math.BigInteger; +import java.time.Clock; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -14,6 +15,7 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; @@ -2711,13 +2713,39 @@ && findTransition(transaction, current.transition().transitionId()) } /** - * Accepts only the final owner's separately obtained physical six-key readback. Remote current - * sources and admission barriers are checked by the coordinator outside this SQL transaction; - * this transaction records their exact original NEW operation, not cross-store atomicity. + * Accepts only the final owner's separately obtained physical readback. Remote current sources + * and admission barriers are checked by the coordinator outside this SQL transaction; this + * transaction records the exact original NEW receipt and positive execution evidence. */ CanonicalGameplayBindingTransitionSnapshot commitOriginalNewFinalAdmission( CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback actual) { requireNoAmbientTransaction(); + return commitVerifiedOriginalNewFinalAdmission(verifyOriginalNewFinalReadback(actual)); + } + + void commitOriginalNewFinalAdmission( + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback actual, + Clock clock, + long absoluteDeadlineMillis) { + requireNoAmbientTransaction(); + // Capture only immutable SQL evidence before admitting the resource worker. The caller may + // wipe the physical session readback if its deadline expires while SQL is still draining. + var verified = verifyOriginalNewFinalReadback(actual); + CanonicalGameplayOriginalNewCapacityExecutionBudget.run( + clock, + absoluteDeadlineMillis, + budget -> + new CanonicalGameplayBindingInventoryRepository(budget.sql(dsl)) + .commitVerifiedOriginalNewFinalAdmission(verified)); + } + + private record VerifiedOriginalNewFinalReadback( + OriginalNewFinalAdmissionSource source, + OriginalNewFinalAdmissionReceipt receipt, + OriginalNewCapacityExecution execution) {} + + private static VerifiedOriginalNewFinalReadback verifyOriginalNewFinalReadback( + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback actual) { Objects.requireNonNull(actual, "actual"); var source = actual.source(); var candidate = source.candidate(); @@ -2743,6 +2771,21 @@ CanonicalGameplayBindingTransitionSnapshot commitOriginalNewFinalAdmission( != actual.admissionAtMillis() + actual.canonicalSessionDurationMillis()) { throw conflict("Final controller readback differs from its authenticated original NEW"); } + return new VerifiedOriginalNewFinalReadback( + source, + new OriginalNewFinalAdmissionReceipt( + actual.finalSessionSha256(), + actual.admissionAtMillis(), + actual.continuityExpiresAtMillis(), + actual.canonicalSessionDurationMillis()), + actual.execution()); + } + + private CanonicalGameplayBindingTransitionSnapshot commitVerifiedOriginalNewFinalAdmission( + VerifiedOriginalNewFinalReadback verified) { + var source = verified.source(); + var candidate = source.candidate(); + var receipt = verified.receipt(); return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); @@ -2841,7 +2884,7 @@ CanonicalGameplayBindingTransitionSnapshot commitOriginalNewFinalAdmission( || (source.transitionStatus() == CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED && !committed) - || BigInteger.valueOf(actual.admissionAtMillis()) + || BigInteger.valueOf(receipt.admissionAtMillis()) .compareTo(decision.leaseExpiresAtEpochMillis()) >= 0) { throw conflict("Final controller source differs from the retained original NEW"); @@ -2868,7 +2911,7 @@ CanonicalGameplayBindingTransitionSnapshot commitOriginalNewFinalAdmission( } requireOriginalNewFinalRegionAcknowledgement(transaction, candidate, transition, entry); if (committed) { - requireOriginalNewFinalReceipt(row, actual, decision); + requireOriginalNewFinalReceipt(row, verified, decision); return transition; } requireNoOriginalNewFinalAdmissionReceipt(row); @@ -2883,11 +2926,11 @@ CanonicalGameplayBindingTransitionSnapshot commitOriginalNewFinalAdmission( + " original_new_continuity_expires_at_ms = ?, original_new_session_duration_ms = ?, original_new_capacity_execution_digest = ?" + " WHERE transition_id = ? AND status = 'PROVISIONAL' AND inventory_revision = ?", decimal(next), - actual.finalSessionSha256(), - actual.admissionAtMillis(), - actual.continuityExpiresAtMillis(), - actual.canonicalSessionDurationMillis(), - actual.execution().digest(), + receipt.finalSessionSha256(), + receipt.admissionAtMillis(), + receipt.continuityExpiresAtMillis(), + receipt.sessionDurationMillis(), + verified.execution().digest(), transition.transitionId(), prior), "Original NEW final transition CAS changed"); @@ -2948,6 +2991,8 @@ CanonicalGameplayBindingTransitionSnapshot commitOriginalNewFinalAdmission( prior), "Original NEW reservation CAS changed"); bumpInventoryClock(transaction, revision, next); + CanonicalGameplayOriginalNewCapacityExecutionOwner.retainCommittedInTransaction( + transaction, verified.execution(), receipt); return toTransitionSnapshot( Objects.requireNonNull( findTransition(transaction, transition.transitionId()), @@ -2963,17 +3008,13 @@ CanonicalGameplayBindingTransitionSnapshot commitOriginalNewFinalAdmission( private static void requireOriginalNewFinalReceipt( Record row, - CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback actual, + VerifiedOriginalNewFinalReadback verified, CanonicalGameplayAdmissionDecision decision) { - OriginalNewFinalAdmissionReceipt receipt = readOriginalNewFinalAdmissionReceipt(row, decision); - if (!actual + if (!verified .execution() .digest() .equals(row.get("original_new_capacity_execution_digest", String.class)) - || !receipt.finalSessionSha256().equals(actual.finalSessionSha256()) - || receipt.admissionAtMillis() != actual.admissionAtMillis() - || receipt.continuityExpiresAtMillis() != actual.continuityExpiresAtMillis() - || receipt.sessionDurationMillis() != actual.canonicalSessionDurationMillis()) { + || !verified.receipt().equals(readOriginalNewFinalAdmissionReceipt(row, decision))) { throw conflict("Committed original NEW has no identical immutable final readback receipt"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java index 7bf0f01b87..0249288705 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionOwner.java @@ -399,8 +399,21 @@ public Snapshot retainCommittedBeforeCleanup(Request request, Result reservation return readExact(request, reservation, false); } - void retainCommitted(CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback actual) { - retainCommitted(actual, Long.MAX_VALUE); + static void retainCommittedInTransaction( + DSLContext transaction, + OriginalNewCapacityExecution execution, + CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionReceipt finalReceipt) { + String receipt = + receiptDigest( + execution, + finalReceipt.finalSessionSha256(), + finalReceipt.admissionAtMillis(), + finalReceipt.continuityExpiresAtMillis(), + finalReceipt.sessionDurationMillis()); + byte[] proof = + execution.terminalEvidence( + "COMMITTED", "sha256:" + finalReceipt.finalSessionSha256(), receipt); + retainTerminal(transaction, execution, "COMMITTED", proof); } void retainCommitted( @@ -420,8 +433,8 @@ void retainCommitted( Record row = find(sql(), execution); if (row == null) throw unavailable(); exact(row, execution); - // The final receipt must already be committed. This read also independently checks indexes - // and the script's atomic terminal record, not the return value of EVAL. + // A pre-existing receipt may predate atomic retention. Qualify that historical gap through + // the exact physical indexes and atomic terminal record before retaining its outcome. Snapshot snapshot = readExact(execution.request(), execution.reservation(), true); if (!"COMMITTED".equals(snapshot.disposition())) throw unavailable(); retainTerminal(execution, "COMMITTED", snapshot.canonicalReadback()); @@ -430,30 +443,30 @@ void retainCommitted( private void retainTerminal(OriginalNewCapacityExecution execution, String status, byte[] proof) { sql() .transaction( - configuration -> { - var tx = DSL.using(configuration); - Record row = find(tx, execution); - if (row == null) throw unavailable(); - exact(row, execution); - String current = row.get("status", String.class); - if (current.equals(status)) { - if (!Arrays.equals(proof, row.get("terminal_readback", byte[].class))) - throw unavailable(); - return; - } - if (!("AUTHORIZED".equals(current) - || ("CLOSED".equals(status) && "INSTALL_DISPATCHED".equals(current)))) - throw unavailable(); - if (tx.execute( - "UPDATE " - + TABLE - + " SET status = ?, terminal_readback = ? WHERE execution_digest = ? AND status = ?", - status, - proof, - execution.digest(), - current) - != 1) throw unavailable(); - }); + configuration -> retainTerminal(DSL.using(configuration), execution, status, proof)); + } + + private static void retainTerminal( + DSLContext tx, OriginalNewCapacityExecution execution, String status, byte[] proof) { + Record row = find(tx, execution); + if (row == null) throw unavailable(); + exact(row, execution); + String current = row.get("status", String.class); + if (current.equals(status)) { + if (!Arrays.equals(proof, row.get("terminal_readback", byte[].class))) throw unavailable(); + return; + } + if (!("AUTHORIZED".equals(current) + || ("CLOSED".equals(status) && "INSTALL_DISPATCHED".equals(current)))) throw unavailable(); + if (tx.execute( + "UPDATE " + + TABLE + + " SET status = ?, terminal_readback = ? WHERE execution_digest = ? AND status = ?", + status, + proof, + execution.digest(), + current) + != 1) throw unavailable(); } /** Authenticated transport calls this read-only method. Absence and contradictions throw. */ @@ -971,16 +984,30 @@ private static void exact(Record row, OriginalNewCapacityExecution execution) { } private static String receiptDigest(Record row, OriginalNewCapacityExecution execution) { + return receiptDigest( + execution, + row.get("original_new_final_session_sha256", String.class), + row.get("original_new_admission_at_ms", Long.class), + row.get("original_new_continuity_expires_at_ms", Long.class), + row.get("original_new_session_duration_ms", Long.class)); + } + + private static String receiptDigest( + OriginalNewCapacityExecution execution, + String finalSessionSha256, + long admissionAtMillis, + long continuityExpiresAtMillis, + long durationMillis) { String receipt = execution.digest() + "/" - + row.get("original_new_final_session_sha256", String.class) + + finalSessionSha256 + "/" - + row.get("original_new_admission_at_ms", Long.class) + + admissionAtMillis + "/" - + row.get("original_new_continuity_expires_at_ms", Long.class) + + continuityExpiresAtMillis + "/" - + row.get("original_new_session_duration_ms", Long.class); + + durationMillis; return "sha256:" + OriginalNewCapacityExecution.sha256(bytes(receipt)); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index 4154e891af..8a1960fdd5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -183,7 +183,8 @@ FinalAdmissionResult completeOriginalNew( source.transitionStatus() == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL; if (committedByThisAttempt) { - inventory.commitOriginalNewFinalAdmission(finalReadback); + inventory.commitOriginalNewFinalAdmission( + finalReadback, clock, absoluteDeadlineMillis); CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource committedSource = readSameSource(source, originalDecision, true); if (committedSource.transitionStatus() @@ -200,7 +201,9 @@ FinalAdmissionResult completeOriginalNew( .orElseThrow( CanonicalGameplayOriginalNewFinalAdmissionCoordinator::unavailable); requireReadbackMatchesReceipt(finalReadback, finalReceipt); - capacityExecution.retainCommitted(finalReadback, absoluteDeadlineMillis); + if (!committedByThisAttempt) { + capacityExecution.retainCommitted(finalReadback, absoluteDeadlineMillis); + } Currentness beforeConfirmation = currentness(source, privateRegionInstallation); requireSameCurrentness(atDispatch, beforeConfirmation, committedByThisAttempt); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java index df3f56920e..e98b8d7949 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java @@ -409,7 +409,10 @@ void finalBeforeFencePreservesEveryCommittedByteHashAndControllerTimeIncludingEx assertThat(eval(action(original, "FENCE"))).isEqualTo(9L); assertThat(eval(expired(action(original, "FENCE")))).isEqualTo(9L); byte[][] credentialFree = action(original, "FENCE").arguments().clone(); + credentialFree[10] = ascii("{}"); credentialFree[11] = ascii("1"); + credentialFree[12] = ascii("{}"); + credentialFree[13] = ascii("{}"); assertThat(eval(new ScriptCase(original.keys(), credentialFree))).isEqualTo(9L); assertThat(eval(expired(new ScriptCase(original.keys(), credentialFree)))).isEqualTo(9L); assertThat(eval(preFenceScriptSha, original)).isEqualTo(2L); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index d288e43fe1..f49c9c2770 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -664,6 +664,8 @@ void changedExecutionCandidateRefusesBeforeCreatingSqlDispatchCustody() throws E "sha256:" + "0".repeat(64), controlledCapacity.selectedOwnerId(), controlledCapacity.selectedOwnerFence()); + var accountOpen = controlledAccountOpen(); + var issuerOpen = issuerOpen(); var sqlBefore = sqlImage(); var physicalBefore = physicalImage(); try (var credential = @@ -672,13 +674,7 @@ void changedExecutionCandidateRefusesBeforeCreatingSqlDispatchCustody() throws E assertThatThrownBy( () -> capacityOwner() - .authorize( - source, - template, - controlledAccountOpen(), - issuerOpen(), - changed, - deadline())) + .authorize(source, template, accountOpen, issuerOpen, changed, deadline())) .isInstanceOf(IllegalStateException.class); } assertThat(sqlImage()).isEqualTo(sqlBefore); @@ -1106,6 +1102,141 @@ void ordinaryProvisionalHandoffWithoutCapacityExecutionNeedsNoFinalAcknowledgeme .isZero(); } + @Test + void failedPositiveRetentionRollsBackFinalReceiptAndExactRecoveryCommitsBoth() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var accountOpen = controlledAccountOpen(); + var issuerOpen = issuerOpen(); + String before = sqlImage(); + var retentionAttempted = new java.util.concurrent.atomic.AtomicBoolean(); + var observer = + new org.jooq.impl.DefaultExecuteListener() { + @Override + public void executeStart(org.jooq.ExecuteContext context) { + String query = context.sql(); + if (query == null + || !query.startsWith("UPDATE game_session_original_new_capacity_execution") + || !query.contains("terminal_readback")) return; + retentionAttempted.set(true); + assertThat(sqlImage()).isEqualTo(before); + throw new IllegalStateException("Controlled positive execution retention failure"); + } + }; + var observedSql = + org.jooq.impl.DSL.using(fixture.dsl().configuration().deriveAppending(observer)); + var observedInventory = new CanonicalGameplayBindingInventoryRepository(observedSql); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var readback = + finalOwner() + .finalizeOriginalNewOnce( + source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { + var committedRedis = physicalImage(); + assertThatThrownBy( + () -> observedInventory.commitOriginalNewFinalAdmission(readback, CLOCK, deadline())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Controlled positive execution retention failure"); + assertThat(retentionAttempted).isTrue(); + assertThat(sqlImage()).isEqualTo(before); + assertThatThrownBy( + () -> + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation())) + .isInstanceOf(IllegalStateException.class); + var recovered = + capacityOwner() + .retainCommittedBeforeCleanup( + controlledCapacity.request(), controlledCapacity.reservation(), deadline()); + assertThat(recovered.disposition()).isEqualTo("COMMITTED"); + assertThat(recovered.physicalDigest()).isEqualTo("sha256:" + readback.finalSessionSha256()); + assertThat( + inventory + .readOriginalNewFinalAdmissionSource(decision) + .finalReceipt() + .orElseThrow() + .finalSessionSha256()) + .isEqualTo(readback.finalSessionSha256()); + assertThat( + capacityOwner() + .readExact(controlledCapacity.request(), controlledCapacity.reservation()) + .canonicalReadback()) + .containsExactly(recovered.canonicalReadback()); + assertThat(physicalImage()).isEqualTo(committedRedis); + } + } + + @Test + void previouslySplitReceiptRequiresExactPhysicalProofAndRetainsIdempotently() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var accountOpen = controlledAccountOpen(); + var issuerOpen = issuerOpen(); + var sql = fixture.dsl(); + // Model an old receipt-only writer while preserving the actual guarded receipt transaction. + sql.execute( + """ + CREATE FUNCTION fixture_preserve_authorized_execution() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + RETURN OLD; + END; + $$ + """); + sql.execute( + """ + CREATE TRIGGER aaa_fixture_preserve_authorized_execution + BEFORE UPDATE ON game_session_original_new_capacity_execution + FOR EACH ROW EXECUTE FUNCTION fixture_preserve_authorized_execution() + """); + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var readback = + finalOwner() + .finalizeOriginalNewOnce( + source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { + inventory.commitOriginalNewFinalAdmission(readback); + } finally { + sql.execute( + "DROP TRIGGER aaa_fixture_preserve_authorized_execution ON game_session_original_new_capacity_execution"); + sql.execute("DROP FUNCTION fixture_preserve_authorized_execution()"); + } + var request = controlledCapacity.request(); + var reservation = controlledCapacity.reservation(); + var owner = capacityOwner(); + assertThat(inventory.readOriginalNewFinalAdmissionSource(decision).finalReceipt()).isPresent(); + assertThat( + sql.fetchSingle( + "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + controlledCapacity.digest()) + .get(0, String.class)) + .isEqualTo("AUTHORIZED"); + assertThatThrownBy(() -> owner.readExact(request, reservation)) + .isInstanceOf(IllegalStateException.class); + var originalPhysical = physicalImage(); + byte[] sessionKey = ascii(installation.sessionKey()); + byte[] originalSession = admin.get(sessionKey); + admin.del(sessionKey); + assertThatThrownBy(() -> owner.retainCommittedBeforeCleanup(request, reservation, deadline())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> owner.readExact(request, reservation)) + .isInstanceOf(IllegalStateException.class); + admin.set(sessionKey, originalSession); + var retained = owner.retainCommittedBeforeCleanup(request, reservation, deadline()); + assertThat(retained.disposition()).isEqualTo("COMMITTED"); + assertThat( + owner + .retainCommittedBeforeCleanup(request, reservation, deadline()) + .canonicalReadback()) + .containsExactly(retained.canonicalReadback()); + assertThat(owner.readExact(request, reservation).canonicalReadback()) + .containsExactly(retained.canonicalReadback()); + assertThat(physicalImage()).isEqualTo(originalPhysical); + } + @Test void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff() throws Exception { From a56b3edbd1bee5bbce3bb2382cb959bac4d31c0b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:33:29 +1300 Subject: [PATCH 43/52] Pass the controlled Redis deletion key as the declared varargs array --- ...alGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index f49c9c2770..682ff3c799 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -1219,7 +1219,7 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { var originalPhysical = physicalImage(); byte[] sessionKey = ascii(installation.sessionKey()); byte[] originalSession = admin.get(sessionKey); - admin.del(sessionKey); + admin.del(new byte[][] {sessionKey}); assertThatThrownBy(() -> owner.retainCommittedBeforeCleanup(request, reservation, deadline())) .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> owner.readExact(request, reservation)) From 5cf3c60c72e7332407b009893e81b326a9fbd18b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:35:47 +1300 Subject: [PATCH 44/52] Expire the controlled session key without a Redis varargs call --- ...alGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 682ff3c799..c28899871c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -1219,7 +1219,7 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { var originalPhysical = physicalImage(); byte[] sessionKey = ascii(installation.sessionKey()); byte[] originalSession = admin.get(sessionKey); - admin.del(new byte[][] {sessionKey}); + assertThat(admin.pexpire(sessionKey, 0)).isTrue(); assertThatThrownBy(() -> owner.retainCommittedBeforeCleanup(request, reservation, deadline())) .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> owner.readExact(request, reservation)) From 020391f634e4ca84ef8810520264b4d7d1e460c2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:02:47 +1300 Subject: [PATCH 45/52] Bound recovery reads and require authentic region transfer custody --- .../game-session-service/runtime-and-data.md | 4 +- ...riginalNewCapacityExecutionReadClient.java | 38 +++-- ...alAdmissionCompositionIntegrationTest.java | 5 +- ...nalNewCapacityExecutionReadClientTest.java | 144 ++++++++++++++++++ .../AccountTenantCapacityGrpcServiceTest.java | 5 +- .../AbstractReloadingBlockingGrpcClient.java | 14 +- ...stractReloadingBlockingGrpcClientTest.java | 9 ++ .../CapacityAdmissionTestFixture.java | 22 ++- .../CanonicalGameplayRegionLeaseOwner.java | 1 + ..._require_frozen_region_transfer_insert.sql | 54 +++++++ ...e-session-original-new-final-admission.lua | 5 +- ...-session-original-new-final-admission.json | 2 +- ...alNewFinalAdmissionLuaIntegrationTest.java | 14 ++ ...untimeStatusRepositoryIntegrationTest.java | 49 ++++++ ...eFamilyCatalogPostgresIntegrationTest.java | 53 +++++-- ...lNewCapacityExecutionRedisCommandTest.java | 34 +++-- 16 files changed, 397 insertions(+), 56 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountOriginalNewCapacityExecutionReadClientTest.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.2__require_frozen_region_transfer_insert.sql diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index e95f76f1b1..64fce1c615 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -16,7 +16,7 @@ The capacity execution owner uses one absolute budget for each complete operatio Game Session may exclude an unresolved original from future execution while its historical outcome remains indeterminate. This normal-handoff operation is separate from original-attempt closure, reservation recovery and cleanup. Its permanent tenant-slot `FENCED_INDETERMINATE` hash contains only the exact retained execution binding, digest and denying state. It may be created when the execution key is absent or replace the state of an exact persistent `AUTHORIZED` hash; neither action establishes that an earlier effect did not happen. The existing `INSTALL`, `FINAL` and `CLOSE` arms, including the predecessor script, reject that state. It never creates an authorization, session candidate, session or index, and supplies no `NOT_EXECUTED_AFTER_AUTHORIZATION` evidence. The Account reservation, original attempt/fence and complete capacity hold remain pending or quarantined under Account's existing recovery policy. -After the ordinary timeline/incarnation qualification and lost-completion checks, the contender must acquire the successor Redis grant before freezing the current generation. A still-renewing incumbent therefore rejects the contender without transfer or execution-fence mutation. Before freezing, the contender rechecks the exact source, protected incarnation, initialized timeline and current grant; after fencing it renews and revalidates the grant before protected installation. Grant acquisition does not replace the transfer proof. The handoff freezes one absolute deadline before inventory selection, capped at five seconds and the incoming deadline. Initial provisional/candidate selection, exact committed-source selection and every later installation source revalidation use that same deadline and the original inventory provider through the existing bounded resource worker. Each scoped SQL context owns its derived connection and transaction provider; blocked acquisition, query cancellation and uncertain release retain their existing custody rules. An expired read cannot authorize successor installation. Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The database dispatch guard locks the same runtime row and verifies the exact active selected owner. Both a frozen generation and the completed predecessor refuse new dispatch markers, including during the transaction that installs the successor. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. +After the ordinary timeline/incarnation qualification and lost-completion checks, the contender must acquire the successor Redis grant before freezing the current generation. A still-renewing incumbent therefore rejects the contender without transfer or execution-fence mutation. Before freezing, the contender rechecks the exact source, protected incarnation, initialized timeline and current grant; after fencing it renews and revalidates the grant before protected installation. Grant acquisition does not replace the transfer proof. The handoff freezes one absolute deadline before inventory selection, capped at five seconds and the incoming deadline. Initial provisional/candidate selection, exact committed-source selection and every later installation source revalidation use that same deadline and the original inventory provider through the existing bounded resource worker. Each scoped SQL context owns its derived connection and transaction provider; blocked acquisition, query cancellation and uncertain release retain their existing custody rules. An expired read cannot authorize successor installation. Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The database dispatch guard locks the same runtime row and verifies the exact active selected owner. A newly inserted transfer must start FROZEN with no successor or verification evidence. Both a frozen generation and the completed predecessor refuse new dispatch markers, including during the transaction that installs the successor. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. The protected receiver has a separate `REGION_OWNER_TRANSFER` purpose and signed schema. Its actual SQL source binds the frozen transfer, original execution, immutable tenant-tag assignment and complete protected deployment/registry/ACL/configuration/storage/AOF identity. Nonce, signature, exact carrier, time and two-source-read checks apply to each observation. Before and after fencing, and around a complete streamed physical verification before owner installation, fresh purpose-correct observations must agree with the transfer's retained incarnation. Historical SQL receipts alone cannot qualify a missing marker or a changed, unavailable, reset, restored or rolled-back store. Verification never recreates a previously retained missing fence. An inventory which cannot be completely re-read within the operation deadline remains frozen rather than dropping the currentness requirement. Normal handoff does not authorize adoption across storage loss; the owning reset/recovery qualification remains required. @@ -104,7 +104,7 @@ Game Session's runtime-family catalog is a manually composed **LOCAL SQL** sourc The catalog seals the actual current Game Session PostgreSQL schema, not a historical union of `CREATE TABLE` statements, a prefix exclusion or a static expected-table response. Every installed table, including empty tables, requires an explicit family disposition; named mixed components additionally bind their actual columns. Sorted definition digests cover tables, columns, constraints, indexes, triggers, routines, sequences, views, types, policies and rules, alongside the actual configured Flyway history. View and materialized-view facts bind both the query definition and relation options, including security-invoker, security-barrier and materialized-view storage settings; changing options invalidates the current seal even when the query text is unchanged. Unknown or removed relations/components refuse capture; changed schema definitions, routines, classification or prior/later migration facts invalidate the sealed epoch and previously retained reads. A new epoch requires an explicit monotonic owner installation against the complete current classified schema, not automatic resampling during a read. -Flyway writes each installing migration's own history row only after its migration transaction. The seal therefore binds distinct stable V1057, V1058, V1059, V1060, V1061, V1062, V1063, V1064 and V1065 installation markers and the actual installed definitions; it excludes only those nine installing history rows without inventing or claiming their eventual checksums. After installation, capture/readback additionally require exactly one successful SQL row for each version with its exact installing script in the configured history table. All other prior and later history facts remain part of the seal. Each forward installer seals the next monotonic owner epoch only after all routine replacements: V1058 binds view options, V1059 narrows the initial-preparation public-target conflict while preserving retained private projections, V1060 installs classified private catalog revision history/current-head control relations, and V1061 adds immutable private FRESH runtime identity provenance and seals epoch `5`; V1062 adds pending source protection and its writer guards before sealing epoch `6`; V1063 adds exact original-NEW capacity execution and its final-receipt binding before sealing epoch `7`; V1064 restores the final Human runtime completion row-version lower bound while preserving the full current RUNNING launch, candidate, capacity and identity guard, then seals epoch `8`; V1065 adds retained normal-handoff transfer control and per-original fencing receipt families before sealing epoch `9`. Earlier migrations and all retained epoch, snapshot and history bytes remain immutable. Requests retained under an older epoch conflict with the current epoch rather than being rewritten or resampled. Other installation and retention obligations remain with the [database migration owner](../../system-architecture-database-migrations.md); the configured history table, rather than an assumed `flyway_schema_history` alias, is itself explicitly classified as retained control evidence. +Flyway writes each installing migration's own history row only after its migration transaction. The seal therefore binds distinct stable V1057, V1058, V1059, V1060, V1061, V1062, V1063, V1064, V1065, V1065.0.1 and V1065.0.2 installation markers and the actual installed definitions; it excludes only those eleven installing history rows without inventing or claiming their eventual checksums. After installation, capture/readback additionally require exactly one successful SQL row for each version with its exact installing script in the configured history table. All other prior and later history facts remain part of the seal. Each forward installer seals the next monotonic owner epoch only after all routine replacements: V1058 binds view options, V1059 narrows the initial-preparation public-target conflict while preserving retained private projections, V1060 installs classified private catalog revision history/current-head control relations, and V1061 adds immutable private FRESH runtime identity provenance and seals epoch `5`; V1062 adds pending source protection and its writer guards before sealing epoch `6`; V1063 adds exact original-NEW capacity execution and its final-receipt binding before sealing epoch `7`; V1064 restores the final Human runtime completion row-version lower bound while preserving the full current RUNNING launch, candidate, capacity and identity guard, then seals epoch `8`; V1065 adds retained normal-handoff transfer control and per-original fencing receipt families before sealing epoch `9`; V1065.0.1 requires the current durable region owner for capacity dispatch and seals epoch `10`; V1065.0.2 requires every new transfer to enter through the initial FROZEN state and seals epoch `11`. Earlier migrations and all retained epoch, snapshot and history bytes remain immutable. Requests retained under an older epoch conflict with the current epoch rather than being rewritten or resampled. Other installation and retention obligations remain with the [database migration owner](../../system-architecture-database-migrations.md); the configured history table, rather than an assumed `flyway_schema_history` alias, is itself explicitly classified as retained control evidence. Gameplay commands and remote work whose namespace partition or replacement class is unresolved remain `UNKNOWN` and blocking, never implicitly S3. Durable tick/effect recovery, selected-work manifests, remote outcomes, script-pin authority/history and region/timeline provenance remain separate blocking evidence rather than cloned gameplay payload or a FRESH manifest. Input history and reconnect context retain their distinct audit/privacy consequences. `game_manifest` remains unsupported unqualified legacy lineage, not a build or FRESH source. Catalog/pointer, original operator/LOGIN/roster/binding/account/issuer authority, installed Saga control, and their original request, nonce, fence, replay, retirement and hold guards retain their owning consequences. Classification grants neither cleanup authority nor permission to discard uncertain work. The private preparation, original allocation and lifecycle-bound catalog revision branch are included as retained control/provenance; `PREPARING` is not a private runtime, CLOSED pointer or readiness result. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewCapacityExecutionReadClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewCapacityExecutionReadClient.java index 15918cb5b1..6746779263 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewCapacityExecutionReadClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewCapacityExecutionReadClient.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.accountservice.client; +import io.grpc.Deadline; import io.grpc.ManagedChannel; import java.io.IOException; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.UUID; @@ -27,6 +29,7 @@ public final class AccountOriginalNewCapacityExecutionReadClient OriginalNewCapacityExecutionReadServiceGrpc .OriginalNewCapacityExecutionReadServiceBlockingStub> implements AccountTenantCapacityRecoveryWorker.ExecutionReadClient { + private static final long MAX_READ_MILLIS = 5000; private final String namespace; private final String peer; private final Clock clock; @@ -61,6 +64,7 @@ public AccountTenantCapacityRecoveryWorker.Observation readExact( TenantCapacityAdmission.Request request, TenantCapacityAdmission.Result reservation, Instant deadline) { + Deadline maximum = Deadline.after(MAX_READ_MILLIS, TimeUnit.MILLISECONDS); requireNoAmbientSql("Capacity execution read requires no Account transaction"); if (!namespace.equals(request.targetNamespace()) || request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION @@ -68,18 +72,19 @@ public AccountTenantCapacityRecoveryWorker.Observation readExact( || SessionContext.isInternalService() || SessionContext.getServiceName() != null || SessionContext.getServiceInstanceId() != null) throw unavailable(); - long millis = Math.min(5000, java.time.Duration.between(clock.instant(), deadline).toMillis()); + long millis = Math.min(MAX_READ_MILLIS, Duration.between(clock.instant(), deadline).toMillis()); if (millis <= 0) throw unavailable(); + Deadline rpcDeadline = maximum.offset(millis - MAX_READ_MILLIS, TimeUnit.MILLISECONDS); + var stub = requirePublishedInitializedStub("Capacity execution read unavailable"); var selector = new OriginalNewCapacityExecutionReadGrpcCodec.Selector(request, reservation); + var wire = OriginalNewCapacityExecutionReadGrpcCodec.toRequest(selector); + if (rpcDeadline.isExpired()) throw unavailable(); var response = - requireInitializedStub("Capacity execution read unavailable") - .withDeadlineAfter(millis, TimeUnit.MILLISECONDS) + stub.withDeadline(rpcDeadline) .withMaxOutboundMessageSize(OriginalNewCapacityExecutionReadGrpcCodec.MAX_REQUEST_BYTES) .withMaxInboundMessageSize(OriginalNewCapacityExecutionReadGrpcCodec.MAX_RESPONSE_BYTES) - .readOriginalNewCapacityExecution( - OriginalNewCapacityExecutionReadGrpcCodec.toRequest(selector)); + .readOriginalNewCapacityExecution(wire); var readback = OriginalNewCapacityExecutionReadGrpcCodec.fromResponse(selector, response); - if (!clock.instant().isBefore(deadline)) throw unavailable(); var disposition = AccountTenantCapacityRecoveryWorker.Disposition.valueOf(readback.disposition()); // The complete terminal bytes are generated from actual owner evidence, not a boolean. @@ -94,15 +99,18 @@ public AccountTenantCapacityRecoveryWorker.Observation readExact( observed.writeBytes(value); } byte[] canonical = observed.toByteArray(); - return new AccountTenantCapacityRecoveryWorker.Observation( - peer, - reservation, - CapacityAdmissionDigest.preimage(request), - disposition, - UUID.nameUUIDFromBytes(canonical), - readback.currentOwnerFence(), - readback.physicalDigest(), - canonical); + var observation = + new AccountTenantCapacityRecoveryWorker.Observation( + peer, + reservation, + CapacityAdmissionDigest.preimage(request), + disposition, + UUID.nameUUIDFromBytes(canonical), + readback.currentOwnerFence(), + readback.physicalDigest(), + canonical); + if (rpcDeadline.isExpired() || !clock.instant().isBefore(deadline)) throw unavailable(); + return observation; } @Override diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index cf321463f4..69d982e6ed 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -229,7 +229,10 @@ void actualNormalHandoffKeepsUnknownCapacityHeldAndBoundedRecoveryQuarantinesSam () -> session.capacityRead.readExact( session.capacityRequest, reservation, CLOCK.instant().plusSeconds(5))) - .isInstanceOf(RuntimeException.class); + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); TenantCapacityAdmission.Result result = reservation; var recovery = new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountOriginalNewCapacityExecutionReadClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountOriginalNewCapacityExecutionReadClientTest.java new file mode 100644 index 0000000000..e6bf9797a7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountOriginalNewCapacityExecutionReadClientTest.java @@ -0,0 +1,144 @@ +package unit.net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Clock; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.accountservice.client.AccountOriginalNewCapacityExecutionReadClient; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.v1.OriginalNewCapacityExecutionReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadOriginalNewCapacityExecutionRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalNewCapacityExecutionResponse; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountOriginalNewCapacityExecutionReadClientTest { + @Test + void readReachesItsTransportDeadlineWhileTlsReloadIsBlocked(@TempDir Path directory) + throws Exception { + var pki = + LoopbackMtlsTestPki.create( + directory, + "Capacity execution read test CA", + new IdentitySpec("gs", CapacityAdmissionTestFixture.PEER, true), + new IdentitySpec("account", "spiffe://firemud/ns/prod/sa/account-service", false)); + var tls = pki.clientProperties(directory, pki.identity("account")); + var identity = pki.identity("gs"); + var readStarted = new CountDownLatch(1); + var service = + new OriginalNewCapacityExecutionReadServiceGrpc + .OriginalNewCapacityExecutionReadServiceImplBase() { + @Override + public void readOriginalNewCapacityExecution( + ReadOriginalNewCapacityExecutionRequest request, + StreamObserver response) { + readStarted.countDown(); + } + }; + var server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(service) + .build() + .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + server.getPort()); + var factory = new BlockingReloadChannelFactory(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var reservation = + new TenantCapacityAdmission.Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.randomUUID(), + 1, + request.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + + try (var client = + new AccountOriginalNewCapacityExecutionReadClient( + endpoints, tls, factory, request.targetNamespace(), Clock.systemUTC()); + var executor = Executors.newSingleThreadExecutor()) { + client.init(); + try { + Files.writeString(Path.of(tls.getCertChain()), "\n", StandardOpenOption.APPEND); + assertThat(factory.reloadStarted.await(5, TimeUnit.SECONDS)).isTrue(); + var read = + executor.submit( + () -> + assertThatThrownBy( + () -> + client.readExact( + request, reservation, Instant.now().plusSeconds(2))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); + assertThat(readStarted.await(3, TimeUnit.SECONDS)).isTrue(); + read.get(4, TimeUnit.SECONDS); + } finally { + factory.releaseReload.countDown(); + } + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static final class BlockingReloadChannelFactory extends GrpcChannelFactory { + private final AtomicBoolean initialBuild = new AtomicBoolean(true); + private final CountDownLatch reloadStarted = new CountDownLatch(1); + private final CountDownLatch releaseReload = new CountDownLatch(1); + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + if (!initialBuild.getAndSet(false)) { + reloadStarted.countDown(); + try { + if (!releaseReload.await(10, TimeUnit.SECONDS)) { + throw new SSLException("Test reload release timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new SSLException("Test reload wait interrupted", interrupted); + } + } + return super.buildChannel(target, defaultPort, properties, keepAlive); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 052e448105..0bda32761b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -67,7 +67,10 @@ void unexpectedOwnerFailuresAreSanitizedInternal(RuntimeException cause) { var error = ArgumentCaptor.forClass(Throwable.class); verify(observer).onError(error.capture()); - assertThat(Status.fromThrowable(error.getValue())).isEqualTo(Status.INTERNAL); + Status status = Status.fromThrowable(error.getValue()); + assertThat(status.getCode()).isEqualTo(Status.Code.INTERNAL); + assertThat(status.getDescription()).isNull(); + assertThat(status.getCause()).isNull(); assertThat(error.getValue().getCause()).isNull(); verify(observer, never()).onNext(any()); verify(observer, never()).onCompleted(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 8840f13cee..ed4f21d6c5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -23,8 +23,8 @@ public abstract class AbstractReloadingBlockingGrpcClient target() { target.put("tenantId", TENANT.toString()); target.put("tenantSlug", "tenant"); target.put("worldSlug", "world"); - target.put("realmId", REQUEST.toString()); + target.put("realmId", REALM.toString()); target.put("realmSlug", "production"); - target.put("playableStateNamespaceId", REQUEST.toString()); + target.put("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE.toString()); target.put("playableStateScope", "SHARED"); - target.put("gameInstanceId", REQUEST.toString()); + target.put("gameInstanceId", GAME_INSTANCE.toString()); target.put("canonicalVersionId", REQUEST.toString()); target.put("catalogRevision", "7"); target.put("pointerVersion", "3"); 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 a6d9a882ae..c96695e3ce 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 @@ -894,6 +894,7 @@ private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveCurrentInst CanonicalGameplayRegionOwnerTransferCoordinator transferOwner, long handoffDeadline) { if (transferSource == null) { + if (original == null) throw unavailable(); return resolveExactSource( request, readInstallationInventory( diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.2__require_frozen_region_transfer_insert.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.2__require_frozen_region_transfer_insert.sql new file mode 100644 index 0000000000..2104a6ecdd --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.2__require_frozen_region_transfer_insert.sql @@ -0,0 +1,54 @@ +-- [jooq ignore start] +CREATE FUNCTION require_gs_frozen_region_owner_transfer_insert() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.state IS DISTINCT FROM 'FROZEN' + OR NEW.incarnation_digest IS NOT NULL OR NEW.verification_round IS NOT NULL + OR NEW.verification_cursor IS DISTINCT FROM -1 + OR NEW.verification_complete IS DISTINCT FROM false + OR NEW.new_owner_id IS NOT NULL OR NEW.new_owner_fence IS NOT NULL + OR NEW.new_lease_correlation IS NOT NULL THEN + RAISE EXCEPTION 'Region transfer must start as a clean frozen intent' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER gs_region_owner_transfer_frozen_insert BEFORE INSERT ON game_session_region_owner_transfer + FOR EACH ROW EXECUTE FUNCTION require_gs_frozen_region_owner_transfer_insert(); + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1064' + ) AND ($needle$; + replacement := $replacement$WHERE version='1064' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.2__require_frozen_region_transfer_insert.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.2' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1064'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.2'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1064','V1064__restore_final_human_completion_lower_bound.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.2'',''V1065.0.2__require_frozen_region_transfer_insert.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua index 21ea5bff33..2a3098ac2e 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua @@ -256,7 +256,10 @@ if capacityType ~= 'hash' or redis.call('PTTL', KEYS[7]) ~= -1 or redis.call('HGET', KEYS[7], 'binding') ~= capacityBytes or redis.call('HGET', KEYS[7], 'digest') ~= capacityDigest then return -1 end local capacityState = redis.call('HGET', KEYS[7], 'state') -if capacityState == 'CLOSED' then return 7 end +if capacityState == 'CLOSED' then + if redis.call('HLEN', KEYS[7]) ~= 3 then return -1 end + return 7 +end if capacityState ~= 'AUTHORIZED' and capacityState ~= 'COMMITTED' then return -1 end if (capacityState == 'AUTHORIZED' and redis.call('HLEN', KEYS[7]) ~= 3) or (capacityState == 'COMMITTED' and redis.call('HLEN', KEYS[7]) ~= 6) then return -1 end diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json index d87f69ca05..6540f69df7 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.original-new-final-admission.v1", "resourcePath": "redis/lua/game-session-original-new-final-admission.lua", - "sha256": "d6e268e1bbe91255f82714646f4051eee9424da1949fa806a1a431d21096c427", + "sha256": "a36f23363c457dfacc32dcd9b82c6da0e02854ec9897ce10556dffadc1502a93", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java index e98b8d7949..f2cbc0de90 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java @@ -433,6 +433,20 @@ void alreadyClosedFenceIsReadOnlyAndNeverReclassifiesTheHistoricalOutcome() thro assertHash(original.keys()[6], capacityPhysicalFields(original, "CLOSED")); } + @Test + void installAndFinalRefuseMalformedClosedExecutionWithoutChangingAnyKey() throws Exception { + ScriptCase original = seed(); + assertThat(eval(action(original, "CLOSE"))).isEqualTo(4L); + assertThat(eval(action(original, "INSTALL"))).isEqualTo(7L); + assertThat(eval(original)).isEqualTo(7L); + + admin.hset(ascii(original.keys()[6]), ascii("unexpected"), ascii("value")); + Map malformed = physicalImage(original); + assertThat(eval(action(original, "INSTALL"))).isEqualTo(-1L); + assertThat(eval(original)).isEqualTo(-1L); + assertPhysicalImage(original, malformed, 7); + } + @Test void expiredFirstFenceRefusesBothAbsentAndAuthorizedWithoutAnyMutation() throws Exception { for (boolean install : new boolean[] {false, true}) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 74f1ded699..23c928e469 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -720,6 +720,55 @@ void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throw proof.seedUndeliveredDispatch(proof.execution); String original = proof.originalImage(); assertSqlGuard(() -> proof.rawReplaceOwner("unretained-successor", "e".repeat(64))); + String forgedOwner = "forged-successor"; + String forgedLease = "e".repeat(64); + long forgedFence = + proof + .sql + .fetchSingle("SELECT nextval('game_session_region_executor_fence_seq')") + .get(0, Long.class); + for (String state : List.of("COMPLETED", "FROZEN")) { + boolean completed = "COMPLETED".equals(state); + assertThatThrownBy( + () -> + proof.sql.execute( + "INSERT INTO game_session_region_owner_transfer" + + " (transfer_id,tenant_id,game_instance_id,region_id,region_epoch,old_owner_id,old_owner_fence," + + " old_lease_correlation,source_digest,intent_digest,state,incarnation_digest,verification_round," + + " verification_cursor,verification_complete,new_owner_id,new_owner_fence,new_lease_correlation)" + + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,true,?,?,?)", + UUID.randomUUID(), + proof.scope.tenantId(), + proof.scope.gameInstanceId(), + proof.scope.regionId(), + proof.prior.regionEpoch(), + proof.prior.ownerInstanceId(), + proof.prior.executorFence().longValueExact(), + proof.prior.leaseTokenCorrelation(), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64), + state, + "sha256:" + "a".repeat(64), + UUID.randomUUID(), + 0L, + completed ? forgedOwner : null, + completed ? forgedFence : null, + completed ? forgedLease : null)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Region transfer must start as a clean frozen intent"); + } + assertSqlGuard( + () -> + proof.sql.execute( + "UPDATE game_session_region_runtime_status SET owner_instance_id=?,executor_fence=?,lease_token_correlation=?" + + " WHERE tenant_id=? AND game_instance_id=? AND region_id=?", + forgedOwner, + forgedFence, + forgedLease, + proof.scope.tenantId(), + proof.scope.gameInstanceId(), + proof.scope.regionId())); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); UUID id = proof.begin(); assertSqlGuard(() -> proof.rawReplaceOwner("frozen-successor", "e".repeat(64))); proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index a8c0998997..7c4c5ee25a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(10); + assertThat(catalog.catalogEpoch()).isEqualTo(11); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -172,7 +172,12 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB assertThat(catalog.schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.ROUTINE) .anyMatch(fact -> fact.kind() == FactKind.MIGRATION) - .anyMatch(fact -> fact.kind() == FactKind.TRIGGER) + .anyMatch( + fact -> + fact.kind() == FactKind.TRIGGER + && fact.identity() + .equals( + "game_session_region_owner_transfer.gs_region_owner_transfer_frozen_insert")) .anyMatch(fact -> fact.kind() == FactKind.SEQUENCE); assertThat( catalog.schemaFacts().stream() @@ -189,7 +194,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1063", "catalog-installation:1064", "catalog-installation:1065", - "catalog-installation:1065.0.1") + "catalog-installation:1065.0.1", + "catalog-installation:1065.0.2") .noneMatch( identity -> identity.contains(":1057:") @@ -201,7 +207,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1063:") || identity.contains(":1064:") || identity.contains(":1065:") - || identity.contains(":1065.0.1:")); + || identity.contains(":1065.0.1:") + || identity.contains(":1065.0.2:")); assertThat( f.dsl .fetchSingle( @@ -744,7 +751,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(10); + assertThat(original.catalog().catalogEpoch()).isEqualTo(11); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -880,7 +887,17 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( } for (String version : List.of( - "1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065", "1065.0.1")) { + "1057", + "1058", + "1059", + "1060", + "1061", + "1062", + "1063", + "1064", + "1065", + "1065.0.1", + "1065.0.2")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -909,7 +926,17 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( } for (String version : List.of( - "1057", "1058", "1059", "1060", "1061", "1062", "1063", "1064", "1065", "1065.0.1")) { + "1057", + "1058", + "1059", + "1060", + "1061", + "1062", + "1063", + "1064", + "1065", + "1065.0.1", + "1065.0.2")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -930,12 +957,12 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip try (Fixture f = fixture(null)) { var original = f.owner().capture(request()); f.addComponent(); - for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12}) { + for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13}) { assertThatThrownBy(() -> f.installEpoch(invalid)) .hasMessageContaining("exact classified installed schema"); } // Controlled explicit owner revision, not an exposed registry/runtime mutation API. - f.installEpoch(11); + f.installEpoch(12); assertThatThrownBy(() -> f.owner().capture(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().readExact(original.request())) @@ -943,9 +970,9 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip assertThat(f.evidence(original.request())) .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().capture(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(11); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(12); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count(EPOCHS)).isEqualTo(11); + assertThat(f.count(EPOCHS)).isEqualTo(12); } } @@ -982,9 +1009,9 @@ void metadataEpochAndSnapshotGuardsRefuseMutationStaleBytesAndChangedExactSqlFra "INSERT INTO " + EPOCHS + "(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 11,catalog_bytes,catalog_digest FROM " + + " SELECT 12,catalog_bytes,catalog_digest FROM " + EPOCHS - + " WHERE catalog_epoch=10")) + + " WHERE catalog_epoch=11")) .hasMessageContaining("exact classified installed schema"); assertThatThrownBy( () -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionRedisCommandTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionRedisCommandTest.java index b24e71c9cf..7d951b90dd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionRedisCommandTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityExecutionRedisCommandTest.java @@ -27,6 +27,7 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.function.LongSupplier; +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.redis.contracts.RedisScriptCatalog; @@ -175,17 +176,20 @@ private static final class Fixture { @SuppressWarnings("unchecked") Fixture() { - UUID tenant = UUID.randomUUID(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var player = (TenantCapacityAdmission.PlayerContext) request.context(); + UUID tenant = request.identity().tenantId(); + UUID transitionId = request.identity().admissionId(); var binding = new CanonicalGameplayBindingIdentity( - UUID.randomUUID(), + player.accountId(), tenant, - UUID.randomUUID(), - UUID.randomUUID(), + player.playableStateNamespaceId(), + player.characterId(), "SHARED", - UUID.randomUUID(), + player.gameInstanceId(), 1, - UUID.randomUUID().toString(), + player.sessionId().toString(), UUID.randomUUID(), BigInteger.ONE, "firemud-account-service", @@ -193,8 +197,10 @@ private static final class Fixture { BigInteger.ONE, BigInteger.ONE, BigInteger.ONE); - UUID transitionId = UUID.randomUUID(); + byte[] candidateBytes = "controlled-candidate".getBytes(StandardCharsets.US_ASCII); + byte[] executionBytes = "controlled-execution".getBytes(StandardCharsets.US_ASCII); when(candidate.bindingIdentity()).thenReturn(binding); + when(candidate.bindingDecisionId()).thenReturn(transitionId); when(candidate.transition()) .thenReturn( new CanonicalGameplayOriginalNewCandidate.TransitionSource( @@ -204,8 +210,7 @@ private static final class Fixture { UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())); - when(candidate.canonicalBytes()) - .thenAnswer(ignored -> "controlled-candidate".getBytes(StandardCharsets.US_ASCII)); + when(candidate.canonicalBytes()).thenAnswer(ignored -> candidateBytes.clone()); when(assignment.isBindingTransition()).thenReturn(true); when(assignment.transitionId()).thenReturn(transitionId); when(assignment.tenantId()).thenReturn(tenant); @@ -216,12 +221,13 @@ private static final class Fixture { when(assignment.sessionId()).thenReturn(binding.sessionId()); when(assignment.bindingRef()).thenReturn(binding.bindingRef()); when(assignment.tenantGameplayTag()).thenReturn("g1-0123456789abcdef0123456789abcdef"); - TenantCapacityAdmission.Request request = mock(); - when(request.admissionAttemptId()).thenReturn(UUID.randomUUID()); when(execution.request()).thenReturn(request); - when(execution.canonicalBytes()) - .thenAnswer(ignored -> "controlled-execution".getBytes(StandardCharsets.US_ASCII)); - when(execution.digest()).thenReturn("sha256:" + "a".repeat(64)); + when(execution.canonicalBytes()).thenAnswer(ignored -> executionBytes.clone()); + when(execution.digest()) + .thenReturn(CanonicalGameplayIssuerMemberV2Codec.sha256(executionBytes)); + when(execution.candidateDigest()) + .thenReturn(CanonicalGameplayIssuerMemberV2Codec.sha256(candidateBytes)); + when(execution.transitionId()).thenReturn(transitionId); RedisAsyncCommands commands = mock( RedisAsyncCommands.class, From c7ef5a966346fb74a51d84adc5ab836a889926c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:38:55 +1300 Subject: [PATCH 46/52] Keep capacity admission deadlines and initial execution custody exact --- .../game-session-service/runtime-and-data.md | 6 +- ...tionCompletionPostgresIntegrationTest.java | 21 ++++- .../capacity/CapacityAdmissionDigestTest.java | 2 +- ...NewCapacityExecutionReadGrpcCodecTest.java | 2 +- .../TenantCapacityAdmissionGrpcCodecTest.java | 2 +- .../client/AccountTenantCapacityClient.java | 20 +++-- ...GameplayRegionOwnerTransferRepository.java | 10 ++- ...re_initial_capacity_execution_dispatch.sql | 51 +++++++++++++ ...untimeStatusRepositoryIntegrationTest.java | 44 ++++++++++- ...eFamilyCatalogPostgresIntegrationTest.java | 76 ++++++++++++++++--- .../AccountTenantCapacityClientMtlsTest.java | 76 ++++++++++++++++++- 11 files changed, 274 insertions(+), 36 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1065.0.3__require_initial_capacity_execution_dispatch.sql diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 64fce1c615..36a0d35ce0 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -2,7 +2,7 @@ ## Original NEW capacity execution evidence -V1063 adds retained exact original capacity execution evidence and the final transition's execution-digest receipt binding. This is not reservation, quota or usage authority. Account alone finalizes, releases or rearms the same reservation after its exact authenticated terminal proof. SQL persists one original installation-dispatch marker before Redis. Only the transaction's successful creator may dispatch installation once; retries only independently inspect the existing record. A lost dispatch reply or missing/reset record is indeterminate and is never recreated from a historical authorization. +V1063 adds retained exact original capacity execution evidence and the final transition's execution-digest receipt binding. This is not reservation, quota or usage authority. Account alone finalizes, releases or rearms the same reservation after its exact authenticated terminal proof. SQL persists one original installation-dispatch marker before Redis. The execution insert guard requires installation-dispatch state for a new ordinary execution. Only the transaction's successful creator may dispatch installation once. Retries independently inspect the existing record. A lost dispatch reply or missing/reset record is indeterminate and is never recreated from a historical authorization. The seven-key tenant-slot final script atomically serializes `FINAL` against permanent same-attempt `CLOSE`, retaining the complete attempt envelope, reservation fence/expiry, original owner and actual committed session hash/times. New execution requires the exact persistent `AUTHORIZED` record and an unexpired reservation at Redis `TIME`. Account transition restrictions, coupled to the irreversible closure, exclude a delayed final CAS after release or rearm without relying on a one-time remote current-fence read. Original evidence is immutable and retained without TTL, deletion or truncation. V1063 separately classifies the evidence family and seals the next runtime-family catalog epoch without changing retained predecessor epochs or migration histories. @@ -16,7 +16,7 @@ The capacity execution owner uses one absolute budget for each complete operatio Game Session may exclude an unresolved original from future execution while its historical outcome remains indeterminate. This normal-handoff operation is separate from original-attempt closure, reservation recovery and cleanup. Its permanent tenant-slot `FENCED_INDETERMINATE` hash contains only the exact retained execution binding, digest and denying state. It may be created when the execution key is absent or replace the state of an exact persistent `AUTHORIZED` hash; neither action establishes that an earlier effect did not happen. The existing `INSTALL`, `FINAL` and `CLOSE` arms, including the predecessor script, reject that state. It never creates an authorization, session candidate, session or index, and supplies no `NOT_EXECUTED_AFTER_AUTHORIZATION` evidence. The Account reservation, original attempt/fence and complete capacity hold remain pending or quarantined under Account's existing recovery policy. -After the ordinary timeline/incarnation qualification and lost-completion checks, the contender must acquire the successor Redis grant before freezing the current generation. A still-renewing incumbent therefore rejects the contender without transfer or execution-fence mutation. Before freezing, the contender rechecks the exact source, protected incarnation, initialized timeline and current grant; after fencing it renews and revalidates the grant before protected installation. Grant acquisition does not replace the transfer proof. The handoff freezes one absolute deadline before inventory selection, capped at five seconds and the incoming deadline. Initial provisional/candidate selection, exact committed-source selection and every later installation source revalidation use that same deadline and the original inventory provider through the existing bounded resource worker. Each scoped SQL context owns its derived connection and transaction provider; blocked acquisition, query cancellation and uncertain release retain their existing custody rules. An expired read cannot authorize successor installation. Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The database dispatch guard locks the same runtime row and verifies the exact active selected owner. A newly inserted transfer must start FROZEN with no successor or verification evidence. Both a frozen generation and the completed predecessor refuse new dispatch markers, including during the transaction that installs the successor. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. +After the ordinary timeline/incarnation qualification and lost-completion checks, the contender must acquire the successor Redis grant before freezing the current generation. A still-renewing incumbent therefore rejects the contender without transfer or execution-fence mutation. Before freezing, the contender rechecks the exact source, protected incarnation, initialized timeline and current grant; after fencing it renews and revalidates the grant before protected installation. Grant acquisition does not replace the transfer proof. The handoff freezes one absolute deadline before inventory selection, capped at five seconds and the incoming deadline. Initial provisional/candidate selection, exact committed-source selection and every later installation source revalidation use that same deadline and the original inventory provider through the existing bounded resource worker. Each scoped SQL context owns its derived connection and transaction provider; blocked acquisition, query cancellation and uncertain release retain their existing custody rules. An expired read cannot authorize successor installation. Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The database dispatch guard locks the same runtime row and verifies the exact active selected owner. A newly inserted transfer must start FROZEN with no successor or verification evidence. Both a frozen generation and the completed predecessor refuse new dispatch markers, including during the transaction that installs the successor. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A lookup for one frozen transition returns unavailable when its captured execution is ambiguous. Whole-region enrollment retains every original. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. The protected receiver has a separate `REGION_OWNER_TRANSFER` purpose and signed schema. Its actual SQL source binds the frozen transfer, original execution, immutable tenant-tag assignment and complete protected deployment/registry/ACL/configuration/storage/AOF identity. Nonce, signature, exact carrier, time and two-source-read checks apply to each observation. Before and after fencing, and around a complete streamed physical verification before owner installation, fresh purpose-correct observations must agree with the transfer's retained incarnation. Historical SQL receipts alone cannot qualify a missing marker or a changed, unavailable, reset, restored or rolled-back store. Verification never recreates a previously retained missing fence. An inventory which cannot be completely re-read within the operation deadline remains frozen rather than dropping the currentness requirement. Normal handoff does not authorize adoption across storage loss; the owning reset/recovery qualification remains required. @@ -104,7 +104,7 @@ Game Session's runtime-family catalog is a manually composed **LOCAL SQL** sourc The catalog seals the actual current Game Session PostgreSQL schema, not a historical union of `CREATE TABLE` statements, a prefix exclusion or a static expected-table response. Every installed table, including empty tables, requires an explicit family disposition; named mixed components additionally bind their actual columns. Sorted definition digests cover tables, columns, constraints, indexes, triggers, routines, sequences, views, types, policies and rules, alongside the actual configured Flyway history. View and materialized-view facts bind both the query definition and relation options, including security-invoker, security-barrier and materialized-view storage settings; changing options invalidates the current seal even when the query text is unchanged. Unknown or removed relations/components refuse capture; changed schema definitions, routines, classification or prior/later migration facts invalidate the sealed epoch and previously retained reads. A new epoch requires an explicit monotonic owner installation against the complete current classified schema, not automatic resampling during a read. -Flyway writes each installing migration's own history row only after its migration transaction. The seal therefore binds distinct stable V1057, V1058, V1059, V1060, V1061, V1062, V1063, V1064, V1065, V1065.0.1 and V1065.0.2 installation markers and the actual installed definitions; it excludes only those eleven installing history rows without inventing or claiming their eventual checksums. After installation, capture/readback additionally require exactly one successful SQL row for each version with its exact installing script in the configured history table. All other prior and later history facts remain part of the seal. Each forward installer seals the next monotonic owner epoch only after all routine replacements: V1058 binds view options, V1059 narrows the initial-preparation public-target conflict while preserving retained private projections, V1060 installs classified private catalog revision history/current-head control relations, and V1061 adds immutable private FRESH runtime identity provenance and seals epoch `5`; V1062 adds pending source protection and its writer guards before sealing epoch `6`; V1063 adds exact original-NEW capacity execution and its final-receipt binding before sealing epoch `7`; V1064 restores the final Human runtime completion row-version lower bound while preserving the full current RUNNING launch, candidate, capacity and identity guard, then seals epoch `8`; V1065 adds retained normal-handoff transfer control and per-original fencing receipt families before sealing epoch `9`; V1065.0.1 requires the current durable region owner for capacity dispatch and seals epoch `10`; V1065.0.2 requires every new transfer to enter through the initial FROZEN state and seals epoch `11`. Earlier migrations and all retained epoch, snapshot and history bytes remain immutable. Requests retained under an older epoch conflict with the current epoch rather than being rewritten or resampled. Other installation and retention obligations remain with the [database migration owner](../../system-architecture-database-migrations.md); the configured history table, rather than an assumed `flyway_schema_history` alias, is itself explicitly classified as retained control evidence. +Flyway writes each installing migration's own history row only after its migration transaction. The seal therefore binds distinct stable V1057, V1058, V1059, V1060, V1061, V1062, V1063, V1064, V1065, V1065.0.1, V1065.0.2 and V1065.0.3 installation markers and the actual installed definitions; it excludes only those twelve installing history rows without inventing or claiming their eventual checksums. After installation, capture/readback additionally require exactly one successful SQL row for each version with its exact installing script in the configured history table. All other prior and later history facts remain part of the seal. Each forward installer seals the next monotonic owner epoch only after all routine replacements: V1058 binds view options, V1059 narrows the initial-preparation public-target conflict while preserving retained private projections, V1060 installs classified private catalog revision history/current-head control relations, and V1061 adds immutable private FRESH runtime identity provenance and seals epoch `5`; V1062 adds pending source protection and its writer guards before sealing epoch `6`; V1063 adds exact original-NEW capacity execution and its final-receipt binding before sealing epoch `7`; V1064 restores the final Human runtime completion row-version lower bound while preserving the full current RUNNING launch, candidate, capacity and identity guard, then seals epoch `8`; V1065 adds retained normal-handoff transfer control and per-original fencing receipt families before sealing epoch `9`. V1065.0.1 requires the current durable region owner for capacity dispatch and seals epoch `10`. V1065.0.2 requires every new transfer to enter through the initial FROZEN state and seals epoch `11`. V1065.0.3 guards initial capacity execution state and seals epoch `12`. Earlier migrations and all retained epoch, snapshot and history bytes remain immutable. Requests retained under an older epoch conflict with the current epoch rather than being rewritten or resampled. Other installation and retention obligations remain with the [database migration owner](../../system-architecture-database-migrations.md); the configured history table, rather than an assumed `flyway_schema_history` alias, is itself explicitly classified as retained control evidence. Gameplay commands and remote work whose namespace partition or replacement class is unresolved remain `UNKNOWN` and blocking, never implicitly S3. Durable tick/effect recovery, selected-work manifests, remote outcomes, script-pin authority/history and region/timeline provenance remain separate blocking evidence rather than cloned gameplay payload or a FRESH manifest. Input history and reconnect context retain their distinct audit/privacy consequences. `game_manifest` remains unsupported unqualified legacy lineage, not a build or FRESH source. Catalog/pointer, original operator/LOGIN/roster/binding/account/issuer authority, installed Saga control, and their original request, nonce, fence, replay, retirement and hold guards retain their owning consequences. Classification grants neither cleanup authority nor permission to discard uncertain work. The private preparation, original allocation and lifecycle-bound catalog revision branch are included as retained control/provenance; `PREPARING` is not a private runtime, CLOSED pointer or readiness result. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 784a2fa95f..0def873ad4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -432,6 +432,8 @@ void overlappingRecoveryCallsCannotInvalidateTheSameWorkersLiveClaim() throws Ex var readStarted = new CountDownLatch(1); var resumeRead = new CountDownLatch(1); var calls = new AtomicInteger(); + var secondWorkerCalls = new AtomicInteger(); + var recoveryClock = Clock.fixed(f.request.evidence().evaluatedAt(), ZoneOffset.UTC); var recovery = new AccountTenantCapacityRecoveryWorker( f.owner, @@ -449,7 +451,17 @@ void overlappingRecoveryCallsCannotInvalidateTheSameWorkersLiveClaim() throws Ex return capacityObservation( request, reservation, AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED); }, - Clock.fixed(Instant.now(), ZoneOffset.UTC)); + recoveryClock); + var secondWorker = + new AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + secondWorkerCalls.incrementAndGet(); + return capacityObservation( + request, reservation, AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED); + }, + recoveryClock); var action = AccountTenantCapacityRecoveryWorker.NoCommitAction.RELEASE; try (var executor = Executors.newSingleThreadExecutor()) { var pending = executor.submit(() -> recovery.reconcile(f.request, action)); @@ -459,6 +471,12 @@ void overlappingRecoveryCallsCannotInvalidateTheSameWorkersLiveClaim() throws Ex .hasMessage("ENTITLEMENT_UNAVAILABLE"); assertThatThrownBy(() -> recovery.rearm(f.request, next)) .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> secondWorker.reconcile(f.request, action)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> secondWorker.rearm(f.request, next)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThat(calls).hasValue(1); + assertThat(secondWorkerCalls).hasValue(0); } finally { resumeRead.countDown(); } @@ -466,6 +484,7 @@ void overlappingRecoveryCallsCannotInvalidateTheSameWorkersLiveClaim() throws Ex assertThat(result.state()).isEqualTo(TenantCapacityAdmission.State.FINALIZED); assertThat(recovery.reconcile(f.request, action)).isEqualTo(result); assertThat(calls).hasValue(1); + assertThat(secondWorkerCalls).hasValue(0); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index dbc77a6006..64cb4d0d06 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -242,7 +242,7 @@ void nonCreatingEvidenceIsValidContentButCannotAuthorizeExecution() { denied.admissionAttemptId(), denied.capacityRearmFence(), denied.mutationDigest(), - java.util.UUID.randomUUID(), + java.util.UUID.fromString("b1111111-1111-4111-8111-111111111111"), 1, denied.evidence().expiresAt(), TenantCapacityAdmission.State.RESERVED, diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecutionReadGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecutionReadGrpcCodecTest.java index 67461f34f4..d8df54ff1e 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecutionReadGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecutionReadGrpcCodecTest.java @@ -95,7 +95,7 @@ private static OriginalNewCapacityExecutionReadGrpcCodec.Selector selector() { request.admissionAttemptId(), request.capacityRearmFence(), request.mutationDigest(), - UUID.randomUUID(), + UUID.fromString("b3333333-3333-4333-8333-333333333333"), 1, CapacityAdmissionTestFixture.NOW.plusSeconds(15), TenantCapacityAdmission.State.RESERVED, diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index d829673131..bea9dda822 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -195,7 +195,7 @@ private static Result result(Request request) { request.admissionAttemptId(), request.capacityRearmFence(), request.mutationDigest(), - UUID.randomUUID(), + UUID.fromString("b2222222-2222-4222-8222-222222222222"), 1, CapacityAdmissionTestFixture.NOW.plusSeconds(15), State.RESERVED, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index fd219bb4ec..b55388c562 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -3,6 +3,7 @@ import io.grpc.Context; import io.grpc.Deadline; import io.grpc.ManagedChannel; +import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.io.IOException; import java.time.Clock; @@ -60,30 +61,33 @@ public void init() throws IOException { * allocates another ID. */ public Result commit(Request request, long absoluteDeadlineMillis) { + long maximumMillis = + TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); + Deadline maximum = Deadline.after(maximumMillis, TimeUnit.MILLISECONDS); requireNoAmbientSql("Capacity commitment requires no ambient SQL"); + long startedMillis = clock.millis(); request.requireStructurallyValid(); if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION || !namespace.equals(request.targetNamespace())) throw new IllegalArgumentException("Exact Game Session context required"); - long remainingMillis = Math.subtractExact(absoluteDeadlineMillis, clock.millis()); + long remainingMillis = Math.subtractExact(absoluteDeadlineMillis, startedMillis); Deadline deadline = - Deadline.after( - Math.min( - TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS), - remainingMillis), + maximum.offset( + Math.max(0L, Math.min(maximumMillis, remainingMillis)) - maximumMillis, TimeUnit.MILLISECONDS); Deadline incoming = Context.current().getDeadline(); if (incoming != null) deadline = deadline.minimum(incoming); var stub = - requireInitializedStub("Account capacity unavailable") + requirePublishedInitializedStub("Account capacity unavailable") .withDeadline(deadline) .withMaxOutboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES) .withMaxInboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_RESPONSE_WIRE_BYTES); try { + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + if (deadline.isExpired()) throw Status.DEADLINE_EXCEEDED.asRuntimeException(); // Exact retry may replay an expired/terminal reservation. The final owner still checks it. return TenantCapacityAdmissionGrpcCodec.requireResponse( - request, - stub.commitTenantCapacityAdmission(TenantCapacityAdmissionGrpcCodec.toRequest(request))); + request, stub.commitTenantCapacityAdmission(wire)); } catch (StatusRuntimeException failure) { throw TenantCapacityAdmissionGrpcCodec.validateFailure(failure); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index c32431c434..cea23fbcd1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -89,18 +89,20 @@ DSLContext sql() { /** Read only an already captured original under its still-current frozen old owner. */ Item frozenOriginal(UUID transitionId) { noSql(); - Record row = + var rows = sql() - .fetchOne( + .fetch( "SELECT i.transfer_id,i.target_ordinal,i.execution_digest FROM " + ITEM + " i JOIN " + TRANSFER + " t ON t.transfer_id=i.transfer_id" + " JOIN game_session_original_new_capacity_execution e ON e.execution_digest=i.execution_digest" - + " WHERE e.transition_id=? AND t.state='FROZEN'", + + " WHERE e.transition_id=? AND t.state='FROZEN' LIMIT 2", transitionId); - if (row == null) return null; + if (rows.isEmpty()) return null; + if (rows.size() != 1) throw unavailable(); + Record row = rows.getFirst(); UUID id = row.get("transfer_id", UUID.class); current(sql(), id, false); return loadItem( diff --git a/services/game-session-service/src/main/resources/db/migration/V1065.0.3__require_initial_capacity_execution_dispatch.sql b/services/game-session-service/src/main/resources/db/migration/V1065.0.3__require_initial_capacity_execution_dispatch.sql new file mode 100644 index 0000000000..f50a256302 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1065.0.3__require_initial_capacity_execution_dispatch.sql @@ -0,0 +1,51 @@ +-- [jooq ignore start] +CREATE FUNCTION require_gs_initial_capacity_execution_dispatch() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + -- The status constraint and any separately guarded custody states determine the legal + -- initial markers. Positive authorization and terminal proof require a later transition. + IF NEW.status IN ('AUTHORIZED','COMMITTED','CLOSED') OR NEW.terminal_readback IS NOT NULL THEN + RAISE EXCEPTION 'Original NEW capacity execution cannot start with an authorization or terminal proof' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER gs_capacity_execution_initial_dispatch BEFORE INSERT ON game_session_original_new_capacity_execution + FOR EACH ROW EXECUTE FUNCTION require_gs_initial_capacity_execution_dispatch(); + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1064' + ) AND ($needle$; + replacement := $replacement$WHERE version='1064' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1065.0.3__require_initial_capacity_execution_dispatch.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1065.0.3' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1064'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1065.0.3'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1064','V1064__restore_final_human_completion_lower_bound.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1065.0.3'',''V1065.0.3__require_initial_capacity_execution_dispatch.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 23c928e469..382df5a7fa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -601,6 +601,15 @@ void boundedCensusAndVerificationResumeBeyondThirtyTwoWithoutLosingAnyOriginal() UUID id = proof.begin(); var first = proof.captureAndFence(id); assertThat(first).hasSize(32); + assertThat(first) + .allMatch(item -> item.execution().transitionId().equals(proof.execution.transitionId())); + assertThatThrownBy( + () -> + proof.transfers.within( + transferDeadline(), + ignored -> proof.transfers.frozenOriginal(proof.execution.transitionId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Normal region owner transfer is held"); assertThatThrownBy( () -> proof.transfers.within( @@ -714,6 +723,28 @@ void finalQualificationRechecksLostFenceBeyondTheFirstPageWithoutRecreatingIt() } } + @Test + void originalCapacityExecutionRefusesForgedInitialAuthorizationAndTerminalEvidence() + throws Exception { + try (var proof = new TransferSqlProof()) { + byte[] forgedReadback = {1}; + for (String status : List.of("AUTHORIZED", "COMMITTED", "CLOSED", "INSTALL_DISPATCHED")) { + byte[] readback = "AUTHORIZED".equals(status) ? null : forgedReadback; + assertThatThrownBy(() -> proof.insertExecution(proof.execution, status, readback)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining( + "Original NEW capacity execution cannot start with an authorization or terminal proof"); + } + assertThat(proof.executionState(proof.execution)).isNull(); + assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); + + proof.seedUndeliveredDispatch(proof.execution); + assertThat(proof.executionState(proof.execution)).isEqualTo("INSTALL_DISPATCHED"); + assertThat(proof.physicalExecutionExists(proof.execution)).isFalse(); + } + } + @Test void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throws Exception { try (var proof = new TransferSqlProof()) { @@ -1234,12 +1265,17 @@ private UUID begin() { private void seedUndeliveredDispatch(OriginalNewCapacityExecution original) { // Controlled crash-window storage seed only. No guard is disabled, no AUTHORIZED result is // invented, and this is not the real authorize path exercised by the two row-lock races. + insertExecution(original, "INSTALL_DISPATCHED", null); + } + + private void insertExecution( + OriginalNewCapacityExecution original, String status, byte[] terminalReadback) { sql.execute( "INSERT INTO game_session_original_new_capacity_execution" + " (tenant_id,request_id,admission_id,admission_attempt_id,transition_id,capacity_rearm_fence," + " reservation_id,reservation_fence,mutation_digest,execution_digest,canonical_execution," - + " selected_owner_id,selected_owner_fence,tenant_gameplay_tag,status)" - + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,'INSTALL_DISPATCHED')", + + " selected_owner_id,selected_owner_fence,tenant_gameplay_tag,status,terminal_readback)" + + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", original.request().identity().tenantId(), original.request().identity().requestId(), original.request().identity().admissionId(), @@ -1253,7 +1289,9 @@ private void seedUndeliveredDispatch(OriginalNewCapacityExecution original) { original.canonicalBytes(), original.selectedOwnerId(), original.selectedOwnerFence(), - tags.assignmentForTransition(original.transitionId()).tenantGameplayTag()); + tags.assignmentForTransition(original.transitionId()).tenantGameplayTag(), + status, + terminalReadback); } private List captureAndFence(UUID id) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 7c4c5ee25a..08b9e6da58 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -88,7 +88,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(11); + assertThat(catalog.catalogEpoch()).isEqualTo(12); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -178,6 +178,12 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB && fact.identity() .equals( "game_session_region_owner_transfer.gs_region_owner_transfer_frozen_insert")) + .anyMatch( + fact -> + fact.kind() == FactKind.TRIGGER + && fact.identity() + .equals( + "game_session_original_new_capacity_execution.gs_capacity_execution_initial_dispatch")) .anyMatch(fact -> fact.kind() == FactKind.SEQUENCE); assertThat( catalog.schemaFacts().stream() @@ -195,7 +201,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1064", "catalog-installation:1065", "catalog-installation:1065.0.1", - "catalog-installation:1065.0.2") + "catalog-installation:1065.0.2", + "catalog-installation:1065.0.3") .noneMatch( identity -> identity.contains(":1057:") @@ -208,7 +215,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1064:") || identity.contains(":1065:") || identity.contains(":1065.0.1:") - || identity.contains(":1065.0.2:")); + || identity.contains(":1065.0.2:") + || identity.contains(":1065.0.3:")); assertThat( f.dsl .fetchSingle( @@ -751,7 +759,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(11); + assertThat(original.catalog().catalogEpoch()).isEqualTo(12); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -897,7 +905,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1064", "1065", "1065.0.1", - "1065.0.2")) { + "1065.0.2", + "1065.0.3")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -936,7 +945,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1064", "1065", "1065.0.1", - "1065.0.2")) { + "1065.0.2", + "1065.0.3")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -957,12 +967,12 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip try (Fixture f = fixture(null)) { var original = f.owner().capture(request()); f.addComponent(); - for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13}) { + for (long invalid : new long[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14}) { assertThatThrownBy(() -> f.installEpoch(invalid)) .hasMessageContaining("exact classified installed schema"); } // Controlled explicit owner revision, not an exposed registry/runtime mutation API. - f.installEpoch(12); + f.installEpoch(13); assertThatThrownBy(() -> f.owner().capture(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().readExact(original.request())) @@ -970,9 +980,9 @@ void explicitNewOwnerEpochRetainsButInvalidatesOldRequestsAndRejectsReusedOrSkip assertThat(f.evidence(original.request())) .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().capture(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(12); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(13); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count(EPOCHS)).isEqualTo(12); + assertThat(f.count(EPOCHS)).isEqualTo(13); } } @@ -1009,9 +1019,9 @@ void metadataEpochAndSnapshotGuardsRefuseMutationStaleBytesAndChangedExactSqlFra "INSERT INTO " + EPOCHS + "(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 12,catalog_bytes,catalog_digest FROM " + + " SELECT 13,catalog_bytes,catalog_digest FROM " + EPOCHS - + " WHERE catalog_epoch=11")) + + " WHERE catalog_epoch=12")) .hasMessageContaining("exact classified installed schema"); assertThatThrownBy( () -> @@ -1593,6 +1603,48 @@ void genuineV1064ToV1065TransferFenceUpgradeRetainsOriginalRowsSnapshotsAndEpoch } } + @Test + void initialCapacityExecutionGuardUpgradeRetainsEarlierEpochsAndHistory() { + try (Fixture f = fixture("1065.0.2")) { + f.populatePredecessor(); + var original = f.owner().capture(request()); + assertThat(original.catalog().catalogEpoch()).isEqualTo(11); + var history = f.historyRows(false); + var epochs = + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e ORDER BY catalog_epoch") + .getValues(0, String.class); + var before = f.rows(f.tables()); + before.remove(f.history); + before.remove(EPOCHS); + + migration(f.source, f.schema, f.history, "1065.0.3").migrate(); + + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat(f.historyRows(false)).hasSize(history.size() + 1); + assertThat(f.historyRows(false).subList(0, history.size())).isEqualTo(history); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e WHERE catalog_epoch<=11 ORDER BY catalog_epoch") + .getValues(0, String.class)) + .isEqualTo(epochs); + assertThat(f.evidence(original.request())) + .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + var current = f.owner().capture(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(12); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + migration(f.source, f.schema, f.history, "1065.0.3").validate(); + } + } + private static Request request() { return new Request(UUID.randomUUID(), "test"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 6dfc209023..cca8da7206 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -5,6 +5,7 @@ import com.google.protobuf.Any; import io.grpc.Context; +import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; @@ -16,16 +17,20 @@ import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import java.net.InetSocketAddress; +import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.time.Clock; import java.time.ZoneOffset; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import javax.net.ssl.SSLException; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; @@ -33,6 +38,7 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; @@ -197,6 +203,42 @@ void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() } } + @Test + void commitReachesItsTransportDeadlineWhileTlsReloadIsBlocked() throws Exception { + var calls = new AtomicInteger(); + var respond = new AtomicBoolean(true); + var tls = pki.clientProperties(directory, pki.identity("client")); + var factory = new BlockingReloadChannelFactory(); + var server = server("account", calls, false, new AtomicLong(), respond); + try (var client = client(server, tls, factory); + var executor = Executors.newSingleThreadExecutor()) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + client.commit(request, deadline()); + respond.set(false); + try { + Files.writeString(Path.of(tls.getCertChain()), "\n", StandardOpenOption.APPEND); + assertThat(factory.reloadStarted.await(5, TimeUnit.SECONDS)).isTrue(); + long explicitDeadline = CapacityAdmissionTestFixture.NOW.toEpochMilli() + 1_000L; + var timedOut = + executor.submit( + () -> + assertThatThrownBy(() -> client.commit(request, explicitDeadline)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); + timedOut.get(3, TimeUnit.SECONDS); + assertThat(calls).hasValue(2); + } finally { + factory.releaseReload.countDown(); + } + } finally { + stop(server); + } + } + @Test void incomingDeadlineBoundsAStalledAccountCall() throws Exception { AtomicInteger calls = new AtomicInteger(); @@ -253,12 +295,18 @@ private static long deadline() { } private static AccountTenantCapacityClient client(Server server) throws Exception { + return client( + server, pki.clientProperties(directory, pki.identity("client")), new GrpcChannelFactory()); + } + + private static AccountTenantCapacityClient client( + Server server, CommonGrpcClientProperties tls, GrpcChannelFactory factory) { var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + server.getPort()); return new AccountTenantCapacityClient( endpoints, - pki.clientProperties(directory, pki.identity("client")), - new GrpcChannelFactory(), + tls, + factory, "prod", Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC)); } @@ -347,4 +395,28 @@ private static void stop(Server server) throws InterruptedException { server.shutdownNow(); assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); } + + private static final class BlockingReloadChannelFactory extends GrpcChannelFactory { + private final AtomicBoolean initialBuild = new AtomicBoolean(true); + private final CountDownLatch reloadStarted = new CountDownLatch(1); + private final CountDownLatch releaseReload = new CountDownLatch(1); + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + if (!initialBuild.getAndSet(false)) { + reloadStarted.countDown(); + try { + if (!releaseReload.await(10, TimeUnit.SECONDS)) { + throw new SSLException("Test reload release timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new SSLException("Test reload wait interrupted", interrupted); + } + } + return super.buildChannel(target, defaultPort, properties, keepAlive); + } + } } From a4133bcac04f403102cfe07cc9195305b44e5b38 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:47:14 +1300 Subject: [PATCH 47/52] Publish TLS replacements before retirement and verify exact retention paths --- .../AbstractReloadingBlockingGrpcClient.java | 7 +- ...stractReloadingBlockingGrpcClientTest.java | 36 +++++++ ...GameplayRegionOwnerTransferRepository.java | 23 ++--- ...NewFinalAdmissionOwnerIntegrationTest.java | 95 ++++++++++--------- ...untimeStatusRepositoryIntegrationTest.java | 13 +++ ...riginalNewCapacityExecutionBudgetTest.java | 18 +++- 6 files changed, 132 insertions(+), 60 deletions(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index ed4f21d6c5..a339e66225 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -161,11 +161,12 @@ protected final synchronized void reloadChannel() throws SSLException { newChannel.shutdown(); throw e; } - if (channel != null) { - channel.shutdown(); - } + ManagedChannel previous = channel; channel = newChannel; stub = newStub; + if (previous != null) { + previous.shutdown(); + } } protected final TStub stub() { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 66a777feb7..3b4609f370 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -2,9 +2,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; import java.io.IOException; @@ -14,6 +19,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -76,6 +82,36 @@ void explicitLifecycleInitializesOnceAndRejectsUseAfterClose() throws Exception .hasMessage("test client is closed"); } + @Test + void replacementStubIsPublishedWhenPreviousChannelStartsShutdown() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var previous = mock(ManagedChannel.class); + var replacement = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous, replacement); + var stubAtShutdown = new AtomicReference(); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + client.initExplicit(); + var original = client.requirePublishedExplicitStub(); + when(previous.shutdown()) + .thenAnswer( + invocation -> { + stubAtShutdown.set(client.requirePublishedExplicitStub()); + return previous; + }); + + client.reloadChannel(); + + var published = client.requirePublishedExplicitStub(); + assertThat(published).isNotSameAs(original); + assertThat(stubAtShutdown.get()).isSameAs(published); + verify(previous).shutdown(); + } + verify(replacement).shutdown(); + } + @Test void initialisationFailurePreventsLateReloadFromCreatingAnotherChannel(@TempDir Path directory) throws Exception { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index cea23fbcd1..7fe91281cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -550,17 +550,18 @@ static void completeTerminalOnly( if (exists( tx, "SELECT 1" + PENDING, prior.tenantId(), prior.gameInstanceId(), prior.regionId())) throw unavailable(); - tx.execute( - "UPDATE " - + TRANSFER - + " SET state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=? WHERE tenant_id=? AND game_instance_id=? AND region_id=? AND old_owner_fence=? AND state='FROZEN'", - newOwner, - newFence, - newLease, - prior.tenantId(), - prior.gameInstanceId(), - prior.regionId(), - prior.executorFence().longValueExact()); + if (tx.execute( + "UPDATE " + + TRANSFER + + " SET state='COMPLETED',new_owner_id=?,new_owner_fence=?,new_lease_correlation=? WHERE tenant_id=? AND game_instance_id=? AND region_id=? AND old_owner_fence=? AND state='FROZEN'", + newOwner, + newFence, + newLease, + prior.tenantId(), + prior.gameInstanceId(), + prior.regionId(), + prior.executorFence().longValueExact()) + != 1) throw unavailable(); } @Override diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index c28899871c..4f824d6311 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -1175,22 +1175,6 @@ void previouslySplitReceiptRequiresExactPhysicalProofAndRetainsIdempotently() th var source = inventory.readOriginalNewFinalAdmissionSource(decision); var accountOpen = controlledAccountOpen(); var issuerOpen = issuerOpen(); - var sql = fixture.dsl(); - // Model an old receipt-only writer while preserving the actual guarded receipt transaction. - sql.execute( - """ - CREATE FUNCTION fixture_preserve_authorized_execution() RETURNS trigger LANGUAGE plpgsql AS $$ - BEGIN - RETURN OLD; - END; - $$ - """); - sql.execute( - """ - CREATE TRIGGER aaa_fixture_preserve_authorized_execution - BEFORE UPDATE ON game_session_original_new_capacity_execution - FOR EACH ROW EXECUTE FUNCTION fixture_preserve_authorized_execution() - """); try (var credential = new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); var template = credential.template(); @@ -1198,22 +1182,11 @@ FOR EACH ROW EXECUTE FUNCTION fixture_preserve_authorized_execution() finalOwner() .finalizeOriginalNewOnce( source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) { - inventory.commitOriginalNewFinalAdmission(readback); - } finally { - sql.execute( - "DROP TRIGGER aaa_fixture_preserve_authorized_execution ON game_session_original_new_capacity_execution"); - sql.execute("DROP FUNCTION fixture_preserve_authorized_execution()"); + commitHistoricalSplitReceipt(readback); } var request = controlledCapacity.request(); var reservation = controlledCapacity.reservation(); var owner = capacityOwner(); - assertThat(inventory.readOriginalNewFinalAdmissionSource(decision).finalReceipt()).isPresent(); - assertThat( - sql.fetchSingle( - "SELECT status FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", - controlledCapacity.digest()) - .get(0, String.class)) - .isEqualTo("AUTHORIZED"); assertThatThrownBy(() -> owner.readExact(request, reservation)) .isInstanceOf(IllegalStateException.class); var originalPhysical = physicalImage(); @@ -2104,28 +2077,21 @@ void recreatedCapacityOwnerRetainsCommittedSqlBeforeServingCleanup() throws Exce inventory.commitOriginalNewFinalAdmission(actual); finalDigest = actual.finalSessionSha256(); } - // Stop after final SQL commit, before the original coordinator retained terminal evidence. + // A recreated owner can read the retained positive immediately after the receipt commits. String rows = sqlImage(); var physical = physicalImage(); - assertThatThrownBy( - () -> - capacityOwner() - .readExact(controlledCapacity.request(), controlledCapacity.reservation())) - .isInstanceOf(IllegalStateException.class); - assertThat(sqlImage()).isEqualTo(rows); - assertThat(physicalImage()).isEqualTo(physical); - // The existing closure/lifecycle entry point must recover positive custody before refusing - // a negative outcome; no original coordinator or credential is available here. + var retained = + capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); + assertThat(retained.disposition()).isEqualTo("COMMITTED"); + assertThat(retained.physicalDigest()).isEqualTo("sha256:" + finalDigest); assertThatThrownBy( () -> capacityOwner() .closeOriginalAttempt( controlledCapacity.request(), controlledCapacity.reservation())) .isInstanceOf(IllegalStateException.class); - var retained = - capacityOwner().readExact(controlledCapacity.request(), controlledCapacity.reservation()); - assertThat(retained.disposition()).isEqualTo("COMMITTED"); - assertThat(retained.physicalDigest()).isEqualTo("sha256:" + finalDigest); + assertThat(sqlImage()).isEqualTo(rows); + assertThat(physicalImage()).isEqualTo(physical); var assignment = tags.assignmentForTransition(fixture.transitionId()); controlledRemoveServingKeys(source, assignment); var replay = @@ -2338,9 +2304,9 @@ void missingCommittedServingEvidenceCannotReleaseOriginalOwnerCustody() throws E issuerOpen(), controlledCapacity, deadline())) { - inventory.commitOriginalNewFinalAdmission(actual); + commitHistoricalSplitReceipt(actual); } - admin.del(ascii(installation.sessionKey())); + assertThat(admin.del(ascii(installation.sessionKey()))).isEqualTo(1L); String rows = sqlImage(); var physical = physicalImage(); assertThatThrownBy( @@ -3521,6 +3487,47 @@ private String capacityKey(CanonicalGameplayTenantGameplayTagRepository.Assignme + controlledCapacity.request().admissionAttemptId(); } + private void commitHistoricalSplitReceipt( + CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.Readback readback) { + var sql = fixture.dsl(); + // Model the old receipt-only writer while exercising the actual guarded receipt transaction. + sql.execute( + """ + CREATE FUNCTION fixture_preserve_authorized_execution() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + RETURN OLD; + END; + $$ + """); + sql.execute( + """ + CREATE TRIGGER aaa_fixture_preserve_authorized_execution + BEFORE UPDATE ON game_session_original_new_capacity_execution + FOR EACH ROW WHEN (OLD.status = 'AUTHORIZED' AND NEW.status = 'COMMITTED') + EXECUTE FUNCTION fixture_preserve_authorized_execution() + """); + try { + inventory.commitOriginalNewFinalAdmission(readback); + } finally { + sql.execute( + "DROP TRIGGER aaa_fixture_preserve_authorized_execution ON game_session_original_new_capacity_execution"); + sql.execute("DROP FUNCTION fixture_preserve_authorized_execution()"); + } + assertThat( + inventory + .readOriginalNewFinalAdmissionSource(decision) + .finalReceipt() + .orElseThrow() + .finalSessionSha256()) + .isEqualTo(readback.finalSessionSha256()); + var execution = + sql.fetchSingle( + "SELECT status, terminal_readback FROM game_session_original_new_capacity_execution WHERE execution_digest = ?", + readback.execution().digest()); + assertThat(execution.get("status", String.class)).isEqualTo("AUTHORIZED"); + assertThat(execution.get("terminal_readback", byte[].class)).isNull(); + } + private void controlledRemoveServingKeys( CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source, CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 382df5a7fa..dd9b643e6c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -748,6 +748,19 @@ void originalCapacityExecutionRefusesForgedInitialAuthorizationAndTerminalEviden @Test void rawOwnerReplacementCannotSkipFrozenIncompleteOrChangedExactTransfer() throws Exception { try (var proof = new TransferSqlProof()) { + assertThatThrownBy( + () -> + proof.sql.transaction( + configuration -> + CanonicalGameplayRegionOwnerTransferRepository.completeTerminalOnly( + DSL.using(configuration), + proof.prior, + "unretained-terminal-successor", + proof.prior.executorFence().longValueExact() + 1, + "e".repeat(64)))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Normal region owner transfer is held"); + assertThat(proof.currentOwner()).isEqualTo(proof.prior); proof.seedUndeliveredDispatch(proof.execution); String original = proof.originalImage(); assertSqlGuard(() -> proof.rawReplaceOwner("unretained-successor", "e".repeat(64))); 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 a622986aa6..b90fc15c28 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 @@ -368,6 +368,7 @@ void cancellationAfterPoolReturnCannotCancelAReusedConnectionStatement() throws when(provider.acquire()).thenReturn(connection); when(statement.execute()).thenReturn(true); CountDownLatch returned = new CountDownLatch(1), finish = new CountDownLatch(1); + CountDownLatch cancellationWorkerFinished = new CountDownLatch(1); doAnswer( invocation -> { returned.countDown(); @@ -385,13 +386,26 @@ void cancellationAfterPoolReturnCannotCancelAReusedConnectionStatement() throws execute(budget.sql(source(provider))); awaitUninterruptibly(finish); return true; - })) + }, + cancellation -> + Thread.ofVirtual() + .name("test-original-new-capacity-cancel") + .unstarted( + () -> { + try { + cancellation.run(); + } finally { + cancellationWorkerFinished.countDown(); + } + }))) .isInstanceOf(IllegalStateException.class); assertThat(returned.await(1, TimeUnit.SECONDS)).isTrue(); - verify(statement, never()).cancel(); } finally { finish.countDown(); } + assertThat(cancellationWorkerFinished.await(2, TimeUnit.SECONDS)).isTrue(); + awaitResourceAndCancellationWorkerCleanup(); + verify(statement, never()).cancel(); } @Test From 961b797bb4f1a039a2fb49b768554cb9bf27f79c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:24:46 +1300 Subject: [PATCH 48/52] Preserve exact capacity commitment and transfer recovery custody --- .../game-session-service/runtime-and-data.md | 4 +- .../client/AccountTenantCapacityClient.java | 20 +- ...lGameplayProtectedIncarnationReceiver.java | 14 +- ...ameplayRegionOwnerTransferCoordinator.java | 13 +- ...yRegionOwnerTransferObservationSource.java | 9 + ...GameplayRegionOwnerTransferRepository.java | 139 ++++++++--- ...e-session-original-new-final-admission.lua | 20 +- ...-session-original-new-final-admission.json | 2 +- ...alNewFinalAdmissionLuaIntegrationTest.java | 21 +- ...NewFinalAdmissionOwnerIntegrationTest.java | 66 +++++- ...untimeStatusRepositoryIntegrationTest.java | 111 ++++++++- ...eFamilyCatalogPostgresIntegrationTest.java | 220 +++++++++++++++--- .../AccountTenantCapacityClientMtlsTest.java | 9 +- 13 files changed, 537 insertions(+), 111 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 36a0d35ce0..36cfd49778 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -16,11 +16,11 @@ The capacity execution owner uses one absolute budget for each complete operatio Game Session may exclude an unresolved original from future execution while its historical outcome remains indeterminate. This normal-handoff operation is separate from original-attempt closure, reservation recovery and cleanup. Its permanent tenant-slot `FENCED_INDETERMINATE` hash contains only the exact retained execution binding, digest and denying state. It may be created when the execution key is absent or replace the state of an exact persistent `AUTHORIZED` hash; neither action establishes that an earlier effect did not happen. The existing `INSTALL`, `FINAL` and `CLOSE` arms, including the predecessor script, reject that state. It never creates an authorization, session candidate, session or index, and supplies no `NOT_EXECUTED_AFTER_AUTHORIZATION` evidence. The Account reservation, original attempt/fence and complete capacity hold remain pending or quarantined under Account's existing recovery policy. -After the ordinary timeline/incarnation qualification and lost-completion checks, the contender must acquire the successor Redis grant before freezing the current generation. A still-renewing incumbent therefore rejects the contender without transfer or execution-fence mutation. Before freezing, the contender rechecks the exact source, protected incarnation, initialized timeline and current grant; after fencing it renews and revalidates the grant before protected installation. Grant acquisition does not replace the transfer proof. The handoff freezes one absolute deadline before inventory selection, capped at five seconds and the incoming deadline. Initial provisional/candidate selection, exact committed-source selection and every later installation source revalidation use that same deadline and the original inventory provider through the existing bounded resource worker. Each scoped SQL context owns its derived connection and transaction provider; blocked acquisition, query cancellation and uncertain release retain their existing custody rules. An expired read cannot authorize successor installation. Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The database dispatch guard locks the same runtime row and verifies the exact active selected owner. A newly inserted transfer must start FROZEN with no successor or verification evidence. Both a frozen generation and the completed predecessor refuse new dispatch markers, including during the transaction that installs the successor. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A lookup for one frozen transition returns unavailable when its captured execution is ambiguous. Whole-region enrollment retains every original. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. +After the ordinary timeline/incarnation qualification and lost-completion checks, the contender must acquire the successor Redis grant before freezing the current generation. A still-renewing incumbent therefore rejects the contender without transfer or execution-fence mutation. Before freezing, the contender rechecks the exact source, protected incarnation, initialized timeline and current grant; after fencing it renews and revalidates the grant before protected installation. Grant acquisition does not replace the transfer proof. The handoff freezes one absolute deadline before inventory selection, capped at five seconds and the incoming deadline. Initial provisional/candidate selection, exact committed-source selection and every later installation source revalidation use that same deadline and the original inventory provider through the existing bounded resource worker. Each scoped SQL context owns its derived connection and transaction provider; blocked acquisition, query cancellation and uncertain release retain their existing custody rules. An expired read cannot authorize successor installation. Before remote fencing, the owner commits one immutable transfer intent for the exact current region generation and World/lifecycle source while holding the region row lock shared with capacity authorization. The database dispatch guard locks the same runtime row and verifies the exact active selected owner. A newly inserted transfer must start FROZEN with no successor or verification evidence. Both a frozen generation and the completed predecessor refuse new dispatch markers, including during the transaction that installs the successor. Bounded deterministic enrollment pages capture every unresolved original in the region, including older generations. A lookup for one frozen transition returns unavailable when its captured execution is ambiguous. If the exact original committed after freeze and before capture, a retry may pin its immutable final receipt and terminal execution under the same frozen predecessor. That source can resume the transfer without inventing a census item or restoring provisional admission authority. Whole-region enrollment retains every unresolved original. A final locked anti-join establishes complete coverage; page completion or a cursor is not completeness. Physical fence receipts and a restartable verification round retain exact original execution/candidate/tag identity. Each operation uses the existing absolute five-second resource budget, and each SQL page contains at most 32 items. Incomplete steps retain their intent and progress for explicit continuation; no new scheduler, unbounded retry loop or fresh-intent escape is supplied. The protected receiver has a separate `REGION_OWNER_TRANSFER` purpose and signed schema. Its actual SQL source binds the frozen transfer, original execution, immutable tenant-tag assignment and complete protected deployment/registry/ACL/configuration/storage/AOF identity. Nonce, signature, exact carrier, time and two-source-read checks apply to each observation. Before and after fencing, and around a complete streamed physical verification before owner installation, fresh purpose-correct observations must agree with the transfer's retained incarnation. Historical SQL receipts alone cannot qualify a missing marker or a changed, unavailable, reset, restored or rolled-back store. Verification never recreates a previously retained missing fence. An inventory which cannot be completely re-read within the operation deadline remains frozen rather than dropping the currentness requirement. Normal handoff does not authorize adoption across storage loss; the owning reset/recovery qualification remains required. -An observed `COMMITTED` hash is not a transfer exemption: the existing positive continuation must verify the complete serving/session/index outcome, persist any missing final SQL receipt and retain immutable `COMMITTED` evidence before that item is handled. Missing positive proof blocks transfer. Existing exact `CLOSED` evidence likewise follows the existing independent closure-retention path. Neither terminal record is overwritten. Only the privately constructed current fencing capability and complete locked inventory check permit the actual acquire/install/revalidate path to install the successor and immutable transfer completion in one transaction. The original attempts remain fenced and non-admitting. A completed transfer supports a separately phase-bound signed currentness read only while its immutable successor still matches the actual current region source; completed observations cannot enroll items, change receipts or authorize another installation. If confirmation fails after SQL commits, the same process can use its retained live grant to recheck the exact completed successor and its retained physical fences before completing installation. A lost or expired grant leaves this continuation held. The original completion reply supplies no authority to recreate a grant or advance another transfer. +An observed `COMMITTED` hash is not a transfer exemption: the existing positive continuation must verify the complete serving/session/index outcome, persist any missing final SQL receipt and retain immutable `COMMITTED` evidence before that item is handled. Missing positive proof blocks transfer. Existing exact `CLOSED` evidence likewise follows the existing independent closure-retention path. Neither terminal record is overwritten. The acquire/install/revalidate path installs the successor and immutable transfer completion in one transaction. A nonempty transfer requires its current fencing capability and complete locked inventory check. A terminal-only transfer requires an empty retained inventory and proof that no unresolved predecessor execution remains. The original attempts remain fenced and non-admitting. A completed transfer supports a separately phase-bound signed currentness read only while its immutable successor still matches the actual current region source; completed observations cannot enroll items, change receipts or authorize another installation. If confirmation fails after SQL commits, the same process can use its retained live grant to recheck the exact completed successor and its retained physical fences, or the exact terminal-only completion and empty inventory, before completing installation. A lost or expired grant leaves this continuation held. The original completion reply supplies no authority to recreate a grant or advance another transfer. An exact retained first-NEW Account-aborted original remains part of the transfer inventory, whether abort preceded capture or completed while the transfer was frozen. Its topology lookup verifies the retained definitive abort and existing immutable mapping without restoring provisional admission authority. First negative closure still requires the complete physical candidate/index proof; already-retained CLOSED replay uses its exact permanent tombstone. Unknown history remains fenced and indeterminate, never discarded because Account or SQL records an abort. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index b55388c562..df3a632c97 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -10,6 +10,7 @@ import java.util.Objects; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; @@ -57,8 +58,8 @@ public void init() throws IOException { /** * The caller must obtain its typed context from current owned player state, not text/metadata. * Retries retain this exact request. The Account call consumes the remaining absolute admission - * budget, capped at five seconds and the incoming deadline. A timeout is indeterminate and never - * allocates another ID. + * budget, capped at five seconds and the incoming deadline. A timeout or an inexact response + * leaves the commitment indeterminate. Retry with the original identity. */ public Result commit(Request request, long absoluteDeadlineMillis) { long maximumMillis = @@ -82,15 +83,22 @@ public Result commit(Request request, long absoluteDeadlineMillis) { .withDeadline(deadline) .withMaxOutboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES) .withMaxInboundMessageSize(TenantCapacityAdmissionGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + CommitTenantCapacityAdmissionResponse response; try { - var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); if (deadline.isExpired()) throw Status.DEADLINE_EXCEEDED.asRuntimeException(); - // Exact retry may replay an expired/terminal reservation. The final owner still checks it. - return TenantCapacityAdmissionGrpcCodec.requireResponse( - request, stub.commitTenantCapacityAdmission(wire)); + response = stub.commitTenantCapacityAdmission(wire); } catch (StatusRuntimeException failure) { throw TenantCapacityAdmissionGrpcCodec.validateFailure(failure); } + try { + // Exact retry may replay an expired/terminal reservation. The final owner still checks it. + return TenantCapacityAdmissionGrpcCodec.requireResponse(request, response); + } catch (IllegalArgumentException inexactResponse) { + throw Status.UNKNOWN + .withDescription("Account capacity commitment response was inexact") + .asRuntimeException(); + } } @Override diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java index 0828a818ad..3e5439828a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -263,10 +263,13 @@ VerifiedIncarnation observeForRegionOwnerTransfer( if (absoluteDeadlineMillis <= clock.millis()) { throw new ObservationUnavailableException("Protected transfer observation deadline expired"); } - CurrentContext before = loadRegionOwnerTransferCurrentContext(transferId, targetOrdinal); + CurrentContext before = + loadRegionOwnerTransferCurrentContext(transferId, targetOrdinal, absoluteDeadlineMillis); return observeCurrentContext( before, - () -> loadRegionOwnerTransferCurrentContext(transferId, targetOrdinal), + () -> + loadRegionOwnerTransferCurrentContext( + transferId, targetOrdinal, absoluteDeadlineMillis), absoluteDeadlineMillis); } @@ -467,17 +470,18 @@ private CurrentContext loadInitialCurrentContext(UUID originalRequestId) { } private CurrentContext loadRegionOwnerTransferCurrentContext( - UUID transferId, long targetOrdinal) { + UUID transferId, long targetOrdinal, long deadline) { requireNoAmbientTransaction(); CanonicalGameplayRegionOwnerTransferObservationSource.Context context = - regionOwnerTransferSource.readCurrent(transferId, targetOrdinal); + regionOwnerTransferSource.readCurrent(transferId, targetOrdinal, deadline); if (context == null || !transferId.equals(context.transferId()) || targetOrdinal != context.targetOrdinal()) { throw new ObservationRejectedException("Protected transfer observation source differs"); } CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = - regionOwnerTransferSource.readAssignment(context.transitionId(), tenantTagRepository); + regionOwnerTransferSource.readAssignment( + context.transitionId(), tenantTagRepository, deadline); if (assignment == null || !assignment.isBindingTransition() || !context.transitionId().equals(assignment.transitionId()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java index 74733c8f83..abf45c3eb3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferCoordinator.java @@ -36,13 +36,13 @@ boolean alreadyCompleted( return repository.completedForCurrent(prior, requestingOwner, deadline); } - CanonicalGameplayRegionOwnerTransferRepository.Item frozenOriginal( + CanonicalGameplayRegionOwnerTransferRepository.FrozenOriginal frozenOriginal( UUID transitionId, long deadline) { return repository.within(deadline, ignored -> repository.frozenOriginal(transitionId)); } void requireFrozenOriginal( - CanonicalGameplayRegionOwnerTransferRepository.Item original, + CanonicalGameplayRegionOwnerTransferRepository.FrozenOriginal original, CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior, long deadline) { @@ -55,7 +55,7 @@ void requireFrozenOriginal( } UUID resume( - CanonicalGameplayRegionOwnerTransferRepository.Item original, + CanonicalGameplayRegionOwnerTransferRepository.FrozenOriginal original, CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior, long deadline) { @@ -74,7 +74,7 @@ private UUID advance( CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior, long deadline, - CanonicalGameplayRegionOwnerTransferRepository.Item original) { + CanonicalGameplayRegionOwnerTransferRepository.FrozenOriginal original) { return repository.within( deadline, budget -> { @@ -177,7 +177,10 @@ CanonicalGameplayRegionRuntimeStatus recoverCompleted( budget -> { var completed = repository.completedSuccessor(transferId, ownerInstance, correlation); var page = repository.completedPage(transferId, -1); - if (page.isEmpty()) throw held(); + if (page.isEmpty()) { + repository.requireTerminalOnlyCompletion(transferId, completed); + return completed.status(); + } var first = page.getFirst(); var before = observe(first, budget.absoluteDeadlineMillis()); if (!before.incarnationDigest().equals(completed.incarnationDigest())) throw held(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java index 4d9c6bd96b..0aea41dccd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java @@ -9,12 +9,21 @@ interface CanonicalGameplayRegionOwnerTransferObservationSource { Context readCurrent(UUID transferId, long targetOrdinal); + default Context readCurrent(UUID transferId, long targetOrdinal, long deadline) { + return readCurrent(transferId, targetOrdinal); + } + /** Independent topology read; SQL implementations retain their operation's admitted budget. */ default CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( UUID transitionId, CanonicalGameplayTenantGameplayTagRepository tags) { return tags.assignmentForTransition(transitionId); } + default CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository tags, long deadline) { + return readAssignment(transitionId, tags); + } + /** * One frozen item and its original owner, with its exact current control phase. A COMPLETED * context requires independently current sealed successor evidence and is read-only currentness, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 7fe91281cf..cb9e4f859d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -86,35 +86,81 @@ DSLContext sql() { return budget.sql(dsl); } - /** Read only an already captured original under its still-current frozen old owner. */ - Item frozenOriginal(UUID transitionId) { + /** + * Pins the captured original or the exact terminal original that committed before capture. + * Neither path creates a transfer, an inventory item or provisional admission authority. + */ + FrozenOriginal frozenOriginal(UUID transitionId) { noSql(); + return readFrozenOriginal(sql(), transitionId); + } + + private FrozenOriginal readFrozenOriginal(DSLContext tx, UUID transitionId) { var rows = - sql() - .fetch( - "SELECT i.transfer_id,i.target_ordinal,i.execution_digest FROM " - + ITEM - + " i JOIN " - + TRANSFER - + " t ON t.transfer_id=i.transfer_id" - + " JOIN game_session_original_new_capacity_execution e ON e.execution_digest=i.execution_digest" - + " WHERE e.transition_id=? AND t.state='FROZEN' LIMIT 2", - transitionId); - if (rows.isEmpty()) return null; - if (rows.size() != 1) throw unavailable(); - Record row = rows.getFirst(); + tx.fetch( + "SELECT i.transfer_id,i.target_ordinal,i.execution_digest FROM " + + ITEM + + " i JOIN " + + TRANSFER + + " t ON t.transfer_id=i.transfer_id" + + " JOIN game_session_original_new_capacity_execution e ON e.execution_digest=i.execution_digest" + + " WHERE e.transition_id=? AND t.state='FROZEN' LIMIT 2", + transitionId); + if (rows.size() > 1) throw unavailable(); + if (rows.size() == 1) { + var row = rows.getFirst(); + UUID id = row.get("transfer_id", UUID.class); + current(tx, id, false); + var item = + loadItem( + tx, + id, + row.get("target_ordinal", Long.class), + row.get("execution_digest", String.class)); + return new FrozenOriginal(id, item.execution().digest(), item.candidate()); + } + + var terminalRows = + tx.fetch( + "SELECT t.transfer_id,e.execution_digest,e.canonical_execution,c.original_new_candidate_bytes" + + " FROM game_session_canonical_binding_transition c" + + " JOIN game_session_original_new_capacity_execution e ON e.transition_id=c.transition_id" + + " AND e.execution_digest=c.original_new_capacity_execution_digest" + + " JOIN game_session_canonical_binding_region_bridge_obligation b ON b.transition_id=c.transition_id" + + " JOIN " + + TRANSFER + + " t ON t.tenant_id=b.tenant_id AND t.game_instance_id=b.game_instance_id" + + " AND t.region_id=b.region_id AND t.region_epoch=b.region_epoch" + + " AND t.old_owner_id=e.selected_owner_id AND t.old_owner_fence=e.selected_owner_fence" + + " WHERE c.transition_id=? AND c.status='COMMITTED' AND e.status='COMMITTED'" + + " AND c.original_new_final_session_sha256 IS NOT NULL AND t.state='FROZEN' LIMIT 2", + transitionId); + if (terminalRows.isEmpty()) return null; + if (terminalRows.size() != 1) throw unavailable(); + var row = terminalRows.getFirst(); UUID id = row.get("transfer_id", UUID.class); - current(sql(), id, false); - return loadItem( - sql(), - id, - row.get("target_ordinal", Long.class), - row.get("execution_digest", String.class)); + var transfer = current(tx, id, false); + byte[] candidateBytes = row.get("original_new_candidate_bytes", byte[].class); + var candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); + var execution = decode(row.get("canonical_execution", byte[].class)); + var binding = candidate.bindingIdentity(); + if (!candidate.bindingDecisionId().equals(transitionId) + || !execution.transitionId().equals(transitionId) + || !execution.digest().equals(row.get("execution_digest", String.class)) + || !execution.candidateDigest().equals(digest(candidateBytes)) + || !execution.selectedOwnerId().equals(transfer.get("old_owner_id", String.class)) + || execution.selectedOwnerFence() != transfer.get("old_owner_fence", Long.class) + || !binding.tenantId().equals(transfer.get("tenant_id", UUID.class)) + || !binding.gameInstanceId().equals(transfer.get("game_instance_id", UUID.class)) + || !binding.regionId().equals(transfer.get("region_id", UUID.class)) + || binding.regionEpoch().longValueExact() != transfer.get("region_epoch", Long.class)) + throw unavailable(); + return new FrozenOriginal(id, execution.digest(), candidate); } /** Revalidate a pinned continuation without creating a replacement transfer intent. */ void requireFrozenOriginal( - Item original, + FrozenOriginal original, CanonicalGameplayRegionRuntimeStatusRepository.Source source, CanonicalGameplayRegionRuntimeStatus prior) { noSql(); @@ -127,14 +173,9 @@ void requireFrozenOriginal( CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(tx); requireOldOwner(tx, source, prior); var row = current(tx, original.transferId(), true); - if (!sourceDigest(source, prior).equals(row.get("source_digest", String.class))) - throw unavailable(); - var actual = - loadItem( - tx, original.transferId(), original.ordinal(), original.execution().digest()); - if (!actual.candidate().equals(original.candidate()) - || !Arrays.equals( - actual.execution().canonicalBytes(), original.execution().canonicalBytes())) + if (!sourceDigest(source, prior).equals(row.get("source_digest", String.class)) + || !original.equals( + readFrozenOriginal(tx, original.candidate().bindingDecisionId()))) throw unavailable(); }); } @@ -302,6 +343,24 @@ CompletedTransfer completedSuccessor(UUID transferId, String ownerInstance, Stri return new CompletedTransfer(status, completed.get("incarnation_digest", String.class)); } + /** Requalifies the existing no-item installation path without synthesizing an observation. */ + void requireTerminalOnlyCompletion(UUID transferId, CompletedTransfer expected) { + var status = expected.status(); + if (expected.incarnationDigest() != null + || exists(sql(), "SELECT 1 FROM " + ITEM + " WHERE transfer_id=?", transferId)) + throw unavailable(); + Record retained = requireCompleted(transferId); + if (retained.get("incarnation_digest") != null + || !status.equals(CanonicalGameplayRegionRuntimeStatusRepository.toStatus(retained)) + || exists( + sql(), + "SELECT 1" + PENDING + " AND e.selected_owner_fence<=?", + status.tenantId(), + status.gameInstanceId(), + status.regionId(), + retained.get("old_owner_fence", Long.class))) throw unavailable(); + } + private Record requireCompleted(UUID transferId) { Record completed = observationCurrent(sql(), transferId); if (!"COMPLETED".equals(completed.get("state", String.class))) throw unavailable(); @@ -566,8 +625,14 @@ static void completeTerminalOnly( @Override public Context readCurrent(UUID transferId, long targetOrdinal) { + return readCurrent(transferId, targetOrdinal, Long.MAX_VALUE); + } + + @Override + public Context readCurrent(UUID transferId, long targetOrdinal, long deadline) { if (admitted.get() == null) - return within(Long.MAX_VALUE, ignored -> readCurrent(transferId, targetOrdinal)); + return within(deadline, ignored -> readCurrent(transferId, targetOrdinal, deadline)); + if (deadline < admitted.get().absoluteDeadlineMillis()) throw unavailable(); Record transfer = observationCurrent(sql(), transferId); Record row = sql() @@ -608,8 +673,15 @@ public Context readCurrent(UUID transferId, long targetOrdinal) { @Override public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( UUID transitionId, CanonicalGameplayTenantGameplayTagRepository sourceTags) { + return readAssignment(transitionId, sourceTags, Long.MAX_VALUE); + } + + @Override + public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment( + UUID transitionId, CanonicalGameplayTenantGameplayTagRepository sourceTags, long deadline) { if (admitted.get() == null) - return within(Long.MAX_VALUE, ignored -> readAssignment(transitionId, sourceTags)); + return within(deadline, ignored -> readAssignment(transitionId, sourceTags, deadline)); + if (deadline < admitted.get().absoluteDeadlineMillis()) throw unavailable(); return sourceTags .withCapacityExecutionDsl(sql()) .assignmentForRetainedCapacityExecution(transitionId); @@ -1000,6 +1072,9 @@ private boolean done() { } } + record FrozenOriginal( + UUID transferId, String executionDigest, CanonicalGameplayOriginalNewCandidate candidate) {} + record Item( UUID transferId, long ordinal, diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua index 2a3098ac2e..417a11e956 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-final-admission.lua @@ -77,6 +77,16 @@ if not capacity or capacity.schema ~= 'gs-original-new-capacity-execution/v1' or not positive(capacity.selectedOwnerFence) then return -2 end local capacityExpiry = exactNumber(capacity.expiresAtMillis) if not capacityExpiry then return -2 end +local capacityNames = {'schema', 'tenantId', 'requestId', 'admissionId', 'admissionAttemptId', + 'reservationId', 'reservationFence', 'capacityRearmFence', 'selectedOwnerId', + 'selectedOwnerFence', 'transitionId', 'expiresAtMillis', 'mutationDigest', 'expiresAt', + 'snapshotIdentity', 'evaluationIdentity', 'candidateDigest', 'canonicalAttemptPayload'} +if not objectWithFields(capacity, capacityNames) then return -2 end +for _, name in ipairs(capacityNames) do + if type(capacity[name]) ~= 'string' or #capacity[name] == 0 then return -2 end +end +if #capacity.candidateDigest ~= 71 + or not string.match(capacity.candidateDigest, '^sha256:[0-9a-f]+$') then return -2 end local tenantId, accountId, namespaceId, characterId = ARGV[1], ARGV[2], ARGV[3], ARGV[4] local gameInstanceId, sessionId, generation, tag = ARGV[5], ARGV[6], ARGV[7], ARGV[8] local candidateBytes, characterBytes, templateBytes = ARGV[9], ARGV[10], ARGV[11] @@ -100,16 +110,6 @@ if KEYS[1] ~= prefix .. slot .. ':' .. gameInstanceId .. ':' .. sessionId -- Only a separately qualified current incarnation may dispatch FENCE during normal owner handoff. -- It excludes future execution, including delayed old callers, but never proves no earlier commit. if action == 'FENCE' then - local capacityNames = {'schema', 'tenantId', 'requestId', 'admissionId', 'admissionAttemptId', - 'reservationId', 'reservationFence', 'capacityRearmFence', 'selectedOwnerId', - 'selectedOwnerFence', 'transitionId', 'expiresAtMillis', 'mutationDigest', 'expiresAt', - 'snapshotIdentity', 'evaluationIdentity', 'candidateDigest', 'canonicalAttemptPayload'} - if not objectWithFields(capacity, capacityNames) then return -2 end - for _, name in ipairs(capacityNames) do - if type(capacity[name]) ~= 'string' or #capacity[name] == 0 then return -2 end - end - if #capacity.candidateDigest ~= 71 - or not string.match(capacity.candidateDigest, '^sha256:[0-9a-f]+$') then return -2 end local capacityType = redis.call('TYPE', KEYS[7]).ok if capacityType ~= 'none' then if capacityType ~= 'hash' or redis.call('PTTL', KEYS[7]) ~= -1 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json index 6540f69df7..3476af2a02 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-final-admission.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.original-new-final-admission.v1", "resourcePath": "redis/lua/game-session-original-new-final-admission.lua", - "sha256": "a36f23363c457dfacc32dcd9b82c6da0e02854ec9897ce10556dffadc1502a93", + "sha256": "a1044f03a1ce67ce7280493afb735119ecd81577cce2c923e98df3ca3826cbc0", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java index f2cbc0de90..fcb46b96ac 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest.java @@ -346,7 +346,7 @@ void absentExecutionFenceInstallsOnlyTheExactPersistentDenyWithoutRecreatingRunt Map before = physicalImage(original); // No credential, template, OPEN barrier, candidate or index is needed to deny future execution. - byte[][] arguments = action(original, "FENCE").arguments().clone(); + byte[][] arguments = original.arguments().clone(); arguments[8] = ascii("unavailable-candidate"); arguments[10] = ascii("unavailable-template"); arguments[12] = ascii("unavailable-account"); @@ -525,7 +525,7 @@ void fenceRefusesWrongTypeTtlIdentityAndEveryUnexpectedPhysicalShapeWithoutMutat } @Test - void fenceRequiresTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() + void allActionsRequireTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() throws Exception { for (String fault : List.of( @@ -544,7 +544,7 @@ void fenceRequiresTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() "wrong-key")) { admin.flushdb(); ScriptCase original = seed(false); - byte[][] arguments = action(original, "FENCE").arguments().clone(); + byte[][] arguments = original.arguments().clone(); String[] keys = original.keys().clone(); var envelope = (tools.jackson.databind.node.ObjectNode) JSON.readTree(arguments[16]); switch (fault) { @@ -565,12 +565,19 @@ void fenceRequiresTheExactCompleteEnvelopeAndCanonicalKeyIdentityBeforeWriting() default -> throw new IllegalStateException("Unknown fixture fault: " + fault); } arguments[16] = canonicalBytes(envelope); - arguments[18] = ascii("sha256:" + HexFormatHolder.sha256(arguments[16])); + String digest = "sha256:" + HexFormatHolder.sha256(arguments[16]); + arguments[18] = ascii(digest); + var template = (tools.jackson.databind.node.ObjectNode) JSON.readTree(arguments[10]); + template.put("capacityExecutionDigest", digest); + arguments[10] = canonicalBytes(template); Map before = physicalImage(original); - assertThat(eval(new ScriptCase(keys, arguments))).as(fault).isEqualTo(-2L); - assertPhysicalImage(original, before, 7); - assertThat(admin.type(ascii(keys[6]))).isEqualTo("none"); + ScriptCase malformed = new ScriptCase(keys, arguments); + for (String verb : List.of("INSTALL", "FINAL", "CLOSE", "FENCE")) { + assertThat(eval(action(malformed, verb))).as("%s %s", verb, fault).isEqualTo(-2L); + assertPhysicalImage(original, before, 7); + assertThat(admin.type(ascii(keys[6]))).isEqualTo("none"); + } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index 4f824d6311..da21f2f3bb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -690,6 +690,7 @@ void processStopAfterActualSqlAuthorizationBeforeRedisSendFencesUnknownAndActual java.nio.file.Files.write(executionFile, controlledCapacity.canonicalBytes()); String jdbcUrl = POSTGRES.getJdbcUrl(); String schema = fixture.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); + var childOutput = directory.resolve("stop-after-authorization.log"); var process = new ProcessBuilder( Path.of(System.getProperty("java.home"), "bin", "java").toString(), @@ -701,10 +702,11 @@ void processStopAfterActualSqlAuthorizationBeforeRedisSendFencesUnknownAndActual POSTGRES.getPassword(), executionFile.toString()) .redirectErrorStream(true) + .redirectOutput(childOutput.toFile()) .start(); try { assertThat(process.waitFor(20, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); - String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + String output = java.nio.file.Files.readString(childOutput, StandardCharsets.UTF_8); assertThat(process.exitValue()).as("Child output: %s", output).isEqualTo(72); assertThat(output).contains("INDEPENDENT_INSTALL_DISPATCHED_COMMIT"); } finally { @@ -1281,6 +1283,68 @@ void committedRedisWinnerMustAcquireFullPositiveSqlRetentionBeforeActualHandoff( .hasMessage("Region transfer changed its original transition"); } + @Test + void frozenTransferResumesExactTerminalOriginalThatCommittedBeforeCapture() throws Exception { + repairAccountMember(); + bridge(); + var source = inventory.readOriginalNewFinalAdmissionSource(decision); + var original = regionBinding.installation(); + var repository = new CanonicalGameplayRegionOwnerTransferRepository(fixture.dsl(), CLOCK, tags); + var receiver = + new CanonicalGameplayControlledRegionTransferObservationFixture() + .receiver(repository, tags); + var transfer = + new CanonicalGameplayRegionOwnerTransferCoordinator( + fixture.dsl(), CLOCK, repository, capacityOwner(), receiver); + UUID transferId; + try (var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(source.candidate(), CLOCK); + var template = credential.template(); + var readback = + finalOwner() + .finalizeOriginalNewOnce( + source, + template, + controlledAccountOpen(), + issuerOpen(), + controlledCapacity, + deadline())) { + transferId = + repository.within( + deadline(), ignored -> repository.begin(original.source, original.status)); + assertThat(transferId).isNotNull(); + inventory.commitOriginalNewFinalAdmission(readback); + } + var captured = repository.within(deadline(), ignored -> repository.capture(transferId)); + assertThat(captured).isEmpty(); + var retained = inventory.readRegionTransferOriginalSource(fixture.transitionId(), source); + byte[] committed = admin.get(ascii(installation.sessionKey())); + assertThat(retained.finalReceipt()).isPresent(); + assertThat( + new CanonicalGameplayRegionRuntimeStatusRepository(fixture.dsl()).find(original.source)) + .contains(original.status); + admin.pexpire(ascii(original.grant.key()), 0); + var successor = + CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal( + fixture.dsl(), ownerClient, catalog, original, sources.resolver, transfer, deadline()); + assertThat(successor.evidence).isNull(); + assertThat(successor.status.executorFence()).isGreaterThan(original.status.executorFence()); + var completed = fixture.dsl().fetchSingle("SELECT * FROM game_session_region_owner_transfer"); + assertThat(completed.get("transfer_id", UUID.class)).isEqualTo(transferId); + assertThat(completed.get("state", String.class)).isEqualTo("COMPLETED"); + assertThat( + fixture + .dsl() + .fetchCount(org.jooq.impl.DSL.table("game_session_region_owner_transfer_item"))) + .isZero(); + assertThat( + inventory + .readRegionTransferOriginalSource(fixture.transitionId(), retained) + .finalReceipt()) + .isEqualTo(retained.finalReceipt()); + assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(committed); + } + @Test void frozenTransferResumesSameCommittedOriginalAfterFenceRetentionFailure() throws Exception { repairAccountMember(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index dd9b643e6c..8c37460ca5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -516,11 +516,13 @@ void frozenContinuationWaitsBeforeRegionWhileAcknowledgedBridgeOwnsInventory() t ExecutorService executor = Executors.newFixedThreadPool(2)) { proof.seedUndeliveredDispatch(proof.execution); UUID id = proof.begin(); + var captured = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertThat(captured).hasSize(1); var original = - proof - .transfers - .within(transferDeadline(), ignored -> proof.transfers.capture(id)) - .getFirst(); + proof.transfers.within( + transferDeadline(), + ignored -> proof.transfers.frozenOriginal(proof.execution.transitionId())); String before = proof.transferImage(id); gate.arm(); Future replay = executor.submit(proof::replayBridge); @@ -723,6 +725,107 @@ void finalQualificationRechecksLostFenceBeyondTheFirstPageWithoutRecreatingIt() } } + @Test + void terminalOnlyTransferRecoversExactCompletedSuccessorAfterOriginalFinalReceipt() + throws Exception { + try (var proof = new TransferSqlProof(); + var credential = + new CanonicalGameplayOriginalNewFinalAdmissionTestFixture( + proof.admission.candidate(), proof.clock); + var raw = credential.template(); + var template = raw.bindCapacityExecution(proof.execution)) { + var account = proof.controlledAccountOpen(); + var issuer = proof.issuerOpen(); + proof + .capacity(proof.sql) + .authorize( + proof.admission, template, account, issuer, proof.execution, transferDeadline()); + try (var readback = + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + proof.redis, proof.scripts, proof.clock, proof.tags) + .finalizeOriginalNewOnce( + proof.admission, + template, + account, + issuer, + proof.execution, + transferDeadline())) { + UUID id = proof.begin(); + assertThatThrownBy( + () -> + proof.coordinator.recoverCompleted( + id, "sql-proof-successor", "e".repeat(64), transferDeadline())) + .isInstanceOf(IllegalStateException.class); + + new CanonicalGameplayBindingInventoryRepository(proof.sql) + .commitOriginalNewFinalAdmission(readback); + assertThat(proof.captureAndFence(id)).isEmpty(); + proof.verifyPage(id); + boolean verified = + proof.transfers.within( + transferDeadline(), ignored -> proof.transfers.finishVerification(id)); + assertThat(verified).isTrue(); + var installed = proof.install(id); + String completion = proof.transferImage(id); + String retained = proof.originalImage(); + assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED"); + assertThat( + proof.coordinator.recoverCompleted( + id, + installed.ownerInstanceId(), + installed.leaseTokenCorrelation(), + transferDeadline())) + .isEqualTo(installed); + assertThatThrownBy( + () -> + proof.coordinator.recoverCompleted( + id, installed.ownerInstanceId(), "f".repeat(64), transferDeadline())) + .isInstanceOf(IllegalStateException.class); + assertThat(proof.currentOwner()).isEqualTo(installed); + assertThat(proof.transferImage(id)).isEqualTo(completion); + assertThat(proof.originalImage()).isEqualTo(retained); + } + } + } + + @Test + void standaloneTransferObservationCancelsBlockedSqlAtItsExplicitDeadline() throws Exception { + try (var proof = new TransferSqlProof(); + var lock = + java.sql.DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { + proof.seedUndeliveredDispatch(proof.execution); + UUID id = proof.begin(); + var captured = + proof.transfers.within(transferDeadline(), ignored -> proof.transfers.capture(id)); + assertThat(captured).hasSize(1); + lock.setSchema(proof.sql.fetchSingle("SELECT current_schema()").get(0, String.class)); + lock.setAutoCommit(false); + try (var statement = lock.createStatement()) { + statement.execute("LOCK TABLE game_session_region_owner_transfer IN ACCESS EXCLUSIVE MODE"); + } + try { + long start = System.nanoTime(); + assertThatThrownBy( + () -> + proof.receiver.observeForRegionOwnerTransfer( + id, captured.getFirst().ordinal(), proof.clock.millis() + 500L)) + .isInstanceOf(IllegalStateException.class); + assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofSeconds(3)); + } finally { + lock.rollback(); + } + assertThat( + proof + .receiver + .observeForRegionOwnerTransfer( + id, captured.getFirst().ordinal(), transferDeadline()) + .regionOwnerTransferContext() + .transferId()) + .isEqualTo(id); + } + } + @Test void originalCapacityExecutionRefusesForgedInitialAuthorizationAndTerminalEvidence() throws Exception { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 08b9e6da58..fe41f4b1a2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -1604,45 +1604,193 @@ void genuineV1064ToV1065TransferFenceUpgradeRetainsOriginalRowsSnapshotsAndEpoch } @Test - void initialCapacityExecutionGuardUpgradeRetainsEarlierEpochsAndHistory() { - try (Fixture f = fixture("1065.0.2")) { - f.populatePredecessor(); - var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(11); - var history = f.historyRows(false); - var epochs = - f.dsl - .fetch( - "SELECT to_jsonb(e)::text||':'||xmin::text FROM " - + EPOCHS - + " e ORDER BY catalog_epoch") - .getValues(0, String.class); - var before = f.rows(f.tables()); - before.remove(f.history); - before.remove(EPOCHS); + void genuineV1065To1065Point0Point1UpgradeRetainsPopulatedCatalogAndAddsCurrentOwnerGuard() { + try (Fixture f = fixture("1065")) { + assertCapacityCatalogGuardUpgrade( + f, + "1065.0.1", + 9, + "V1065.0.1__require_current_capacity_dispatch_owner.sql", + "fence_gs_capacity_dispatch_during_transfer()", + null, + List.of( + "FOR UPDATE", + "current_owner.owner_instance_id IS DISTINCT FROM NEW.selected_owner_id", + "current_owner.executor_fence IS DISTINCT FROM NEW.selected_owner_fence", + "Region dispatch is frozen for normal owner transfer", + "Completed region predecessor cannot acquire dispatch")); + } + } - migration(f.source, f.schema, f.history, "1065.0.3").migrate(); + @Test + void + genuineV1065Point0Point1ToPoint0Point2UpgradeRetainsPopulatedCatalogAndAddsFrozenInsertGuard() { + try (Fixture f = fixture("1065.0.1")) { + assertCapacityCatalogGuardUpgrade( + f, + "1065.0.2", + 10, + "V1065.0.2__require_frozen_region_transfer_insert.sql", + "require_gs_frozen_region_owner_transfer_insert()", + "game_session_region_owner_transfer.gs_region_owner_transfer_frozen_insert", + List.of( + "NEW.state IS DISTINCT FROM 'FROZEN'", + "NEW.incarnation_digest IS NOT NULL", + "NEW.verification_round IS NOT NULL", + "NEW.verification_cursor IS DISTINCT FROM -1", + "NEW.verification_complete IS DISTINCT FROM false", + "NEW.new_owner_id IS NOT NULL", + "NEW.new_owner_fence IS NOT NULL", + "NEW.new_lease_correlation IS NOT NULL", + "Region transfer must start as a clean frozen intent")); + } + } - assertThat(f.rows(before.keySet())).isEqualTo(before); - assertThat(f.historyRows(false)).hasSize(history.size() + 1); - assertThat(f.historyRows(false).subList(0, history.size())).isEqualTo(history); - assertThat( - f.dsl - .fetch( - "SELECT to_jsonb(e)::text||':'||xmin::text FROM " - + EPOCHS - + " e WHERE catalog_epoch<=11 ORDER BY catalog_epoch") - .getValues(0, String.class)) - .isEqualTo(epochs); - assertThat(f.evidence(original.request())) - .isEqualTo(GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(original)); - assertThatThrownBy(() -> f.owner().readExact(original.request())) - .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); - var current = f.owner().capture(request()); - assertThat(current.catalog().catalogEpoch()).isEqualTo(12); - assertThat(f.owner().readExact(current.request())).isEqualTo(current); - migration(f.source, f.schema, f.history, "1065.0.3").validate(); + @Test + void + genuineV1065Point0Point2ToPoint0Point3UpgradeRetainsPopulatedCatalogAndAddsInitialDispatchGuard() { + try (Fixture f = fixture("1065.0.2")) { + assertCapacityCatalogGuardUpgrade( + f, + "1065.0.3", + 11, + "V1065.0.3__require_initial_capacity_execution_dispatch.sql", + "require_gs_initial_capacity_execution_dispatch()", + "game_session_original_new_capacity_execution.gs_capacity_execution_initial_dispatch", + List.of( + "NEW.status IN ('AUTHORIZED','COMMITTED','CLOSED')", + "NEW.terminal_readback IS NOT NULL", + "Original NEW capacity execution cannot start with an authorization or terminal proof")); + } + } + + private static void assertCapacityCatalogGuardUpgrade( + Fixture f, + String target, + long priorEpoch, + String script, + String guardRoutine, + String addedTrigger, + List guardFragments) { + f.populatePredecessor(); + assertThat(f.count("game_instances")).isGreaterThan(0L); + assertThat(f.count("gameplay_command")).isGreaterThan(0L); + assertThat(f.count("saga_instance")).isGreaterThan(0L); + var original = f.owner().capture(request()); + assertThat(original.catalog().catalogEpoch()).isEqualTo(priorEpoch); + Map before = f.rows(f.tables()); + before.remove(f.history); + before.remove(EPOCHS); + var classifications = f.classificationRows(); + var epochs = + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e ORDER BY catalog_epoch") + .getValues(0, String.class); + var snapshots = + f.dsl + .fetch( + "SELECT to_jsonb(s)::text||':'||xmin::text FROM " + + SNAPSHOTS + + " s ORDER BY read_request_id") + .getValues(0, String.class); + var history = f.historyRows(false); + var sequences = f.sequencePositions(); + var guards = f.guards(); + var constraints = f.constraints(); + var indexes = f.indexes(); + var routines = f.routines(); + var routineIdentities = List.copyOf(routines.keySet()); + routines.remove("gs_runtime_family_catalog_installed()"); + routines.remove("gs_runtime_family_catalog_bytes(p_epoch bigint)"); + routines.remove(guardRoutine); + byte[] evidence = f.evidence(original.request()); + + migration(f.source, f.schema, f.history, target).migrate(); + + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat(f.classificationRows()).isEqualTo(classifications); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e WHERE catalog_epoch<=? ORDER BY catalog_epoch", + priorEpoch) + .getValues(0, String.class)) + .isEqualTo(epochs); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(s)::text||':'||xmin::text FROM " + + SNAPSHOTS + + " s ORDER BY read_request_id") + .getValues(0, String.class)) + .isEqualTo(snapshots); + assertThat(f.historyRows(false)).hasSize(history.size() + 1); + assertThat(f.historyRows(false).subList(0, history.size())).isEqualTo(history); + var installed = + f.dsl.fetchSingle( + "SELECT type,script,success FROM " + f.history + " WHERE version=?", target); + assertThat(installed.get("type", String.class)).isEqualTo("SQL"); + assertThat(installed.get("script", String.class)).isEqualTo(script); + assertThat(installed.get("success", Boolean.class)).isTrue(); + assertThat(f.sequencePositions()).isEqualTo(sequences); + var installedGuards = f.guards(); + assertThat(installedGuards).containsAllEntriesOf(guards); + if (addedTrigger == null) { + assertThat(installedGuards).isEqualTo(guards); + } else { + assertThat(installedGuards.keySet()).hasSize(guards.size() + 1).contains(addedTrigger); } + assertThat(f.constraints()).isEqualTo(constraints); + assertThat(f.indexes()).isEqualTo(indexes); + var installedRoutines = f.routines(); + assertThat(installedRoutines).containsAllEntriesOf(routines); + assertThat(installedRoutines.keySet()) + .hasSize(routineIdentities.size() + (routineIdentities.contains(guardRoutine) ? 0 : 1)) + .containsAll(routineIdentities) + .contains(guardRoutine); + assertThat(f.count(EPOCHS)).isEqualTo(priorEpoch + 1); + assertThat(f.evidence(original.request())).isEqualTo(evidence); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + assertThatThrownBy(() -> f.owner().capture(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + + String installedGuard = f.routines().get(guardRoutine); + assertThat(installedGuard).isNotNull(); + guardFragments.forEach(fragment -> assertThat(installedGuard).contains(fragment)); + if (addedTrigger != null) { + assertThat(f.guards()).containsKey(addedTrigger); + assertThat(f.guards().get(addedTrigger)) + .contains("BEFORE INSERT") + .contains("EXECUTE FUNCTION") + .contains(guardRoutine.substring(0, guardRoutine.indexOf('('))); + } + var current = f.owner().capture(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(priorEpoch + 1); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes=gs_runtime_family_catalog_bytes(?) FROM " + + EPOCHS + + " WHERE catalog_epoch=?", + priorEpoch + 1, + priorEpoch + 1) + .get(0, Boolean.class)) + .isTrue(); + String installedRoutine = f.routines().get("gs_runtime_family_catalog_installed()"); + String bytesRoutine = f.routines().get("gs_runtime_family_catalog_bytes(p_epoch bigint)"); + assertThat(installedRoutine).contains("version='" + target + "'").contains(script); + assertThat(bytesRoutine) + .contains("version IS DISTINCT FROM '" + target + "'") + .contains("catalog-installation:" + target) + .contains(script); + migration(f.source, f.schema, f.history, target).validate(); } private static Request request() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index cca8da7206..74c0bce78e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -132,14 +132,19 @@ void wrongAccountPeerIsRejectedBeforeRequestBodyRelease() throws Exception { } @Test - void changedResponseFenceCannotSubstituteForOriginalCommitment() throws Exception { + void changedResponseFenceLeavesTheOriginalCommitmentIndeterminate() throws Exception { AtomicInteger calls = new AtomicInteger(); Server server = server("account", calls, true); try (var client = client(server)) { client.init(); assertThatThrownBy( () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNKNOWN)); + assertThat(calls).hasValue(1); } finally { stop(server); } From b76e8c72fd9d382b740c32bd6aac08a0548f8239 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:43:06 +1300 Subject: [PATCH 49/52] Adopt credential-free player evidence for capacity commitment --- .../account-service/api-contracts.md | 6 +- .../account-service/runtime-and-data.md | 8 +- .../player_admission_entitlement_read.proto | 12 +- ...ccountPlayerAdmissionEntitlementOwner.java | 2 +- .../service/AccountTenantCapacityOwner.java | 5 +- ...alAdmissionCompositionIntegrationTest.java | 21 +++- ...titlementOwnerPostgresIntegrationTest.java | 12 +- ...titlementOwnerPostgresIntegrationTest.java | 7 +- ...ntPlayerAdmissionEntitlementOwnerTest.java | 8 +- ...erAdmissionEntitlementGrpcServiceTest.java | 6 +- ...imePlayerAdmissionEntitlementEvidence.java | 31 +++-- ...layerAdmissionEntitlementEvidenceTest.java | 70 ++++++++++-- .../CapacityAdmissionTestFixture.java | 106 +++++++++++++++--- .../capacity-admission-v1-vectors.json | 6 +- .../test_capacity_admission_vectors.py | 22 ++++ ...mePlayerAdmissionEntitlementGrpcCodec.java | 23 +++- ...ayerAdmissionEntitlementGrpcCodecTest.java | 94 ++++++++++++++-- ...yerAdmissionEntitlementClientMtlsTest.java | 86 ++++++++++++-- ...ayOriginalNewAuthenticatedSessionTest.java | 15 +++ 19 files changed, 462 insertions(+), 78 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 5fef7aa9d5..fec82eee33 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -257,7 +257,7 @@ The shared [capacity-admission/v1 schema](../../../../services/common-platform-c - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Local unregistered preparation:** `AccountCanonicalRuntimeMembershipSnapshotRepository` and its explicit transaction service assemble the existing shared content carrier from canonical Account and fresh-tenant provenance, current owner generations/fence, role and membership-pair records, and exact committed source events/checkpoints in one owner transaction. Current tenant cutoff fields bind exactly to the verified current tenant source; unequal historical tenant generations fail closed without an Account-owned reconciliation result. This kernel neither authenticates a caller nor grants gameplay or entitlement authority, and the runtime RPC is not wired to it. **Target gap:** the authenticated runtime producer and consumers must carry and enforce the complete fresh snapshot at their admission boundaries. - `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, and UUID provenance. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. - `ResolvePreseededActorStagingEligibility` – default-disabled, same-namespace Entity Management mTLS-only owner read limited to public-production actor staging; it returns staging evidence and creates no actor or gameplay admission. See [Preseeded actor-staging eligibility owner read](#preseeded-actor-staging-eligibility-owner-read). -- `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. +- `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `connectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `connectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. - `GetTenantEntitlementsTenant` – caller-bound tenant-admin entitlement view for billing-safe control-plane UX. @@ -491,9 +491,9 @@ The canonical membership, entitlement response shape, freshness, and sequence co ### Private player-admission entitlement read -`AccountPlayerAdmissionEntitlementReadService/ReadPlayerAdmissionEntitlement` is a distinct private `PLAYER_ADMISSION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/player_admission_entitlement_read.proto). Only the exact same-namespace Game Session workload may call it over mTLS; method authorization precedes request decoding, and ambient bearer or caller-supplied workload context cannot replace transport identity. The request carries schema version 1, the complete retained canonical target selector, Account-issued connect scope and explicit initial `game-session-account-delegation` credential. Repeated transport members each require exactly one value, and unknown fields fail closed. The credential is disclosed only to the verified Account peer on this method and must never be logged or persisted as request evidence. +`AccountPlayerAdmissionEntitlementReadService/ReadPlayerAdmissionEntitlement` is a distinct private `PLAYER_ADMISSION` evidence read defined by the [purpose-specific protobuf](../../../../protos/account/v1/player_admission_entitlement_read.proto). Only the exact same-namespace Game Session workload may call it over mTLS; method authorization precedes request decoding, and ambient bearer or caller-supplied workload context cannot replace transport identity. The request carries schema version 1, the complete retained canonical target selector, Account-issued connect scope and explicit initial `game-session-account-delegation` credential. Repeated transport members each require exactly one value, and unknown fields fail closed. The signed scope bearer and initial LOGIN credential are request-only on this method. Keep both out of logs and retained evidence. -Account verifies the credential subject and current committed issuance, retained scope, current membership including explicit absence, and Account-selected paid-or-DEMO source. Callers cannot select a source family or convert missing paid authority into DEMO. The response echoes only the closed selectors and carries exact canonical `PLAYER_ADMISSION` evidence, never the credential. The [closed codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns wire bounds, the call deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java) owns the canonical content. `scopeDigest` preserves the retained V2 `sha256:`-prefixed digest, distinct from raw-hex token/registry hashes. Unavailable, changed or expired authority produces no positive or empty-success evidence. Account validates `evaluatedAt` against its own source and scope ordering. The receiving Game Session clock independently requires `now < validUntil`; it does not treat Account's evaluation timestamp as a cross-host not-before bound. No numerical skew allowance or expiry extension is applied. +Account verifies the credential subject and current committed issuance, retained scope, current membership including explicit absence, and Account-selected paid-or-DEMO source. Callers cannot select a source family or convert missing paid authority into DEMO. The response uses closed version-2 selectors and carries exact canonical `PLAYER_ADMISSION` evidence with `bundleVersion=2`. The evidence binds the exact target and `verifiedConnectScopeTokenHash`, the `sha256:`-prefixed lowercase SHA-256 of the exact UTF-8 scope bearer. Game Session compares the response target and independently computes that hash from its original request. The capacity commitment and replay carry the complete hash-bound evidence. The [closed codec](../../../../services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java) owns wire bounds, the call deadline and exact response comparisons; the [evidence codec](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java) owns the canonical content. `scopeDigest` independently binds the complete retained V2 scope tuple, and the initial LOGIN issuance token and registry hashes use their separate raw-hex grammar. Unavailable, changed or expired authority produces no positive or empty-success evidence. Account validates `evaluatedAt` against its own source and scope ordering. The receiving Game Session clock independently requires `now < validUntil`; it does not treat Account's evaluation timestamp as a cross-host not-before bound. No numerical skew allowance or expiry extension is applied. This read supports only public-production `SHARED`/`PRESEEDED_ONLY` targets. Broader WORLDS discovery does not widen that restriction. It supplies point-in-time evidence, not membership repair, actor selection, capacity commitment, a World hold through Account commit or later admission, or gameplay admission. The receiver and Game Session client remain manually composed and unregistered; genuine scope/LOGIN custody, runtime integration and proof limits belong to the [player-admission source tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 665cfb3b2c..17b938d223 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -245,9 +245,9 @@ Runtime caller contract: - `GetTenantMembershipForRuntime` requires `authorityAvailability=AVAILABLE` before its snapshot can authorize admission; `UNAVAILABLE` is an authority failure, not missing or `INACTIVE` membership and cannot produce `JOIN_REQUIRED`. The generated proto and Account producer emit `membershipLifecycleState` and the opaque generation, and current text `PLAY` validates those fields alongside membership existence, admission, and version evidence; its entitlement-first ordering, private-grant validation, and outcomes are summarized by the canonical [PLAY outcome matrix](../../system-architecture-authentication.md#play-current-and-target-failure-boundaries). `authorityAvailability`, roles, the complete tuple, and checkpoints remain absent; the complete fresh atomic target snapshot and fail-closed consumer proof remain implementation gaps. - `GetTenantEntitlementsForRuntime(tenantId, requestId)` is the authoritative internal entitlement surface for gameplay/runtime flows. Runtime callers may cache its positive result only under the strict-new-commitment and bounded-continuity rules in [ADR 0028](../../decisions/adr-0028-differentiated-entitlement-freshness.md); the cache never becomes a second writer. - Minimum request fields: `tenantId`, `requestId`. - - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `verifiedConnectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. - - Minimum response fields: `tenantId`, nullable `subscriptionStatus`, nullable `provisioningStatus`, `gameplayAvailable`, `allowPublicJoin`, `allowNewGameplayBindings`, `allowNewInstanceStarts`, `quotas { ... }`, `evaluatedAt`, `entitlementVersion`, `tenantBillingSequence`, opaque `tenantAuthorityGeneration`, positive `bundleVersion`, opaque `snapshotIdentity`, opaque `evaluationIdentity`, the complete applicable `authorityTuple`, the separate exact `tenantBillingCutoff[tenantId]` entry when billing evidence applies, and the complete applicable `outboxCheckpoints[]` set. For player admission, the response additionally requires `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. While `provisioningStatus` is `pending` or `provisioning`, `subscriptionStatus` is null and every gameplay/admission/instance-start flag is false; after provisioning resolves, `provisioningStatus` is null and `subscriptionStatus` carries the canonical subscription state. - - The entitlement values, caller/target binding when applicable, bundle metadata and identities, complete tuple, applicable billing cutoff, and checkpoint set are one Account-authenticated `account-auth-evidence-bundle/v1` result from the same authoritative transaction or Account-owned fence. `snapshotIdentity` names the committed authority snapshot and `evaluationIdentity` names this evaluation of it. The applicable billing cutoff carries the exact `tenantBillingSequence`, `outboxStreamKey`, and `outboxSequence`; every positive matching checkpoint also carries `sourceEventId` and `sourceEventDigest` and must cover that same stream and sequence. Callers must reject missing, extra, contradictory, or separately sourced evidence and must not reconstruct either identity or treat the flat `tenantBillingSequence` as a substitute for the cutoff or checkpoint. A tenant-only runtime bundle cannot authorize player admission; the caller-bound `verifiedConnectScopeId` and target must match the server-verified scope exactly. + - For target player-admission calls only, the minimum request additionally carries `callerAccountId`, the signed `connectScopeId`, and the exact resolved target bundle. Game Session supplies these fields as trusted typed execution/request context; the private `game-session-account-delegation` JWT carries its declared Account authority but does not carry `connectScopeId` or the complete runtime target bundle. Account requires `callerAccountId` to equal the authenticated delegation JWT's `accountId`/`sub` and the exact bound Game Session subject, then verifies the scope and target fields against the signed connect scope and current exact target before returning the already-declared caller/target-bound evidence. World Management's tenant/operation-bound lifecycle calls retain their separate operation context and do not fabricate player-binding fields. + - Minimum response fields: `tenantId`, nullable `subscriptionStatus`, nullable `provisioningStatus`, `gameplayAvailable`, `allowPublicJoin`, `allowNewGameplayBindings`, `allowNewInstanceStarts`, `quotas { ... }`, `evaluatedAt`, `entitlementVersion`, `tenantBillingSequence`, opaque `tenantAuthorityGeneration`, positive `bundleVersion`, opaque `snapshotIdentity`, opaque `evaluationIdentity`, the complete applicable `authorityTuple`, the separate exact `tenantBillingCutoff[tenantId]` entry when billing evidence applies, and the complete applicable `outboxCheckpoints[]` set. For player admission, the response additionally requires `callerAccountId`, `verifiedConnectScopeTokenHash`, the independently verified `scopeDigest`, and the exact resolved target bundle. While `provisioningStatus` is `pending` or `provisioning`, `subscriptionStatus` is null and every gameplay/admission/instance-start flag is false; after provisioning resolves, `provisioningStatus` is null and `subscriptionStatus` carries the canonical subscription state. + - The entitlement values, caller/target binding when applicable, bundle metadata and identities, complete tuple, applicable billing cutoff, and checkpoint set are one Account-authenticated `account-auth-evidence-bundle/v1` result from the same authoritative transaction or Account-owned fence. `snapshotIdentity` names the committed authority snapshot and `evaluationIdentity` names this evaluation of it. The applicable billing cutoff carries the exact `tenantBillingSequence`, `outboxStreamKey`, and `outboxSequence`; every positive matching checkpoint also carries `sourceEventId` and `sourceEventDigest` and must cover that same stream and sequence. Callers must reject missing, extra, contradictory, or separately sourced evidence and must not reconstruct either identity or treat the flat `tenantBillingSequence` as a substitute for the cutoff or checkpoint. A tenant-only runtime bundle cannot authorize player admission; the token hash, scope digest, and exact target bind the same server-verified scope under the [private player-admission read contract](./api-contracts.md#private-player-admission-entitlement-read). - `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is the runtime-served gameplay-admissible-instance lookup for the canonical realm-catalog/admission-pointer contract owned by Multi-Tenancy. The current implementation is `game_session.v1.GameSessionService/GetAdmissionPointer`; Game Session persists and serves the pointer, while Account calls it through `GameSessionClient` and receives either a `GameplayAdmissionPointer` or an application error. - Current proto/producer fields are `tenantId`, `worldSlug`, `realmSlug`, `gameInstanceId`, `pointerVersion`, `requiresCharacterSelection`, `visible`, `stateScope`, `characterCreationPolicy`, and `publicProductionRealm`, plus display names. The current persisted pointer requires a positive runtime target and does not expose `admissionState`, `updatedAt`, or an explicit `CLOSED` response. - Target minimum response fields: `tenantId`, `worldSlug`, `realmSlug`, `admissionState`, `catalogRevision`, `pointerVersion`, `updatedAt`; `admissibleGameInstanceId` is present if and only if `admissionState` is `OPEN`. These target-only fields must not be reported as current proto/runtime behavior. @@ -322,6 +322,8 @@ Entitlement producer contract: The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. `V1040` prepares immutable capacity-evaluation, attempt-history, and recovery-evidence records plus guarded reservations, but no capacity-family retention entry, horizon, or owner-safe cleanup/archive contract is defined under [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). This remains an open Account activation limitation; existing guards and holds remain in force. +Retained player-admission version-1 evidence remains immutable and held for owner-governed retention. Player-admission version 2 is required for new capacity requests and their replay. Before activation or reuse of predecessor-populated storage, establish the retained Account and Game Session SQL and Redis inventory and resolve its outstanding confirmation, replay, recovery and restore obligations under the [objective compatibility gates](../../decisions/adr-0081-objective-compatibility-gates-for-database-evolution.md). + ### Playtest Grant Persistence and Authority Consequences The complete Account-owned grant mutation and replay contract is defined in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract). This runtime document owns only its data and projection consequences: persist one grant scope `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` with active/revoked state, `grantRevision`, explicit `grantExpiresAt`, fork-expiry reference, grantor/audit metadata, request outcome, and a retained revocation tombstone. The grant row must never be hard-deleted while delayed request replay could still arrive. Each mutation also persists a separate durable grant-mutation operation/replay record—not a second grant row—with `requestId`, ADR 0047's exact seven-field `mutationDigest/v1`, normalized operation, complete lifecycle-bound target, requested expiry, conditional `expectedGrantRevision` mapped to typed `expectedVersion` (absent only for the initial `CREATE` precondition), pending or terminal outcome, and the configured retention/deduplication horizon. Exact request/digest retries replay that operation result and changed inputs conflict before grant mutation; the operation record is distinct from both the current grant row and its retained revocation tombstone. diff --git a/protos/account/v1/player_admission_entitlement_read.proto b/protos/account/v1/player_admission_entitlement_read.proto index ee5d174bb6..67e258a359 100644 --- a/protos/account/v1/player_admission_entitlement_read.proto +++ b/protos/account/v1/player_admission_entitlement_read.proto @@ -28,8 +28,16 @@ message ReadPlayerAdmissionEntitlementRequest { repeated string initial_login_jwt = 2; } -// Echo only selectors, never the presented credential. Evidence is exact bounded RFC 8785 UTF-8. +// Response comparison binding, independent of the credential-bearing version 1 request. +message PlayerAdmissionEntitlementReadResponseBinding { + repeated uint32 schema_version = 1; + repeated game_session.v1.ResolvePublishedRealmAdmissionTargetRequest target = 2; +} + +// Evidence is exact bounded RFC 8785 UTF-8 and carries the verified scope token hash. message ReadPlayerAdmissionEntitlementResponse { - repeated PlayerAdmissionEntitlementReadSelectors request = 1; + reserved 1; + reserved "request"; repeated bytes canonical_evidence = 2; + repeated PlayerAdmissionEntitlementReadResponseBinding binding = 3; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index 48a32ed74f..c8b384f56e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -636,7 +636,7 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( request.requestId(), request.authenticatedCallerWorkload(), - request.connectScopeId(), + scope.scopeTokenHash(), player.snapshot(), binding, facts, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index c42a5e6434..87cb05708a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -16,7 +16,6 @@ import java.util.Objects; import java.util.UUID; import java.util.function.Supplier; -import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; @@ -220,10 +219,10 @@ private void current(Request request) { || !issuance.commitProofSha256().equals(source.get("callerCommitProofSha256")) || now.getEpochSecond() < issuance.identity().notBeforeEpochSecond() || now.getEpochSecond() >= issuance.identity().expiresAtEpochSecond()) throw unavailable(); - String connect = (String) fields.get("verifiedConnectScopeId"); var scope = qualifiedSource( - () -> scopes.findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(connect))) + () -> + scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash())) .orElseThrow(AccountTenantCapacityRepository::unavailable); if (!scope.accountUuid().equals(player.accountId()) || !scope.tenantUuid().equals(player.tenantId()) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 69d982e6ed..1269822a96 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -630,6 +630,11 @@ private static void assertCapacityRefusalWithoutMutation( @Test void retainedOriginalReplaysBeforeChangedNonCreatingEvidenceCanBecomeADenial() throws Exception { try (Session session = session()) { + String unretainedScopeHash = + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash("unretained-test-scope"); + var wrongScope = session.retainControlledEvaluation(true, null, null, unretainedScopeHash); + assertCapacityRefusalWithoutMutation( + session, wrongScope, Status.Code.UNAVAILABLE, "ENTITLEMENT_UNAVAILABLE"); var first = session.capacityClient.commit(session.capacityRequest, CLOCK.millis() + 5_000L); var changed = session.retainControlledEvaluation(false, null); byte[] candidate = session.gs.physicalSession(); @@ -640,6 +645,8 @@ void retainedOriginalReplaysBeforeChangedNonCreatingEvidenceCanBecomeADenial() t StatusRuntimeException.class, () -> session.capacityClient.commit(changed, CLOCK.millis() + 5_000L)); assertCapacityFailure(failure, Status.Code.ALREADY_EXISTS, "IDEMPOTENCY_CONFLICT"); + assertCapacityRefusalWithoutMutation( + session, wrongScope, Status.Code.ALREADY_EXISTS, "IDEMPOTENCY_CONFLICT"); assertThat(session.capacityClient.commit(session.capacityRequest, CLOCK.millis() + 5_000L)) .isEqualTo(first); assertThat(session.capacityImage() + session.durableImage()).isEqualTo(before); @@ -971,17 +978,25 @@ private Genesis genesis() { .readByLease(UUID.fromString((String) lease.carrier().get("leaseId")))); } - /** Controlled entitlement facts, real current caller/scope and actual immutable retention. */ + /** Controlled evaluation inputs with actual immutable retention. */ private TenantCapacityAdmission.Request retainControlledEvaluation( boolean creationAllowed, @org.jspecify.annotations.Nullable String quota) { return retainControlledEvaluation(creationAllowed, quota, null); } - @SuppressWarnings("unchecked") private TenantCapacityAdmission.Request retainControlledEvaluation( boolean creationAllowed, @org.jspecify.annotations.Nullable String quota, @org.jspecify.annotations.Nullable Long catalogRevision) { + return retainControlledEvaluation(creationAllowed, quota, catalogRevision, null); + } + + @SuppressWarnings("unchecked") + private TenantCapacityAdmission.Request retainControlledEvaluation( + boolean creationAllowed, + @org.jspecify.annotations.Nullable String quota, + @org.jspecify.annotations.Nullable Long catalogRevision, + @org.jspecify.annotations.Nullable String scopeTokenHash) { var original = capacityRequest; var parsed = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( @@ -1015,7 +1030,7 @@ private TenantCapacityAdmission.Request retainControlledEvaluation( RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( original.identity().requestId(), original.evidence().callerWorkload(), - (String) fields.get("verifiedConnectScopeId"), + scopeTokenHash == null ? parsed.verifiedConnectScopeTokenHash() : scopeTokenHash, parsed.membershipSource(), target, facts, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 0de1522123..32b82b90e3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -28,6 +28,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.entity.Account; @@ -60,6 +61,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -335,7 +337,15 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { "SELECT canonical_evidence, snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", value.fields().get("evaluationIdentity")); assertThat(retained).isNotNull(); - assertThat(retained.get("canonical_evidence", byte[].class)).isEqualTo(value.canonicalBytes()); + byte[] retainedEvidence = retained.get("canonical_evidence", byte[].class); + assertThat( + new String(retainedEvidence, StandardCharsets.UTF_8).contains(f.scope.connectScopeId())) + .isFalse(); + assertThat(retainedEvidence).containsExactly(value.canonicalBytes()); + var decoded = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(retainedEvidence); + assertThat(decoded.verifiedConnectScopeTokenHash()) + .isEqualTo(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + assertThat(decoded.fields()).doesNotContainKey("verifiedConnectScopeId"); assertThat(retained.get("snapshot_identity", String.class)) .isEqualTo(value.fields().get("snapshotIdentity")); assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java index 9c5f6a9b38..b390cc7076 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java @@ -125,7 +125,12 @@ void paidUsesActualReceiptSdkAndAuthorityCheckpointWithFreshEvaluationOfSameSnap assertThat(java.time.Instant.parse((String) second.fields().get("evaluatedAt"))) .isAfter(java.time.Instant.parse((String) first.fields().get("evaluatedAt"))); assertThat(first.fields()) - .doesNotContainKeys("callerAccountId", "issuer", "accountId", "verifiedConnectScopeId"); + .doesNotContainKeys( + "callerAccountId", + "issuer", + "accountId", + "verifiedConnectScopeId", + "verifiedConnectScopeTokenHash"); assertThat(first.fields().get("quotas")) .isEqualTo( Map.of( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index 42b21054e8..28f9af32c8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -135,6 +135,10 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa assertThat(value.fields().get("requestId")).isEqualTo(f.request.requestId().toString()); assertThat(value.fields().get("callerWorkload")).isEqualTo(PEER); assertThat(f.retainedCapacity).hasSize(1); + assertThat( + new String(value.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) + .contains(f.scope.connectScopeId())) + .isFalse(); assertThat( f.retainedCapacity .get(value.fields().get("evaluationIdentity")) @@ -151,7 +155,9 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa assertThat(value.membershipSource().authorityTuple().membershipAuthorityGeneration()) .containsExactlyEntriesOf(Map.of(TENANT.toString(), "1")); assertThat(value.fields()) - .containsEntry("verifiedConnectScopeId", f.scope.connectScopeId()) + .containsEntry( + "verifiedConnectScopeTokenHash", AccountJoinDigest.tokenHash(f.scope.connectScopeId())) + .doesNotContainKey("verifiedConnectScopeId") .containsEntry("sourceKind", "NON_PAID_DEMO"); var binding = (Map) value.fields().get("target"); assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java index a6b0fc81aa..3a75f2bc03 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcServiceTest.java @@ -285,6 +285,8 @@ private static RuntimePlayerAdmissionEntitlementEvidence evidence() { binding.put("catalogRevision", "7"); binding.put("pointerVersion", "3"); var evidence = mock(RuntimePlayerAdmissionEntitlementEvidence.class); + String scopeHash = RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash(SCOPE); + when(evidence.verifiedConnectScopeTokenHash()).thenReturn(scopeHash); when(evidence.fields()) .thenReturn( Map.of( @@ -296,8 +298,8 @@ private static RuntimePlayerAdmissionEntitlementEvidence evidence() { target.readRequestId().toString(), "callerWorkload", PEER, - "verifiedConnectScopeId", - SCOPE, + "verifiedConnectScopeTokenHash", + scopeHash, "target", binding)); when(evidence.canonicalBytes()) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java index a522ead2f2..dd88e9fdcd 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java @@ -38,6 +38,7 @@ public final class RuntimePlayerAdmissionEntitlementEvidence { public static final String SCHEMA = RuntimeTenantOperationEntitlementEvidence.SCHEMA; public static final String VARIANT = "PLAYER_ADMISSION"; + private static final String BUNDLE_VERSION = "2"; public static final int MAX_CANONICAL_BYTES = 256 * 1024; public static final int MAX_CONNECT_SCOPE_CHARS = 16384; private static final JsonMapper JSON = @@ -115,7 +116,7 @@ private RuntimePlayerAdmissionEntitlementEvidence(Snapshot membership, byte[] ca public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( UUID requestId, String callerWorkload, - String verifiedConnectScopeId, + String verifiedConnectScopeTokenHash, Snapshot membership, Map target, Map facts, @@ -145,10 +146,9 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( value.uri().equals(callerWorkload) && "game-session-service".equals(value.service())) .orElseThrow(() -> invalid("Exact Game Session caller required")); - if (verifiedConnectScopeId == null - || verifiedConnectScopeId.isBlank() - || verifiedConnectScopeId.length() > MAX_CONNECT_SCOPE_CHARS) - throw invalid("Verified connect scope required"); + if (verifiedConnectScopeTokenHash == null + || !verifiedConnectScopeTokenHash.matches("sha256:[0-9a-f]{64}")) + throw invalid("Verified connect scope token hash required"); exact(target, TARGET_FIELDS); exact(facts, FACT_FIELDS); exact(source, SOURCE_FIELDS); @@ -209,13 +209,13 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( Map fields = new LinkedHashMap<>(); fields.put("schema", SCHEMA); fields.put("variant", VARIANT); - fields.put("bundleVersion", "1"); + fields.put("bundleVersion", BUNDLE_VERSION); fields.put("authorityAvailability", "AVAILABLE"); fields.put("issuer", membership.issuerId()); fields.put("tenantId", membership.tenantId()); fields.put("callerAccountId", membership.accountId()); fields.put("callerWorkload", callerWorkload); - fields.put("verifiedConnectScopeId", verifiedConnectScopeId); + fields.put("verifiedConnectScopeTokenHash", verifiedConnectScopeTokenHash); fields.put("target", target); fields.putAll(facts); fields.put("membershipExists", membership.membershipExists()); @@ -290,6 +290,10 @@ public static RuntimePlayerAdmissionEntitlementEvidence parseCanonical(byte[] by .decode(ByteBuffer.wrap(bytes)) .toString(); Map fields = JSON.readValue(json, new TypeReference<>() {}); + if (!BUNDLE_VERSION.equals(fields.get("bundleVersion")) + || !VARIANT.equals(fields.get("variant")) + || fields.containsKey("verifiedConnectScopeId")) + throw invalid("Unsupported player evidence format"); Map authority = object(fields.get("authorityTuple")); Set requiredTuple = Set.of( @@ -402,7 +406,7 @@ public static RuntimePlayerAdmissionEntitlementEvidence parseCanonical(byte[] by fromOwnerEvaluation( UUID.fromString(text(fields.get("requestId"))), text(fields.get("callerWorkload")), - text(fields.get("verifiedConnectScopeId")), + text(fields.get("verifiedConnectScopeTokenHash")), membership, object(fields.get("target")), facts, @@ -551,6 +555,17 @@ public static String digestBytes(byte[] bytes) { } } + /** Correlates the exact authenticated request token with the non-secret evidence binding. */ + public static String connectScopeTokenHash(String token) { + if (token == null || token.isBlank() || token.length() > MAX_CONNECT_SCOPE_CHARS) + throw invalid("Exact connect scope token required"); + return digestBytes(token.getBytes(StandardCharsets.UTF_8)); + } + + public String verifiedConnectScopeTokenHash() { + return text(fields().get("verifiedConnectScopeTokenHash")); + } + public Instant evaluatedAt() { return instant(fields().get("evaluatedAt")); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java index 88367c3487..2ee2480c48 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java @@ -15,9 +15,11 @@ import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; /** Controlled content fixtures, not source authentication, transport or owner execution. */ class RuntimePlayerAdmissionEntitlementEvidenceTest { @@ -26,6 +28,9 @@ class RuntimePlayerAdmissionEntitlementEvidenceTest { private static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; private static final String HASH = "a".repeat(64); + private static final String SCOPE = "controlled-scope"; + private static final String SCOPE_HASH = + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash(SCOPE); private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); @Test @@ -35,7 +40,9 @@ void canonicalVariantRetainsExplicitAbsenceAndCompleteApplicableAuthority() { .containsEntry("variant", "PLAYER_ADMISSION") .containsEntry("authorityAvailability", "AVAILABLE") .containsEntry("callerAccountId", ACCOUNT.toString()) - .containsEntry("verifiedConnectScopeId", "controlled-scope") + .containsEntry("bundleVersion", "2") + .containsEntry("verifiedConnectScopeTokenHash", SCOPE_HASH) + .doesNotContainKey("verifiedConnectScopeId") .containsEntry("membershipExists", false) .containsEntry("membershipLifecycleState", "MISSING"); assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); @@ -45,7 +52,9 @@ void canonicalVariantRetainsExplicitAbsenceAndCompleteApplicableAuthority() { copy[0] = 0; value.fields().put("callerAccountId", TENANT.toString()); assertThat(value.fields()).containsEntry("callerAccountId", ACCOUNT.toString()); - assertThat(value.toString()).doesNotContain("controlled-scope"); + assertThat(value.toString()).doesNotContain(SCOPE); + assertThat(new String(value.canonicalBytes(), StandardCharsets.UTF_8)).doesNotContain(SCOPE); + assertThat(value.verifiedConnectScopeTokenHash()).isEqualTo(SCOPE_HASH); assertThatThrownBy( () -> RuntimeTenantOperationEntitlementEvidence.parseCanonical(value.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class); @@ -88,14 +97,7 @@ void ownerEmissionRejectsOversizedRoleInventoryBeforeReturningEvidence() { assertThatThrownBy( () -> RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - REQUEST, - PEER, - "controlled-scope", - oversized, - target(), - facts(), - sources(), - NOW)) + REQUEST, PEER, SCOPE_HASH, oversized, target(), facts(), sources(), NOW)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Bounded list required"); } @@ -170,6 +172,52 @@ void strictDecoderRoundTripsAndRejectsNoncanonicalUnknownOrConflictingContent() } } + @Test + void legacyBearerBundleAndNewBundleWithRawFieldFailClosed() throws Exception { + var value = capture(target(), facts(), sources(), NOW); + var legacy = value.fields(); + legacy.put("bundleVersion", "1"); + legacy.remove("verifiedConnectScopeTokenHash"); + legacy.put("verifiedConnectScopeId", SCOPE); + Object evaluatedAt = legacy.remove("evaluatedAt"); + Object requestId = legacy.remove("requestId"); + legacy.remove("snapshotIdentity"); + legacy.remove("evaluationIdentity"); + String snapshot = RuntimePlayerAdmissionEntitlementEvidence.digest(legacy); + legacy.put("snapshotIdentity", snapshot); + legacy.put("evaluatedAt", evaluatedAt); + legacy.put("requestId", requestId); + legacy.put( + "evaluationIdentity", + RuntimePlayerAdmissionEntitlementEvidence.digest( + Map.of( + "snapshotIdentity", snapshot, + "requestId", requestId, + "callerWorkload", PEER, + "evaluatedAt", evaluatedAt))); + var rawField = value.fields(); + rawField.put("verifiedConnectScopeId", SCOPE); + var mapper = JsonMapper.builder().build(); + for (var fields : List.of(legacy, rawField)) { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(mapper.writeValueAsString(fields)); + byte[] retained = bytes.clone(); + assertThatThrownBy(() -> RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(bytes)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(SCOPE); + assertThat(bytes).containsExactly(retained); + } + } + + @Test + void rawScopeCannotBeSuppliedAsTheVerifiedTokenHash() { + assertThatThrownBy( + () -> + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, PEER, SCOPE, membership(), target(), facts(), sources(), NOW)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Verified connect scope token hash required"); + } + @Test void validityIsMinimumOfActualScopeCallerAndPaidReceiptBounds() { var source = sources(); @@ -202,7 +250,7 @@ private static RuntimePlayerAdmissionEntitlementEvidence capture( Map source, Instant at) { return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); + REQUEST, PEER, SCOPE_HASH, membership(), target, facts, source, at); } private static Map target() { diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java index f71e3e7ef1..3dbb82c187 100644 --- a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java @@ -92,8 +92,8 @@ public static TenantCapacityAdmission.Request playerRequestFor( player.requestId(), TenantCapacityAdmission.expectedWorkload( namespace, TenantCapacityAdmission.Owner.GAME_SESSION), - "controlled-scope", - membership(player.accountId(), player.tenantId(), player.requestId()), + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash("controlled-scope"), + admittingMembership(player.accountId(), player.tenantId(), player.requestId()), target, facts(), source, @@ -198,7 +198,14 @@ private static RuntimePlayerAdmissionEntitlementEvidence capture( Map source, Instant at) { return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); + REQUEST, + PEER, + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash("controlled-scope"), + membership(), + target, + facts, + source, + at); } private static Map target() { @@ -274,10 +281,15 @@ private static Map sources() { } private static Snapshot membership() { - return membership(ACCOUNT, TENANT, REQUEST); + return membership(ACCOUNT, TENANT, REQUEST, false); } - private static Snapshot membership(UUID account, UUID tenantId, UUID requestId) { + private static Snapshot admittingMembership(UUID account, UUID tenantId, UUID requestId) { + return membership(account, tenantId, requestId, true); + } + + private static Snapshot membership( + UUID account, UUID tenantId, UUID requestId, boolean admitted) { String requestDigest = GameTenantCreationDigest.requestDigest("prod", requestId, "world", "World", null); var source = @@ -330,29 +342,89 @@ private static Snapshot membership(UUID account, UUID tenantId, UUID requestId) Map.of( tenantId.toString(), new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + String membershipStream = prefix + "membership/" + account + "/" + tenantId; + var tenantSource = + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)); + List sourceEvidence; + if (admitted) { + Map eventFields = new LinkedHashMap<>(); + eventFields.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + eventFields.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + eventFields.put("eventId", "membership-event-" + requestId); + eventFields.put("requestId", requestId.toString()); + eventFields.put("outboxStreamKey", membershipStream); + eventFields.put("outboxSequence", "1"); + eventFields.put("sourceScope", "membership/" + account + "/" + tenantId); + eventFields.put("accountId", account.toString()); + eventFields.put("tenantId", tenantId.toString()); + eventFields.put("membershipExists", true); + eventFields.put("membershipLifecycleState", "ACTIVE"); + eventFields.put("membershipVersion", Map.of(tenantId.toString(), "1")); + eventFields.put("membershipAuthorityGeneration", "1"); + eventFields.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenantId.toString(), "2"), + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), "1"), + "privateRealmGrantVersions", + List.of(), + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + "2", + "tenantBillingSequence", + "1", + "outboxStreamKey", + event.outboxStreamKey(), + "outboxSequence", + "1")))); + eventFields.put("issuanceFence", "1"); + eventFields.put("roles", List.of("player")); + eventFields.put("gameplayAdmissionAllowed", true); + eventFields.put("callerBoundAuthorityInvalidated", false); + var membershipEvent = MembershipAuthorityEventV1Codec.seal(eventFields); + sourceEvidence = + List.of( + new SourceEvidence( + membershipStream, + "1", + membershipEvent.eventId(), + membershipEvent.eventDigest(), + membershipEvent.canonicalJson()), + tenantSource); + } else { + sourceEvidence = List.of(tenantSource); + } return new Snapshot( "firemud-account-service", account.toString(), tenantId.toString(), - false, - "MISSING", - false, + admitted, + admitted ? "ACTIVE" : "MISSING", + admitted, Map.of(tenantId.toString(), "1"), "1", - List.of(), + admitted ? List.of("player") : List.of(), tuple, "1", List.of( new Checkpoint(prefix + "account/" + account, "0"), new Checkpoint(prefix + "issuer/firemud-account-service", "0"), - new Checkpoint(prefix + "membership/" + account + "/" + tenantId, "0"), + new Checkpoint(membershipStream, admitted ? "1" : "0"), new Checkpoint(event.outboxStreamKey(), "1")), - List.of( - new SourceEvidence( - event.outboxStreamKey(), - "1", - event.eventId().toString(), - event.eventDigest(), - new String(event.payload(), StandardCharsets.UTF_8)))); + sourceEvidence); } } diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json index c8120d1075..e557b9147e 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json +++ b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json @@ -226,13 +226,13 @@ "0", "0" ], - "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5U291cmNlRXZpZGVuY2UiOlt7ImNhbm9uaWNhbEV2ZW50SnNvbiI6IntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNFwiLFwiZXZlbnRJZFwiOlwiZWRiM2JkMzMtODZlMS0zYmZkLTllYjItZjY3ZmZkYzNjOTZiXCIsXCJldmVudFR5cGVcIjpcIlRFTkFOVF9BVVRIT1JJVFlfQ0hBTkdFRFwiLFwib3V0Ym94U2VxdWVuY2VcIjpcIjFcIixcIm91dGJveFN0cmVhbUtleVwiOlwiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJyZXF1ZXN0RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwicmVxdWVzdElkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInNjaGVtYVZlcnNpb25cIjpcImFjY291bnQtdGVuYW50LWF1dGhvcml0eS1ldmVudC92MVwiLFwic291cmNlRXZpZGVuY2VcIjp7XCJjYW5vbmljYWxUZW5hbnRJZFwiOlwiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJjcmVhdGlvblJlcXVlc3RJZFwiOlwiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzXCIsXCJldmlkZW5jZURpZ2VzdFwiOlwic2hhMjU2OjcxNzQwZWZmNTcxNzI0ZDY3ZmJiMjVjMGY4NzQ1MjYyMzY1NzRmNzI0MjlhODg1OTI2ODljMWFjNDdlODAzY2VcIixcIm9wZXJhdGlvbklkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInByb3ZlbmFuY2VLaW5kXCI6XCJORVdfR0FNRV9ST1dcIixcInJlcXVlc3REaWdlc3RcIjpcInNoYTI1NjpmMDZlNWU1MGJiZGE5OTE3YjNmZGFkOGUyNzczNzA2OTNmNDlhZmMzMzllZWM3Zjc1NDhiMWU1NDEyNTQ2NjkwXCIsXCJzY2hlbWFWZXJzaW9uXCI6MSxcInNvdXJjZUdhbWVSb3dJZFwiOlwiMTdcIixcInNvdXJjZUdhbWVUZW5hbnRLZXlcIjpcIndvcmxkXCIsXCJ0YXJnZXROYW1lc3BhY2VcIjpcInByb2RcIn0sXCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uXCI6XCIyXCIsXCJ0ZW5hbnRBdXRob3JpdHlTb3VyY2VWZXJzaW9uXCI6XCIyXCIsXCJ0ZW5hbnRCaWxsaW5nUmVjZWlwdFwiOntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwiZXZlbnRJZFwiOlwiNWFjMTU4MmItYTQwZC0zNTA1LWFiNDItZjc3NjY1N2I0YjYwXCIsXCJvdXRib3hTdHJlYW1LZXlcIjpcImFjY291bnQ6dGVuYW50LWVudGl0bGVtZW50OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIixcInRlbmFudEJpbGxpbmdTZXF1ZW5jZVwiOlwiMVwifSxcInRlbmFudElkXCI6XCIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIn0iLCJldmVudERpZ2VzdCI6InNoYTI1NjowZTg0Mjk5ODMzZDg1NzU0ZmE1ODNlNDE1MGZhN2Q5MTM3NDZiODNhZWVjMzRhMDU2YzRjY2I1NjZhMTUwYzI0IiwiZXZlbnRJZCI6ImVkYjNiZDMzLTg2ZTEtM2JmZC05ZWIyLWY2N2ZmZGMzYzk2YiIsIm91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9XSwiYXV0aG9yaXR5VHVwbGUiOnsiYWNjb3VudEF1dGhvcml0eUdlbmVyYXRpb24iOiIxIiwiaXNzdWVyQXV0aEdlbmVyYXRpb24iOiIxIiwibWVtYmVyc2hpcEF1dGhvcml0eUdlbmVyYXRpb24iOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjoiMSJ9LCJwcml2YXRlUmVhbG1HcmFudFZlcnNpb25zIjpbXSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiIyIn0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiIyIiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMSJ9fX0sImJ1bmRsZVZlcnNpb24iOiIxIiwiY2FsbGVyQWNjb3VudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIiwiY2FsbGVyV29ya2xvYWQiOiJzcGlmZmU6Ly9maXJlbXVkL25zL3Byb2Qvc2EvZ2FtZS1zZXNzaW9uLXNlcnZpY2UiLCJlbnRpdGxlbWVudFZlcnNpb24iOiIxIiwiZXZhbHVhdGVkQXQiOiIyMDI2LTExLTAyVDAwOjAwOjAwWiIsImV2YWx1YXRpb25JZGVudGl0eSI6InNoYTI1NjoyZDE4MzNlYTE0OTNlNjQzNmM0NTgxMDhlZjk4MWZkODEyODFhNjE3NjA4NTcyYWQ4MGJmM2JkY2RmNDgxZTdlIiwiZ2FtZXBsYXlBZG1pc3Npb25BbGxvd2VkIjpmYWxzZSwiZ2FtZXBsYXlBdmFpbGFibGUiOnRydWUsImlzc3VhbmNlRmVuY2UiOiIxIiwiaXNzdWVyIjoiZmlyZW11ZC1hY2NvdW50LXNlcnZpY2UiLCJtZW1iZXJzaGlwQXV0aG9yaXR5R2VuZXJhdGlvbiI6IjEiLCJtZW1iZXJzaGlwRXhpc3RzIjpmYWxzZSwibWVtYmVyc2hpcExpZmVjeWNsZVN0YXRlIjoiTUlTU0lORyIsIm1lbWJlcnNoaXBWZXJzaW9uIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6IjEifSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6YWNjb3VudC8xMTExMTExMS0xMTExLTQxMTEtODExMS0xMTExMTExMTExMTEifSx7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6aXNzdWVyL2ZpcmVtdWQtYWNjb3VudC1zZXJ2aWNlIn0seyJvdXRib3hTZXF1ZW5jZSI6IjAiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOm1lbWJlcnNoaXAvMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExLzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9LHsib3V0Ym94U2VxdWVuY2UiOiIxIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwic291cmNlRXZlbnREaWdlc3QiOiJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNCIsInNvdXJjZUV2ZW50SWQiOiJlZGIzYmQzMy04NmUxLTNiZmQtOWViMi1mNjdmZmRjM2M5NmIifV0sInByb3Zpc2lvbmluZ1N0YXR1cyI6bnVsbCwicXVvdGFzIjp7Im1heEFjdGl2ZVNlc3Npb25zIjoiMyIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiMiIsIm1heFN0b3JhZ2VCeXRlcyI6IjQwOTYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwicm9sZXMiOltdLCJzY2hlbWEiOiJhY2NvdW50LWF1dGgtZXZpZGVuY2UtYnVuZGxlL3YxIiwic25hcHNob3RJZGVudGl0eSI6InNoYTI1Njo0M2U1ZjVjNjEwZmNmMjBjYjQ0M2ExMzNkZWNlZWIwYzY2OTM5NmYwZWVjYTRmMmY5ODQ5MTFjMTNhNmZiM2YyIiwic291cmNlS2luZCI6Ik5PTl9QQUlEX0RFTU8iLCJzb3VyY2VSZWZlcmVuY2VzIjp7ImFkbWlzc2lvblBvaW50ZXJTbmFwc2hvdERpZ2VzdCI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb21taXRQcm9vZlNoYTI1NiI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb250ZXh0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJjYWxsZXJPcGVyYXRpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclJlZ2lzdHJ5UmVjb3JkU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImNhbGxlclRva2VuRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJjYWxsZXJUb2tlbkp0aSI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclRva2VuU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImVudGl0bGVtZW50U291cmNlRGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJnYW1lU2Vzc2lvbk93bmVyUHJvb2ZEaWdlc3QiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInBhaWRSZWNlaXB0VmFsaWRVbnRpbCI6bnVsbCwicHVibGlzaGVkUG9saWN5U2V0RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzY29wZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRDYXB0dXJlSWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJ3b3JsZExpZmVjeWNsZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRSb3dWZXJzaW9uIjoiMCJ9LCJzdWJzY3JpcHRpb25TdGF0dXMiOm51bGwsInRhcmdldCI6eyJhY3RpdmVXb3JsZEVwb2NoIjoiNSIsImNhbm9uaWNhbFZlcnNpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhdGFsb2dSZXZpc2lvbiI6IjciLCJjaGFyYWN0ZXJDcmVhdGlvblBvbGljeSI6IlBSRVNFRURFRF9PTkxZIiwiY29ubmVjdFNjb3BlRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMjowMFoiLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDFUMjM6NTk6NDBaIiwiZ2FtZUluc3RhbmNlSWQiOiI3Nzc3Nzc3Ny03Nzc3LTQ3NzctODc3Ny03Nzc3Nzc3Nzc3NzciLCJwbGF5YWJsZVN0YXRlTmFtZXNwYWNlSWQiOiI2NjY2NjY2Ni02NjY2LTQ2NjYtODY2Ni02NjY2NjY2NjY2NjYiLCJwbGF5YWJsZVN0YXRlU2NvcGUiOiJTSEFSRUQiLCJwb2ludGVyVmVyc2lvbiI6IjMiLCJyZWFsbUlkIjoiYWFhYWFhYWEtYWFhYS00YWFhLThhYWEtYWFhYWFhYWFhYWFhIiwicmVhbG1TbHVnIjoicHJvZHVjdGlvbiIsInRhcmdldENsYXNzIjoiUFVCTElDX1BST0RVQ1RJT04iLCJ0YXJnZXROYW1lc3BhY2UiOiJwcm9kIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ0ZW5hbnRTbHVnIjoidGVuYW50Iiwid29ybGRTbHVnIjoid29ybGQifSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjIiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YWxpZFVudGlsIjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJ2YXJpYW50IjoiUExBWUVSX0FETUlTU0lPTiIsInZlcmlmaWVkQ29ubmVjdFNjb3BlSWQiOiJjb250cm9sbGVkLXNjb3BlIn0=" + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5U291cmNlRXZpZGVuY2UiOlt7ImNhbm9uaWNhbEV2ZW50SnNvbiI6IntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNFwiLFwiZXZlbnRJZFwiOlwiZWRiM2JkMzMtODZlMS0zYmZkLTllYjItZjY3ZmZkYzNjOTZiXCIsXCJldmVudFR5cGVcIjpcIlRFTkFOVF9BVVRIT1JJVFlfQ0hBTkdFRFwiLFwib3V0Ym94U2VxdWVuY2VcIjpcIjFcIixcIm91dGJveFN0cmVhbUtleVwiOlwiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJyZXF1ZXN0RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwicmVxdWVzdElkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInNjaGVtYVZlcnNpb25cIjpcImFjY291bnQtdGVuYW50LWF1dGhvcml0eS1ldmVudC92MVwiLFwic291cmNlRXZpZGVuY2VcIjp7XCJjYW5vbmljYWxUZW5hbnRJZFwiOlwiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJjcmVhdGlvblJlcXVlc3RJZFwiOlwiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzXCIsXCJldmlkZW5jZURpZ2VzdFwiOlwic2hhMjU2OjcxNzQwZWZmNTcxNzI0ZDY3ZmJiMjVjMGY4NzQ1MjYyMzY1NzRmNzI0MjlhODg1OTI2ODljMWFjNDdlODAzY2VcIixcIm9wZXJhdGlvbklkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInByb3ZlbmFuY2VLaW5kXCI6XCJORVdfR0FNRV9ST1dcIixcInJlcXVlc3REaWdlc3RcIjpcInNoYTI1NjpmMDZlNWU1MGJiZGE5OTE3YjNmZGFkOGUyNzczNzA2OTNmNDlhZmMzMzllZWM3Zjc1NDhiMWU1NDEyNTQ2NjkwXCIsXCJzY2hlbWFWZXJzaW9uXCI6MSxcInNvdXJjZUdhbWVSb3dJZFwiOlwiMTdcIixcInNvdXJjZUdhbWVUZW5hbnRLZXlcIjpcIndvcmxkXCIsXCJ0YXJnZXROYW1lc3BhY2VcIjpcInByb2RcIn0sXCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uXCI6XCIyXCIsXCJ0ZW5hbnRBdXRob3JpdHlTb3VyY2VWZXJzaW9uXCI6XCIyXCIsXCJ0ZW5hbnRCaWxsaW5nUmVjZWlwdFwiOntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwiZXZlbnRJZFwiOlwiNWFjMTU4MmItYTQwZC0zNTA1LWFiNDItZjc3NjY1N2I0YjYwXCIsXCJvdXRib3hTdHJlYW1LZXlcIjpcImFjY291bnQ6dGVuYW50LWVudGl0bGVtZW50OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIixcInRlbmFudEJpbGxpbmdTZXF1ZW5jZVwiOlwiMVwifSxcInRlbmFudElkXCI6XCIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIn0iLCJldmVudERpZ2VzdCI6InNoYTI1NjowZTg0Mjk5ODMzZDg1NzU0ZmE1ODNlNDE1MGZhN2Q5MTM3NDZiODNhZWVjMzRhMDU2YzRjY2I1NjZhMTUwYzI0IiwiZXZlbnRJZCI6ImVkYjNiZDMzLTg2ZTEtM2JmZC05ZWIyLWY2N2ZmZGMzYzk2YiIsIm91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9XSwiYXV0aG9yaXR5VHVwbGUiOnsiYWNjb3VudEF1dGhvcml0eUdlbmVyYXRpb24iOiIxIiwiaXNzdWVyQXV0aEdlbmVyYXRpb24iOiIxIiwibWVtYmVyc2hpcEF1dGhvcml0eUdlbmVyYXRpb24iOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjoiMSJ9LCJwcml2YXRlUmVhbG1HcmFudFZlcnNpb25zIjpbXSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiIyIn0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiIyIiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMSJ9fX0sImJ1bmRsZVZlcnNpb24iOiIyIiwiY2FsbGVyQWNjb3VudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIiwiY2FsbGVyV29ya2xvYWQiOiJzcGlmZmU6Ly9maXJlbXVkL25zL3Byb2Qvc2EvZ2FtZS1zZXNzaW9uLXNlcnZpY2UiLCJlbnRpdGxlbWVudFZlcnNpb24iOiIxIiwiZXZhbHVhdGVkQXQiOiIyMDI2LTExLTAyVDAwOjAwOjAwWiIsImV2YWx1YXRpb25JZGVudGl0eSI6InNoYTI1NjpkYWY2MTU0MjQwNWE1MmMwOTY5OTRiNWRiODk5NmRhNGJhOWJiNWFhOGI4ZjU2YjY4YjY4NWJjNTU4NTdjYjM4IiwiZ2FtZXBsYXlBZG1pc3Npb25BbGxvd2VkIjpmYWxzZSwiZ2FtZXBsYXlBdmFpbGFibGUiOnRydWUsImlzc3VhbmNlRmVuY2UiOiIxIiwiaXNzdWVyIjoiZmlyZW11ZC1hY2NvdW50LXNlcnZpY2UiLCJtZW1iZXJzaGlwQXV0aG9yaXR5R2VuZXJhdGlvbiI6IjEiLCJtZW1iZXJzaGlwRXhpc3RzIjpmYWxzZSwibWVtYmVyc2hpcExpZmVjeWNsZVN0YXRlIjoiTUlTU0lORyIsIm1lbWJlcnNoaXBWZXJzaW9uIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6IjEifSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6YWNjb3VudC8xMTExMTExMS0xMTExLTQxMTEtODExMS0xMTExMTExMTExMTEifSx7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6aXNzdWVyL2ZpcmVtdWQtYWNjb3VudC1zZXJ2aWNlIn0seyJvdXRib3hTZXF1ZW5jZSI6IjAiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOm1lbWJlcnNoaXAvMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExLzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9LHsib3V0Ym94U2VxdWVuY2UiOiIxIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwic291cmNlRXZlbnREaWdlc3QiOiJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNCIsInNvdXJjZUV2ZW50SWQiOiJlZGIzYmQzMy04NmUxLTNiZmQtOWViMi1mNjdmZmRjM2M5NmIifV0sInByb3Zpc2lvbmluZ1N0YXR1cyI6bnVsbCwicXVvdGFzIjp7Im1heEFjdGl2ZVNlc3Npb25zIjoiMyIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiMiIsIm1heFN0b3JhZ2VCeXRlcyI6IjQwOTYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwicm9sZXMiOltdLCJzY2hlbWEiOiJhY2NvdW50LWF1dGgtZXZpZGVuY2UtYnVuZGxlL3YxIiwic25hcHNob3RJZGVudGl0eSI6InNoYTI1NjphNmQ4ZjBjOTU3NTFjMDdkNzExOTlmZGE2ZjFjYjU4MzgyY2ZkODM0NWM2MTllYWIxM2E3MWE1M2MyMmU5YTVjIiwic291cmNlS2luZCI6Ik5PTl9QQUlEX0RFTU8iLCJzb3VyY2VSZWZlcmVuY2VzIjp7ImFkbWlzc2lvblBvaW50ZXJTbmFwc2hvdERpZ2VzdCI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb21taXRQcm9vZlNoYTI1NiI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb250ZXh0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJjYWxsZXJPcGVyYXRpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclJlZ2lzdHJ5UmVjb3JkU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImNhbGxlclRva2VuRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJjYWxsZXJUb2tlbkp0aSI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclRva2VuU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImVudGl0bGVtZW50U291cmNlRGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJnYW1lU2Vzc2lvbk93bmVyUHJvb2ZEaWdlc3QiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInBhaWRSZWNlaXB0VmFsaWRVbnRpbCI6bnVsbCwicHVibGlzaGVkUG9saWN5U2V0RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzY29wZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRDYXB0dXJlSWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJ3b3JsZExpZmVjeWNsZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRSb3dWZXJzaW9uIjoiMCJ9LCJzdWJzY3JpcHRpb25TdGF0dXMiOm51bGwsInRhcmdldCI6eyJhY3RpdmVXb3JsZEVwb2NoIjoiNSIsImNhbm9uaWNhbFZlcnNpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhdGFsb2dSZXZpc2lvbiI6IjciLCJjaGFyYWN0ZXJDcmVhdGlvblBvbGljeSI6IlBSRVNFRURFRF9PTkxZIiwiY29ubmVjdFNjb3BlRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMjowMFoiLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDFUMjM6NTk6NDBaIiwiZ2FtZUluc3RhbmNlSWQiOiI3Nzc3Nzc3Ny03Nzc3LTQ3NzctODc3Ny03Nzc3Nzc3Nzc3NzciLCJwbGF5YWJsZVN0YXRlTmFtZXNwYWNlSWQiOiI2NjY2NjY2Ni02NjY2LTQ2NjYtODY2Ni02NjY2NjY2NjY2NjYiLCJwbGF5YWJsZVN0YXRlU2NvcGUiOiJTSEFSRUQiLCJwb2ludGVyVmVyc2lvbiI6IjMiLCJyZWFsbUlkIjoiYWFhYWFhYWEtYWFhYS00YWFhLThhYWEtYWFhYWFhYWFhYWFhIiwicmVhbG1TbHVnIjoicHJvZHVjdGlvbiIsInRhcmdldENsYXNzIjoiUFVCTElDX1BST0RVQ1RJT04iLCJ0YXJnZXROYW1lc3BhY2UiOiJwcm9kIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ0ZW5hbnRTbHVnIjoidGVuYW50Iiwid29ybGRTbHVnIjoid29ybGQifSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjIiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YWxpZFVudGlsIjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJ2YXJpYW50IjoiUExBWUVSX0FETUlTU0lPTiIsInZlcmlmaWVkQ29ubmVjdFNjb3BlVG9rZW5IYXNoIjoic2hhMjU2OjIyZjhhNGExOTIzNTMzNGVmZDAzNThjOTM2M2MyZTkzYzc5OWJkNWQ4NDkzODkxODk5MmExM2E3MDRiMDUzNjIifQ==" }, "playerVector": { "name": "distinct-player-admission-positive", "capacityDelta": "1", "commitAllowed": true, - "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313634363a313a3331323a6f776e657253657276696365363a737472696e673132303a67616d652d73657373696f6e2d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313533353a313a39393a6163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323232343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a36363636363636362d363636362d343636362d383636362d36363636363636363636363631343a67616d65496e7374616e63654964363a737472696e673133363a37373737373737372d373737372d343737372d383737372d37373737373737373737373731313a6368617261637465724964363a737472696e673133363a38383838383838382d383838382d343838382d383838382d383838383838383838383838393a73657373696f6e4964363a737472696e673133363a39393939393939392d393939392d343939392d383939392d393939393939393939393939373a7265616c6d4964363a737472696e673133363a61616161616161612d616161612d346161612d386161612d616161616161616161616161393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331383a706c617961626c65537461746553636f7065363a737472696e6731363a53484152454431353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431383435353a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3132333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731383130343a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523555323931636d4e6c52585a705a475675593255694f6c7437496d4e68626d397561574e68624556325a573530536e4e7662694936496e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e4677694c4677695a585a6c626e524a5a4677694f6c77695a5752694d324a6b4d7a4d744f445a6c4d53307a596d5a6b4c546c6c596a49745a6a59335a6d5a6b597a4e6a4f545a695843497358434a6c646d56756446523563475663496a7063496c5246546b464f564639425656524954314a4a56466c6651306842546b6446524677694c46776962335630596d3934553256786457567559325663496a7063496a466349697863496d393164474a7665464e30636d56686255746c655677694f6c776959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a795a5846315a584e3052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c467769636d56786457567a64456c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e4e6a6147567459565a6c636e4e7062323563496a7063496d466a59323931626e517464475675595735304c57463164476876636d6c306553316c646d5675644339324d5677694c46776963323931636d4e6c52585a705a47567559325663496a703758434a6a59573576626d6c6a595778555a573568626e524a5a4677694f6c77694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a6a636d566864476c76626c4a6c6358566c6333524a5a4677694f6c77694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a5843497358434a6c646d6c6b5a57356a5a5552705a32567a644677694f6c7769633268684d6a55324f6a63784e7a51775a575a6d4e5463784e7a49305a4459335a6d4a694d6a566a4d4759344e7a51314d6a59794d7a59314e7a526d4e7a49304d6a6c684f4467314f5449324f446c6a4d57466a4e44646c4f44417a5932566349697863496d39775a584a6864476c76626b6c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e427962335a6c626d46755932564c6157356b5843493658434a4f525664665230464e525639535431646349697863496e4a6c6358566c633352456157646c63335263496a7063496e4e6f595449314e6a706d4d445a6c4e5755314d474a695a4745354f544533596a4e6d5a47466b4f4755794e7a637a4e7a41324f544e6d4e446c685a6d4d7a4d7a6c6c5a574d335a6a63314e4468694d5755314e4445794e5451324e6a6b775843497358434a7a5932686c625746575a584a7a61573975584349364d537863496e4e7664584a6a5a556468625756536233644a5a4677694f6c77694d54646349697863496e4e7664584a6a5a556468625756555a573568626e524c5a586c63496a7063496e6476636d786b5843497358434a3059584a6e5a58524f5957316c6333426859325663496a7063496e427962325263496e307358434a305a573568626e52426458526f62334a7064486c485a57356c636d46306157397558434936584349795843497358434a305a573568626e52426458526f62334a7064486c5462335679593256575a584a7a6157397558434936584349795843497358434a305a573568626e5243615778736157356e556d566a5a576c77644677694f6e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c4677695a585a6c626e524a5a4677694f6c77694e57466a4d5455344d6d4974595451775a43307a4e5441314c5746694e4449745a6a63334e6a59314e324930596a59775843497358434a76645852696233685464484a6c5957314c5a586c63496a7063496d466a59323931626e513664475675595735304c57567564476c30624756745a5735304f6e59784f6e526c626d4675644338794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a6349697863496e526c626d467564454a7062477870626d64545a5846315a57356a5a5677694f6c77694d56776966537863496e526c626d467564456c6b58434936584349794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a63496e30694c434a6c646d5675644552705a32567a64434936496e4e6f595449314e6a6f775a5467304d6a6b354f444d7a5a4467314e7a55305a6d45314f444e6c4e4445314d475a684e3251354d544d334e445a694f444e685a57566a4d7a52684d445532597a526a593249314e6a5a684d545577597a4930496977695a585a6c626e524a5a434936496d566b596a4e695a444d7a4c5467325a5445744d324a6d5a4330355a5749794c5759324e325a6d5a474d7a597a6b3259694973496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a395853776959585630614739796158523556485677624755694f6e736959574e6a623356756445463164476876636d6c306555646c626d567959585270623234694f6949784969776961584e7a64575679515856306145646c626d567959585270623234694f6949784969776962575674596d5679633268706345463164476876636d6c306555646c626d567959585270623234694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a6f694d534a394c434a77636d6c325958526c556d566862473148636d467564465a6c636e4e706232357a496a7062585377696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694979496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694979496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d534a3966583073496d4a31626d52735a565a6c636e4e70623234694f69497849697769593246736247567951574e6a6233567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784969776959324673624756795632397961327876595751694f694a7a63476c6d5a6d55364c79396d61584a6c6258566b4c32357a4c33427962325176633245765a3246745a53317a5a584e7a615739754c584e6c636e5a70593255694c434a6c626e52706447786c6257567564465a6c636e4e70623234694f694978496977695a585a68624856686447566b515851694f6949794d4449324c5445784c544179564441774f6a41774f6a417757694973496d563259577831595852706232354a5a47567564476c3065534936496e4e6f595449314e6a6f795a4445344d7a4e6c595445304f544e6c4e6a517a4e6d4d304e5467784d44686c5a6a6b344d575a6b4f4445794f4446684e6a45334e6a41344e546379595751344d474a6d4d324a6b5932526d4e4467785a54646c496977695a3246745a58427359586c425a47317063334e7062323542624778766432566b496a706d5957787a5a5377695a3246745a58427359586c42646d467062474669624755694f6e527964575573496d6c7a63335668626d4e6c526d5675593255694f6949784969776961584e7a64575679496a6f695a6d6c795a5731315a43316859324e76645735304c584e6c636e5a70593255694c434a745a5731695a584a7a61476c77515856306147397961585235523256755a584a6864476c7662694936496a45694c434a745a5731695a584a7a61476c77525868706333527a496a706d5957787a5a53776962575674596d567963326870634578705a6d566a65574e735a564e305958526c496a6f6954556c5455306c4f52794973496d316c62574a6c636e4e6f615842575a584a7a61573975496a7037496a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694936496a45696653776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453659574e6a62335675644338784d5445784d5445784d5330784d5445784c5451784d5445744f4445784d5330784d5445784d5445784d5445784d54456966537837496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453661584e7a645756794c325a70636d56746457517459574e6a623356756443317a5a584a3261574e6c496e307365794a7664585269623368545a5846315a57356a5a534936496a41694c434a76645852696233685464484a6c5957314c5a586b694f694a6859324e76645735304f6d4631644767745958563061473979615852354f6e59784f6d316c62574a6c636e4e6f615841764d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a394c48736962335630596d39345532567864575675593255694f6949784969776962335630596d3934553352795a57467453325635496a6f6959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49794969776963323931636d4e6c52585a6c626e52456157646c633351694f694a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e434973496e4e7664584a6a5a5556325a573530535751694f694a6c5a47497a596d517a4d7930344e6d55784c544e695a6d51744f5756694d69316d4e6a646d5a6d526a4d324d354e6d496966563073496e427962335a7063326c76626d6c755a314e305958523163794936626e567362437769635856766447467a496a7037496d31686545466a64476c325a564e6c63334e706232357a496a6f694d794973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694d694973496d316865464e3062334a685a3256436558526c63794936496a51774f54596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a49697769636d39735a584d694f6c74644c434a7a5932686c625745694f694a6859324e76645735304c574631644767745a585a705a47567559325574596e56755a47786c4c335978496977696332356863484e6f6233524a5a47567564476c3065534936496e4e6f595449314e6a6f304d3255315a6a566a4e6a45775a6d4e6d4d6a426a596a51304d3245784d7a4e6b5a574e6c5a574977597a59324f544d354e6d59775a57566a5954526d4d6d59354f4451354d54466a4d544e684e6d5a694d3259794969776963323931636d4e6c53326c755a434936496b3550546c395151556c4558305246545538694c434a7a62335679593256535a575a6c636d56755932567a496a7037496d466b62576c7a63326c76626c4276615735305a584a54626d467763326876644552705a32567a64434936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a446232317461585251636d39765a6c4e6f595449314e694936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a44623235305a586830535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a6a595778735a584a5063475679595852706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c4a6c5a326c7a64484a35556d566a62334a6b553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d4e686247786c636c5276613256755258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a6a595778735a584a556232746c626b703061534936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c527661325675553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d567564476c30624756745a57353055323931636d4e6c52476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6e5957316c5532567a63326c76626b3933626d567955484a7662325a456157646c633351694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4268615752535a574e6c61584230566d467361575256626e527062434936626e5673624377696348566962476c7a6147566b5547397361574e355532563052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a593239775a5552705a32567a64434936496e4e6f595449314e6a70685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746684969776964323979624752445958423064584a6c535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a3362334a735a4578705a6d566a65574e735a5552705a32567a64434936496e4e6f595449314e6a7068595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668496977696432397962475253623364575a584a7a61573975496a6f694d434a394c434a7a64574a7a59334a7063485270623235546447463064584d694f6d353162477773496e5268636d646c6443493665794a6859335270646d565862334a735a45567762324e6f496a6f694e534973496d4e68626d397561574e6862465a6c636e4e706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e6864474673623264535a585a7063326c7662694936496a63694c434a6a6147467959574e305a584a44636d566864476c76626c427662476c6a65534936496c425352564e465255524652463950546b785a4969776959323975626d566a64464e6a6233426c5258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d6a6f774d466f694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d4446554d6a4d364e546b364e444261496977695a3246745a556c7563335268626d4e6c535751694f6949334e7a63334e7a63334e7930334e7a63334c5451334e7a63744f4463334e7930334e7a63334e7a63334e7a63334e7a63694c434a776247463559574a735a564e305958526c546d46745a584e7759574e6c535751694f6949324e6a59324e6a59324e6930324e6a59324c5451324e6a59744f4459324e6930324e6a59324e6a59324e6a59324e6a59694c434a776247463559574a735a564e305958526c55324e76634755694f694a5453454653525551694c434a7762326c7564475679566d567963326c7662694936496a4d694c434a795a57467362556c6b496a6f695957466859574668595745745957466859533030595746684c546868595745745957466859574668595746685957466849697769636d5668624731546248566e496a6f6963484a765a48566a64476c7662694973496e5268636d646c64454e7359584e7a496a6f695546564354456c4458314253543052565131524a543034694c434a3059584a6e5a58524f5957316c63334268593255694f694a77636d396b496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a305a573568626e52546248566e496a6f6964475675595735304969776964323979624752546248566e496a6f696432397962475169665377696447567559573530515856306147397961585235523256755a584a6864476c7662694936496a49694c434a305a573568626e5243615778736157356e5532567864575675593255694f694978496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a32595778705a46567564476c73496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a3259584a7059573530496a6f6955457842575556535830464554556c5455306c5054694973496e5a6c636d6c6d6157566b51323975626d566a64464e6a6233426c535751694f694a6a62323530636d39736247566b4c584e6a6233426c496e303d31333a636170616369747944656c7461363a6e756d62657231313a3131313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", - "sha256": "89ac3918c76ccd8ac17a1338ff4812ea9a2e814ccfa793e50886777b7fce334b" + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313634363a313a3331323a6f776e657253657276696365363a737472696e673132303a67616d652d73657373696f6e2d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313533353a313a39393a6163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323232343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a36363636363636362d363636362d343636362d383636362d36363636363636363636363631343a67616d65496e7374616e63654964363a737472696e673133363a37373737373737372d373737372d343737372d383737372d37373737373737373737373731313a6368617261637465724964363a737472696e673133363a38383838383838382d383838382d343838382d383838382d383838383838383838383838393a73657373696f6e4964363a737472696e673133363a39393939393939392d393939392d343939392d383939392d393939393939393939393939373a7265616c6d4964363a737472696e673133363a61616161616161612d616161612d346161612d386161612d616161616161616161616161393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331383a706c617961626c65537461746553636f7065363a737472696e6731363a53484152454431353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431383533393a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3132333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731383138383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523555323931636d4e6c52585a705a475675593255694f6c7437496d4e68626d397561574e68624556325a573530536e4e7662694936496e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e4677694c4677695a585a6c626e524a5a4677694f6c77695a5752694d324a6b4d7a4d744f445a6c4d53307a596d5a6b4c546c6c596a49745a6a59335a6d5a6b597a4e6a4f545a695843497358434a6c646d56756446523563475663496a7063496c5246546b464f564639425656524954314a4a56466c6651306842546b6446524677694c46776962335630596d3934553256786457567559325663496a7063496a466349697863496d393164474a7665464e30636d56686255746c655677694f6c776959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a795a5846315a584e3052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c467769636d56786457567a64456c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e4e6a6147567459565a6c636e4e7062323563496a7063496d466a59323931626e517464475675595735304c57463164476876636d6c306553316c646d5675644339324d5677694c46776963323931636d4e6c52585a705a47567559325663496a703758434a6a59573576626d6c6a595778555a573568626e524a5a4677694f6c77694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a6a636d566864476c76626c4a6c6358566c6333524a5a4677694f6c77694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a5843497358434a6c646d6c6b5a57356a5a5552705a32567a644677694f6c7769633268684d6a55324f6a63784e7a51775a575a6d4e5463784e7a49305a4459335a6d4a694d6a566a4d4759344e7a51314d6a59794d7a59314e7a526d4e7a49304d6a6c684f4467314f5449324f446c6a4d57466a4e44646c4f44417a5932566349697863496d39775a584a6864476c76626b6c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e427962335a6c626d46755932564c6157356b5843493658434a4f525664665230464e525639535431646349697863496e4a6c6358566c633352456157646c63335263496a7063496e4e6f595449314e6a706d4d445a6c4e5755314d474a695a4745354f544533596a4e6d5a47466b4f4755794e7a637a4e7a41324f544e6d4e446c685a6d4d7a4d7a6c6c5a574d335a6a63314e4468694d5755314e4445794e5451324e6a6b775843497358434a7a5932686c625746575a584a7a61573975584349364d537863496e4e7664584a6a5a556468625756536233644a5a4677694f6c77694d54646349697863496e4e7664584a6a5a556468625756555a573568626e524c5a586c63496a7063496e6476636d786b5843497358434a3059584a6e5a58524f5957316c6333426859325663496a7063496e427962325263496e307358434a305a573568626e52426458526f62334a7064486c485a57356c636d46306157397558434936584349795843497358434a305a573568626e52426458526f62334a7064486c5462335679593256575a584a7a6157397558434936584349795843497358434a305a573568626e5243615778736157356e556d566a5a576c77644677694f6e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c4677695a585a6c626e524a5a4677694f6c77694e57466a4d5455344d6d4974595451775a43307a4e5441314c5746694e4449745a6a63334e6a59314e324930596a59775843497358434a76645852696233685464484a6c5957314c5a586c63496a7063496d466a59323931626e513664475675595735304c57567564476c30624756745a5735304f6e59784f6e526c626d4675644338794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a6349697863496e526c626d467564454a7062477870626d64545a5846315a57356a5a5677694f6c77694d56776966537863496e526c626d467564456c6b58434936584349794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a63496e30694c434a6c646d5675644552705a32567a64434936496e4e6f595449314e6a6f775a5467304d6a6b354f444d7a5a4467314e7a55305a6d45314f444e6c4e4445314d475a684e3251354d544d334e445a694f444e685a57566a4d7a52684d445532597a526a593249314e6a5a684d545577597a4930496977695a585a6c626e524a5a434936496d566b596a4e695a444d7a4c5467325a5445744d324a6d5a4330355a5749794c5759324e325a6d5a474d7a597a6b3259694973496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a395853776959585630614739796158523556485677624755694f6e736959574e6a623356756445463164476876636d6c306555646c626d567959585270623234694f6949784969776961584e7a64575679515856306145646c626d567959585270623234694f6949784969776962575674596d5679633268706345463164476876636d6c306555646c626d567959585270623234694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a6f694d534a394c434a77636d6c325958526c556d566862473148636d467564465a6c636e4e706232357a496a7062585377696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694979496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694979496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d534a3966583073496d4a31626d52735a565a6c636e4e70623234694f69497949697769593246736247567951574e6a6233567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784969776959324673624756795632397961327876595751694f694a7a63476c6d5a6d55364c79396d61584a6c6258566b4c32357a4c33427962325176633245765a3246745a53317a5a584e7a615739754c584e6c636e5a70593255694c434a6c626e52706447786c6257567564465a6c636e4e70623234694f694978496977695a585a68624856686447566b515851694f6949794d4449324c5445784c544179564441774f6a41774f6a417757694973496d563259577831595852706232354a5a47567564476c3065534936496e4e6f595449314e6a706b595759324d5455304d6a51774e5745314d6d4d774f5459354f5452694e5752694f446b354e6d52684e474a684f574a694e5746684f4749345a6a5532596a5934596a59344e574a6a4e5455344e54646a596a4d34496977695a3246745a58427359586c425a47317063334e7062323542624778766432566b496a706d5957787a5a5377695a3246745a58427359586c42646d467062474669624755694f6e527964575573496d6c7a63335668626d4e6c526d5675593255694f6949784969776961584e7a64575679496a6f695a6d6c795a5731315a43316859324e76645735304c584e6c636e5a70593255694c434a745a5731695a584a7a61476c77515856306147397961585235523256755a584a6864476c7662694936496a45694c434a745a5731695a584a7a61476c77525868706333527a496a706d5957787a5a53776962575674596d567963326870634578705a6d566a65574e735a564e305958526c496a6f6954556c5455306c4f52794973496d316c62574a6c636e4e6f615842575a584a7a61573975496a7037496a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694936496a45696653776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453659574e6a62335675644338784d5445784d5445784d5330784d5445784c5451784d5445744f4445784d5330784d5445784d5445784d5445784d54456966537837496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453661584e7a645756794c325a70636d56746457517459574e6a623356756443317a5a584a3261574e6c496e307365794a7664585269623368545a5846315a57356a5a534936496a41694c434a76645852696233685464484a6c5957314c5a586b694f694a6859324e76645735304f6d4631644767745958563061473979615852354f6e59784f6d316c62574a6c636e4e6f615841764d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a394c48736962335630596d39345532567864575675593255694f6949784969776962335630596d3934553352795a57467453325635496a6f6959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49794969776963323931636d4e6c52585a6c626e52456157646c633351694f694a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e434973496e4e7664584a6a5a5556325a573530535751694f694a6c5a47497a596d517a4d7930344e6d55784c544e695a6d51744f5756694d69316d4e6a646d5a6d526a4d324d354e6d496966563073496e427962335a7063326c76626d6c755a314e305958523163794936626e567362437769635856766447467a496a7037496d31686545466a64476c325a564e6c63334e706232357a496a6f694d794973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694d694973496d316865464e3062334a685a3256436558526c63794936496a51774f54596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a49697769636d39735a584d694f6c74644c434a7a5932686c625745694f694a6859324e76645735304c574631644767745a585a705a47567559325574596e56755a47786c4c335978496977696332356863484e6f6233524a5a47567564476c3065534936496e4e6f595449314e6a70684e6d51345a6a426a4f5455334e54466a4d44646b4e7a45784f546c6d5a4745325a6a466a596a55344d7a677959325a6b4f444d304e574d324d546c6c595749784d3245334d5745314d324d794d6d55355954566a4969776963323931636d4e6c53326c755a434936496b3550546c395151556c4558305246545538694c434a7a62335679593256535a575a6c636d56755932567a496a7037496d466b62576c7a63326c76626c4276615735305a584a54626d467763326876644552705a32567a64434936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a446232317461585251636d39765a6c4e6f595449314e694936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a44623235305a586830535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a6a595778735a584a5063475679595852706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c4a6c5a326c7a64484a35556d566a62334a6b553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d4e686247786c636c5276613256755258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a6a595778735a584a556232746c626b703061534936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c527661325675553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d567564476c30624756745a57353055323931636d4e6c52476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6e5957316c5532567a63326c76626b3933626d567955484a7662325a456157646c633351694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4268615752535a574e6c61584230566d467361575256626e527062434936626e5673624377696348566962476c7a6147566b5547397361574e355532563052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a593239775a5552705a32567a64434936496e4e6f595449314e6a70685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746684969776964323979624752445958423064584a6c535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a3362334a735a4578705a6d566a65574e735a5552705a32567a64434936496e4e6f595449314e6a7068595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668496977696432397962475253623364575a584a7a61573975496a6f694d434a394c434a7a64574a7a59334a7063485270623235546447463064584d694f6d353162477773496e5268636d646c6443493665794a6859335270646d565862334a735a45567762324e6f496a6f694e534973496d4e68626d397561574e6862465a6c636e4e706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e6864474673623264535a585a7063326c7662694936496a63694c434a6a6147467959574e305a584a44636d566864476c76626c427662476c6a65534936496c425352564e465255524652463950546b785a4969776959323975626d566a64464e6a6233426c5258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d6a6f774d466f694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d4446554d6a4d364e546b364e444261496977695a3246745a556c7563335268626d4e6c535751694f6949334e7a63334e7a63334e7930334e7a63334c5451334e7a63744f4463334e7930334e7a63334e7a63334e7a63334e7a63694c434a776247463559574a735a564e305958526c546d46745a584e7759574e6c535751694f6949324e6a59324e6a59324e6930324e6a59324c5451324e6a59744f4459324e6930324e6a59324e6a59324e6a59324e6a59694c434a776247463559574a735a564e305958526c55324e76634755694f694a5453454653525551694c434a7762326c7564475679566d567963326c7662694936496a4d694c434a795a57467362556c6b496a6f695957466859574668595745745957466859533030595746684c546868595745745957466859574668595746685957466849697769636d5668624731546248566e496a6f6963484a765a48566a64476c7662694973496e5268636d646c64454e7359584e7a496a6f695546564354456c4458314253543052565131524a543034694c434a3059584a6e5a58524f5957316c63334268593255694f694a77636d396b496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a305a573568626e52546248566e496a6f6964475675595735304969776964323979624752546248566e496a6f696432397962475169665377696447567559573530515856306147397961585235523256755a584a6864476c7662694936496a49694c434a305a573568626e5243615778736157356e5532567864575675593255694f694978496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a32595778705a46567564476c73496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a3259584a7059573530496a6f6955457842575556535830464554556c5455306c5054694973496e5a6c636d6c6d6157566b51323975626d566a64464e6a6233426c564739725a57354959584e6f496a6f69633268684d6a55324f6a49795a6a68684e4745784f54497a4e544d7a4e47566d5a44417a4e54686a4f544d324d324d795a546b7a597a63354f574a6b4e5751344e446b7a4f446b784f446b354d6d45784d3245334d4452694d44557a4e6a496966513d3d31333a636170616369747944656c7461363a6e756d62657231313a3131313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "a78250cc70a4da7ce2933e504d1ab4d773746ff4b5a21acd18510d24b412c735" } } diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py index f1eed0afad..4adf3aa94a 100644 --- a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -169,6 +169,28 @@ def test_shared_golden_preimages_and_digests(self): def test_player_golden_preimage_and_each_player_identity(self): corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) request, candidate = corpus["playerRequest"], corpus["playerVector"] + encoded_evidence = request["canonicalAccountEvidenceBase64"] + decoded_evidence = json.loads( + base64.b64decode(evidence(encoded_evidence, "PLAYER_ADMISSION"))) + self.assertEqual(decoded_evidence["bundleVersion"], "2") + self.assertNotIn("verifiedConnectScopeId", decoded_evidence) + scope_hash = "sha256:" + hashlib.sha256(b"controlled-scope").hexdigest() + self.assertEqual(decoded_evidence["verifiedConnectScopeTokenHash"], scope_hash) + snapshot = copy.deepcopy(decoded_evidence) + for key in ("snapshotIdentity", "requestId", "evaluatedAt", "evaluationIdentity"): + snapshot.pop(key) + snapshot_identity = "sha256:" + hashlib.sha256( + canonical_json_bytes(snapshot)).hexdigest() + self.assertEqual(decoded_evidence["snapshotIdentity"], snapshot_identity) + evaluation = { + "snapshotIdentity": snapshot_identity, + "requestId": decoded_evidence["requestId"], + "callerWorkload": decoded_evidence["callerWorkload"], + "evaluatedAt": decoded_evidence["evaluatedAt"], + } + evaluation_identity = "sha256:" + hashlib.sha256( + canonical_json_bytes(evaluation)).hexdigest() + self.assertEqual(decoded_evidence["evaluationIdentity"], evaluation_identity) context_ids = [item for key, item in request["ownerContext"].items() if key.endswith("Id")] self.assertEqual(len(context_ids), len(set(context_ids))) encoded = preimage(request, candidate) diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java index 4ef24c0535..a9bfe77d4e 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodec.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import net.firedevops.firemud.account.v1.PlayerAdmissionEntitlementReadResponseBinding; import net.firedevops.firemud.account.v1.PlayerAdmissionEntitlementReadSelectors; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; @@ -81,7 +82,12 @@ public static ReadPlayerAdmissionEntitlementResponse toResponse( requireBinding(request, evidence); var wire = ReadPlayerAdmissionEntitlementResponse.newBuilder() - .addRequest(selectors(request)) + .addBinding( + PlayerAdmissionEntitlementReadResponseBinding.newBuilder() + .addSchemaVersion(2) + .addTarget( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest( + request.target()))) .addCanonicalEvidence(ByteString.copyFrom(evidence.canonicalBytes())) .build(); if (wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) throw invalid(); @@ -93,8 +99,15 @@ public static RuntimePlayerAdmissionEntitlementEvidence requireResponse( Objects.requireNonNull(expected); if (wire == null || wire.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES - || !wire.getUnknownFields().asMap().isEmpty() - || !expected.equals(parseSelectors(one(wire.getRequestList())))) throw invalid(); + || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + var binding = one(wire.getBindingList()); + if (!binding.getUnknownFields().asMap().isEmpty() + || one(binding.getSchemaVersionList()) != 2 + || !expected + .target() + .equals( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + one(binding.getTargetList())))) throw invalid(); var evidence = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( one(wire.getCanonicalEvidenceList()).toByteArray()); @@ -130,7 +143,9 @@ private static void requireBinding( || !target.tenantId().toString().equals(fields.get("tenantId")) || !target.readRequestId().toString().equals(fields.get("requestId")) || !request.expectedGameSessionWorkload().equals(fields.get("callerWorkload")) - || !request.connectScopeId().equals(fields.get("verifiedConnectScopeId"))) throw invalid(); + || !RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash( + request.connectScopeId()) + .equals(evidence.verifiedConnectScopeTokenHash())) throw invalid(); if (!(fields.get("target") instanceof Map actual) || !target.targetNamespace().equals(actual.get("targetNamespace")) || !target.tenantId().toString().equals(actual.get("tenantId")) diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java index 7d19d96322..cb459f3bcb 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java @@ -3,6 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.LinkedHashMap; @@ -10,6 +12,7 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementResponse; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; @@ -29,6 +32,7 @@ class RuntimePlayerAdmissionEntitlementGrpcCodecTest { private static final String HASH = "a".repeat(64); private static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); private static final String TOKEN = "controlled.initial.jwt"; + private static final String SCOPE = "controlled-scope"; private static RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( UUID account, UUID requestId) { @@ -47,23 +51,28 @@ private static RuntimePlayerAdmissionEntitlementGrpcCodec.Request request( REQUEST, 7, 3), - "controlled-scope"); + SCOPE); } @Test - void exactRoundTripPreservesSelectorsAndNeverEchoesCredential() { + void exactRoundTripPreservesTargetAndNeverEchoesEitherCredential() { var request = request(ACCOUNT, REQUEST); var wire = RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, TOKEN); var presented = RuntimePlayerAdmissionEntitlementGrpcCodec.parseRequest(wire); assertThat(presented.request()).isEqualTo(request); assertThat(presented.initialLoginJwt()).isEqualTo(TOKEN); - assertThat(presented.toString()).doesNotContain(TOKEN, "controlled-scope"); - assertThat(request.toString()).doesNotContain("controlled-scope"); + assertThat(presented.toString()).doesNotContain(TOKEN, SCOPE); + assertThat(request.toString()).doesNotContain(SCOPE); var value = capture(target(), facts(), sources(), NOW); var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); assertThat(RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response)) .isEqualTo(value); - assertThat(response.toByteString().toStringUtf8()).doesNotContain(TOKEN); + assertThat(response.getBinding(0).getSchemaVersionList()).containsExactly(2); + assertThat(response.getBinding(0).getTargetList()) + .containsExactly(wire.getSelectors(0).getTarget(0)); + assertThat(response.toByteString().toStringUtf8()).doesNotContain(TOKEN, SCOPE); + assertThat(value.verifiedConnectScopeTokenHash()) + .isEqualTo(RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash(SCOPE)); } @Test @@ -97,7 +106,16 @@ void missingDuplicateUnknownAndOversizedMembersAreRejected() { for (var malformed : List.of( response.getDefaultInstanceForType(), - response.toBuilder().addRequest(response.getRequest(0)).build(), + response.toBuilder().addBinding(response.getBinding(0)).build(), + response.toBuilder() + .setBinding(0, response.getBinding(0).toBuilder().clearTarget()) + .build(), + response.toBuilder() + .setBinding(0, response.getBinding(0).toBuilder().setSchemaVersion(0, 1)) + .build(), + response.toBuilder() + .setBinding(0, response.getBinding(0).toBuilder().setUnknownFields(unknown)) + .build(), response.toBuilder().addCanonicalEvidence(response.getCanonicalEvidence(0)).build(), response.toBuilder().setUnknownFields(unknown).build(), response.toBuilder() @@ -109,6 +127,61 @@ void missingDuplicateUnknownAndOversizedMembersAreRejected() { } } + @Test + void rejectsLegacyCredentialBearingResponseAndWrongCanonicalHashOrBinding() throws Exception { + var request = request(ACCOUNT, REQUEST); + var value = capture(target(), facts(), sources(), NOW); + var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); + var legacy = + ReadPlayerAdmissionEntitlementResponse.newBuilder() + .addCanonicalEvidence(response.getCanonicalEvidence(0)) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 1, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited( + RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest(request, TOKEN) + .getSelectors(0) + .toByteString()) + .build()) + .build()) + .build(); + var wrongTarget = + RuntimePlayerAdmissionEntitlementGrpcCodec.toRequest( + request(ACCOUNT, UUID.randomUUID()), TOKEN) + .getSelectors(0) + .getTarget(0); + String canonical = response.getCanonicalEvidence(0).toStringUtf8(); + for (var invalid : + List.of( + ReadPlayerAdmissionEntitlementResponse.parseFrom(legacy.toByteArray()), + ReadPlayerAdmissionEntitlementResponse.parseFrom( + response.toBuilder() + .setUnknownFields(legacy.getUnknownFields()) + .build() + .toByteArray()), + response.toBuilder() + .setBinding(0, response.getBinding(0).toBuilder().setTarget(0, wrongTarget)) + .build(), + response.toBuilder() + .setCanonicalEvidence( + 0, + ByteString.copyFromUtf8( + canonical.replace(value.verifiedConnectScopeTokenHash(), "sha256:" + HASH))) + .build(), + response.toBuilder() + .setCanonicalEvidence( + 0, + ByteString.copyFromUtf8( + canonical.replace(value.verifiedConnectScopeTokenHash(), SCOPE))) + .build())) { + assertThatThrownBy( + () -> RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + @Test void changedCallerRequestOrScopeCannotBeReturnedAsCorrelatedEvidence() { var request = request(ACCOUNT, REQUEST); @@ -134,7 +207,14 @@ private static RuntimePlayerAdmissionEntitlementEvidence capture( Map source, Instant at) { return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - REQUEST, PEER, "controlled-scope", membership(), target, facts, source, at); + REQUEST, + PEER, + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash(SCOPE), + membership(), + target, + facts, + source, + at); } private static Map target() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java index 74d686b52e..d7b8f5b94b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -37,6 +37,7 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.BooleanSupplier; +import java.util.function.UnaryOperator; import net.firedevops.firemud.account.v1.AccountPlayerAdmissionEntitlementReadServiceGrpc; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.account.v1.ReadPlayerAdmissionEntitlementRequest; @@ -122,7 +123,22 @@ void exactAccountPeerReceivesUncompressedCurrentLoginCredentialAndReturnsBoundCa var calls = new AtomicInteger(); var observedJwt = new AtomicReference(); var observedPeer = new AtomicReference(); - Server server = server("account", calls, observedJwt, observedPeer, context, login.evidence()); + var sentResponse = new AtomicReference(); + Server server = + server( + "account", + calls, + observedJwt, + observedPeer, + context.resolvedTarget(), + Instant.ofEpochMilli(context.claims().expiresAtMillis()), + login.evidence(), + (value, sources) -> {}, + () -> {}, + response -> { + sentResponse.set(response); + return response; + }); try (var client = client(server)) { client.init(); assertThat(client.buildStub(mock(ManagedChannel.class)).getCallOptions().getCompressor()) @@ -135,7 +151,12 @@ void exactAccountPeerReceivesUncompressedCurrentLoginCredentialAndReturnsBoundCa assertThat(calls).hasValue(1); assertThat(observedJwt).hasValue(JWT); assertThat(observedPeer).hasValue(GS_PEER); - assertThat(new String(result.canonicalBytes(), StandardCharsets.UTF_8)).doesNotContain(JWT); + assertThat(result.verifiedConnectScopeTokenHash()) + .isEqualTo( + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash( + context.connectScopeId())); + assertThat(sentResponse.get().toByteString().toStringUtf8()) + .doesNotContain(JWT, context.connectScopeId()); } finally { stop(server); } @@ -297,14 +318,17 @@ void directTextOwnedScopeUsesExactAccountExpiryAndCurrentLoginWithoutFirstPartyC try (var client = client(server)) { client.init(); var result = client.read(scope, ORIGINAL, TRANSPORT, READ_REQUEST, login, () -> true); - assertThat(result.fields()) - .containsEntry("verifiedConnectScopeId", "direct-text-owned-scope"); + assertThat(result.verifiedConnectScopeTokenHash()) + .isEqualTo( + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash( + "direct-text-owned-scope")); assertThat(((Map) result.fields().get("target")).get("connectScopeExpiresAt")) .isEqualTo(DIRECT_SCOPE_EXPIRY.toString()); assertThat(calls).hasValue(1); assertThat(observedJwt).hasValue(JWT); assertThat(observedPeer).hasValue(GS_PEER); - assertThat(new String(result.canonicalBytes(), StandardCharsets.UTF_8)).doesNotContain(JWT); + assertThat(new String(result.canonicalBytes(), StandardCharsets.UTF_8)) + .doesNotContain(JWT, "direct-text-owned-scope"); assertThat(borrowed) .isNotEmpty() .allSatisfy(bytes -> assertThat(bytes).containsOnly((byte) 0)); @@ -470,6 +494,7 @@ void directTextWrongAccountPeerReceivesNoCredential(String identity) throws Exce "owner-proof", "pointer-digest", "scope-expiry", + "stale-scope-hash", "login-jti", "login-hash", "login-context" @@ -490,6 +515,9 @@ void directTextRejectsAuthenticatedResponseBindingDrift(String change) throws Ex case "pointer-digest" -> sources.put("admissionPointerSnapshotDigest", "9".repeat(64)); case "scope-expiry" -> value.put("connectScopeExpiresAt", DIRECT_SCOPE_EXPIRY.plusSeconds(1).toString()); + case "stale-scope-hash" -> { + /* Changed after the exact response is encoded. */ + } case "login-jti" -> sources.put("callerTokenJti", UUID.randomUUID().toString()); case "login-hash" -> sources.put("callerTokenSha256", "9".repeat(64)); case "login-context" -> sources.put("callerContextId", UUID.randomUUID().toString()); @@ -506,7 +534,24 @@ void directTextRejectsAuthenticatedResponseBindingDrift(String change) throws Ex DIRECT_SCOPE_EXPIRY, login.evidence(), drift, - () -> {}); + () -> {}, + response -> { + if (!"stale-scope-hash".equals(change)) return response; + String scopeHash = + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash( + scope.issued().connectScopeId()); + String staleHash = + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash("stale-scope"); + return response.toBuilder() + .setCanonicalEvidence( + 0, + ByteString.copyFromUtf8( + response + .getCanonicalEvidence(0) + .toStringUtf8() + .replace(scopeHash, staleHash))) + .build(); + }); try (var client = client(server)) { client.init(); assertThatThrownBy( @@ -652,6 +697,31 @@ private static Server server( BiConsumer, Map> drift, Runnable afterRead) throws Exception { + return server( + identity, + calls, + observedJwt, + observedPeer, + target, + scopeExpiry, + login, + drift, + afterRead, + UnaryOperator.identity()); + } + + private static Server server( + String identity, + AtomicInteger calls, + AtomicReference observedJwt, + AtomicReference observedPeer, + CanonicalPlayableTarget target, + Instant scopeExpiry, + CanonicalGameplayLoginResult.NonSecretEvidence login, + BiConsumer, Map> drift, + Runnable afterRead, + UnaryOperator responseTransform) + throws Exception { var service = new AccountPlayerAdmissionEntitlementReadServiceGrpc .AccountPlayerAdmissionEntitlementReadServiceImplBase() { @@ -671,7 +741,7 @@ public void readPlayerAdmissionEntitlement( RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse( presented.request(), evidence); afterRead.run(); - observer.onNext(response); + observer.onNext(responseTransform.apply(response)); observer.onCompleted(); } catch (Exception malformed) { observer.onError( @@ -839,7 +909,7 @@ private static RuntimePlayerAdmissionEntitlementEvidence evidence( return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( request.target().readRequestId(), request.expectedGameSessionWorkload(), - request.connectScopeId(), + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash(request.connectScopeId()), membership(request.target().accountId(), request.target().tenantId(), retained), target, facts, 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 8f8df214ce..c40b355b1f 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 @@ -86,6 +86,21 @@ 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); assertThat(templateJson) From 58d8ec9b942a2b618571703368749458af8819f8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:22:37 +1300 Subject: [PATCH 50/52] Prepare the unregistered Account capacity foundation --- .../account-service/api-contracts.md | 11 +- .../account-service/runtime-and-data.md | 10 +- .../subscription-management.md | 4 +- ...ystem-architecture-authz-route-matrix.yaml | 2 +- .../system-architecture-versioning-runtime.md | 6 +- .../player-access-and-session.md | 10 +- dev-tools/evidence_digest.py | 20 +- protos/account/v1/account_service.proto | 3 + .../v1/tenant_capacity_admission.proto | 70 +++ .../AccountTenantCapacityRepository.java | 255 ++++++++ .../AccountTenantCapacityWorkloadGuard.java | 69 +++ ...ccountPlayerAdmissionEntitlementOwner.java | 26 +- .../service/AccountTenantCapacityOwner.java | 315 ++++++++++ .../AccountTenantCapacityRecoveryWorker.java | 428 +++++++++++++ .../AccountTenantCapacityGrpcService.java | 102 ++++ .../V1040__account_tenant_capacity_owner.sql | 321 ++++++++++ ...timeEntitlementNoWriteIntegrationTest.java | 332 +++++++++++ ...alJoinScopePersistenceIntegrationTest.java | 16 +- ...acityMigrationPostgresIntegrationTest.java | 219 +++++++ ...titlementOwnerPostgresIntegrationTest.java | 24 +- ...tionCompletionPostgresIntegrationTest.java | 561 ++++++++++++++++++ ...ccountTenantCapacityWorkloadGuardTest.java | 128 ++++ ...ntPlayerAdmissionEntitlementOwnerTest.java | 56 ++ .../AccountTenantCapacityOwnerTest.java | 497 ++++++++++++++++ .../AccountTenantCapacityGrpcServiceTest.java | 123 ++++ .../capacity/CapacityAdmissionDigest.java | 188 ++++++ .../OriginalNewCapacityExecution.java | 119 ++++ .../capacity/TenantCapacityAdmission.java | 407 +++++++++++++ .../capacity-admission-v1.schema.json | 19 + .../capacity/CapacityAdmissionDigestTest.java | 383 ++++++++++++ .../CapacityAdmissionTestFixture.java | 430 ++++++++++++++ .../capacity-admission-v1-vectors.json | 238 ++++++++ .../test_capacity_admission_vectors.py | 252 ++++++++ .../TenantCapacityAdmissionGrpcCodec.java | 298 ++++++++++ .../TenantCapacityAdmissionGrpcCodecTest.java | 205 +++++++ ...untRuntimeStubServerCompatibilityTest.java | 36 +- 36 files changed, 6142 insertions(+), 41 deletions(-) create mode 100644 protos/account/v1/tenant_capacity_admission.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java create mode 100644 services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java create mode 100644 services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java create mode 100644 services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java create mode 100644 services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json create mode 100644 services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index c58f842260..f5e79e14bf 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -161,7 +161,7 @@ Explicit playtest grants remain partial: registered Account persistence and inte Account has unregistered individual Creator Party, hosted-terms catalog, and individual acceptance storage in V84/V85 through `IndividualCreatorPartyRepository` and `HostedTermsRepository`, with focused repository test sources. These are storage foundations only: authenticated party provisioning and signer verification, operative legal publication, a registered acceptance API/UI, organization acceptance, party transfer, and a commit-bound currentness gate for Game Design writes remain unavailable or unproved. The canonical authority and capability limits are recorded in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. -`CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. +`CommitTenantCapacityAdmission` has a prepared proto RPC, a shared exact contract and codec, and the Account-owned durable evaluation, usage, reservation and recovery components. Account's default runtime composition leaves the capacity receiver and recovery worker unregistered. The [strict tenant-capacity tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) owns the receiving work and proof status. The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. JOIN receiver availability and its blocked Gateway route are recorded under [Current Receiver Composition](#current-receiver-composition). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. @@ -233,8 +233,11 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **target-state internal RPC** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns `TENANT_BILLING_BLOCKED` with `RESOURCE_EXHAUSTED`. Fresh creation-eligible evidence with checked insufficient capacity returns `CAPACITY_QUOTA_EXCEEDED` with the same gRPC status. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. + +The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. + - `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only. The legacy account-targeted gRPC handler returns `FAILED_PRECONDITION` before parsing selectors or reading Account data because no authorized internal caller is configured; the target tenant-only transport and authorization remain unimplemented. This containment does not change the separately authorized REST/service export path. - `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. - Pending-deletion access is a separate opaque Account credential, not a JWT or normal account session. The non-export deletion-specific routes are `GET /accounts/{accountId}/deletion`, `POST /accounts/{accountId}/deletion/cancel`, and `POST /accounts/{accountId}/deletion/billing-settlement`; each is classified `pending_deletion_scoped` for its exact action and bound to the Account-owned deletion workflow registry. The account export lifecycle is state-dependent but always uses the canonical asynchronous `POST /accounts/{accountId}/exports`, `GET /accounts/{accountId}/exports/{exportId}`, and `GET /accounts/{accountId}/exports/{exportId}/content` resources: active accounts use the ordinary authenticated account subject, while pending-deletion accounts use the pending-deletion credential and `pending_deletion_scoped` classification on that same lifecycle. These target routes are not currently routable. @@ -254,7 +257,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Local unregistered preparation:** `AccountCanonicalRuntimeMembershipSnapshotRepository` and its explicit transaction service assemble the existing shared content carrier from canonical Account and fresh-tenant provenance, current owner generations/fence, role and membership-pair records, and exact committed source events/checkpoints in one owner transaction. Current tenant cutoff fields bind exactly to the verified current tenant source; unequal historical tenant generations fail closed without an Account-owned reconciliation result. This kernel neither authenticates a caller nor grants gameplay or entitlement authority, and the runtime RPC is not wired to it. **Target gap:** the authenticated runtime producer and consumers must carry and enforce the complete fresh snapshot at their admission boundaries. - `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, and UUID provenance. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. - `ResolvePreseededActorStagingEligibility` – default-disabled, same-namespace Entity Management mTLS-only owner read limited to public-production actor staging; it returns staging evidence and creates no actor or gameplay admission. See [Preseeded actor-staging eligibility owner read](#preseeded-actor-staging-eligibility-owner-read). -- `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. +- `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `connectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `connectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. - `GetTenantEntitlementsTenant` – caller-bound tenant-admin entitlement view for billing-safe control-plane UX. @@ -461,7 +464,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | Security-locked export recovery | `/accounts/{accountId}/exports/**` while the account is `security_locked` | Account-issued `security-lock-export` credential from the Account-owned recovery workflow; no ordinary JWT, pending-deletion credential, or support-only access | Exact global account subject and export-job binding, no tenant selector, single-use initiation and expiring status/content authorization. The credential authorizes only this export lifecycle and cannot restore login, cancel deletion, mutate billing, or enter gameplay. | | Pending-deletion access | `/accounts/{accountId}/deletion`, `/accounts/{accountId}/deletion/cancel`, `/accounts/{accountId}/exports/**`, `/accounts/{accountId}/deletion/billing-settlement` | Opaque `pending-deletion-access` credential through the Account-owned workflow registry | Target-only exact `pending_deletion_scoped` route classification for deletion-specific routes and the canonical asynchronous export lifecycle. Once the account enters pending deletion, this row takes precedence over ordinary control-plane classification: `control-ui` authority is revoked and cannot access export or any other pending-deletion route. | | Internal service gRPC | `Authenticate`, `GetCallerTenantMembership`, `GetTenantMembershipForAccount`, `GetTenantMembershipForRuntime`, `GetTenantEntitlementsForRuntime`, `ListPresenceVisibilityPolicies`, payment and profile gRPC APIs | Authenticated mTLS workload identity plus method-level authorization | Internal service surfaces are not edge-exposed directly; an end-user REST JWT is not a substitute for the declared workload and method contract. Ordinary REST/admin JWTs are validated by the consuming service, not by Gateway; the gameplay-connect JWT is the separate Gateway handshake-validation exception. | -| Target internal capacity RPC | `CommitTenantCapacityAdmission` | Disjunctive method-level caller policy: exact Game Session mTLS identity plus typed `PlayerExecutionContext` and live player-binding checks, or exact World Management mTLS identity plus tenant/operation-bound instance-lifecycle context and live lifecycle checks | Target-only and not present in the current proto or service implementation. | +| Prepared internal capacity RPC | `CommitTenantCapacityAdmission` | Target disjunctive method-level caller policy: exact Game Session mTLS identity plus typed `PlayerExecutionContext` and live player-binding checks, or exact World Management mTLS identity plus tenant/operation-bound instance-lifecycle context and live lifecycle checks | Proto, strict codec, Account ledger/owner and Game Session adapter are prepared but unregistered; live owner/readback qualification and admission remain held. See [strict tenant-capacity owner status](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). | `/auth/login` and `/auth/player-bootstrap` may share the same underlying credential-verification and abuse-policy implementation, but they are separate authentication products. `/auth/login` establishes a `control-ui` control-plane session for admin/creator surfaces; `/auth/player-bootstrap` establishes only the short-lived `player-bootstrap` gameplay-discovery context. Neither endpoint may substitute one profile for the other. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1f047b9e27..fe4f92d77d 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -72,7 +72,7 @@ The current public registration path creates only a global Account row and a pla Account has source-only persistence for individual Creator Party identity, hosted-terms acceptance/environment-binding evidence, and (from V98) disclosure handoffs with immutable captured source evidence. The V98 database guards constrain handoff identity, result transitions, and source-evidence insertion. A passive Account source-fence seam now excludes unsettled World participation from applicable source mutation/abort settlement and hosted-terms disclosure preparation/dispatch admission; `HostedTermsDisclosureHandoff` and its repository use the existing V98 journal. The unregistered historical World-participation reader resolves retained participation coordinates from the complete unchanged original tuple, verifies the retained capture and source-child vector, and can read after lease expiry or immutable terminal settlement; it uses existing rows and introduces no migration or table. It does not establish currentness, renew or admit authorization, or classify an Account expiry or failed response as World `ABORTED`; only the World owner can produce that terminal outcome with its original commit/fence evidence. The handoff retains opaque authority evidence as supplied and does not authenticate it. No verifier, dispatcher, transport, registry/runtime binding, creator UI, or Game Design evidence binding is registered. Reserve, claim, and publication paths that require the hosted-terms workflow remain unavailable. The acceptance/currentness authority remains target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md), with changed-terms continuity under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner workflow is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled. -The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current text `PLAY` consumes the emitted lifecycle and independent authority generation alongside version and admission evidence; this does not establish the complete atomic-freshness contract. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current receiver composition and refusal boundaries belong to [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving). Current text `PLAY` evaluates fresh entitlement before membership/grant and later actor/binding checks; public `JOIN_REQUIRED` is limited to coherent missing or `INACTIVE` membership when enrollment permits repair. An active but non-admitting response is not a join fallback. Complete caller-target/atomic authority and the remaining AA-2.1 / Unit 1B boundaries remain open. These flows do not create or restore membership. The Account-owned public-production JOIN writer remains a prepared persistence component with atomic membership, operation-outcome, and audit-outbox evidence; the API composition contract linked above governs access to it. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Focused PostgreSQL/component proof and its limits are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof); those controlled fixtures do not establish genuine deployed receiving custody or complete public admission. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The numeric runtime entitlement endpoint remains unavailable under the [Account API contract](./api-contracts.md#grpc-apis). Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Earlier focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof is limited to the prior cardinality guard and retry boundary; it does not establish current positive entitlement production. `CommitTenantCapacityAdmission` and its Account/client persistence and reservation components are locally prepared but remain manually composed and unregistered; cross-implementation vector consumption, remaining physical PostgreSQL qualification, deployed custody, and selected-owner/final activation proof remain open. The [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the capability and proof status. The current `application.yml` and `application-prod.yml` retain `GetTenantMembershipForRuntime`, `GetRealmAccessGrantForRuntime`, `GetTenantEntitlementsForRuntime`, and `ListPresenceVisibilityPolicies` in the gRPC bearer-validation bypass list. Their handlers independently require certificate-derived workload identity in the exact configured namespace: Game Session for membership and realm-grant reads, Game Session or World Management for entitlement reads, and Social & Groups for presence-policy reads. Handler and configured-interceptor tests cover permitted peers without bearer credentials and refusal of unauthorized or wrong-namespace peers. This workload-only bypass does not make the methods unauthenticated public APIs. Complete typed caller-context and tenant-binding qualification, membership/currentness consumption, and the remaining canonical admission and registry contracts remain separate gaps under the [Account API contract](./api-contracts.md); these workload checks alone do not establish readiness. @@ -82,7 +82,9 @@ Recovery/verification foundations are live. Password-reset completion now uses a Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlement receiving boundaries are defined by [Account API Contracts](./api-contracts.md#rest-apis) and its [gRPC inventory](./api-contracts.md#grpc-apis). The held boundary, preserved positive component obligations, and proof history are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-billing-and-retention-receiving). Game Session text `REALMS`/`JOIN` dispatch remains unimplemented under #2898; unknown JOIN outcome recovery and Logging receipt receiver/readback remain #2848, and direct text-client end-to-end proof remains open. The target scope and transport contract remains in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). -The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints compare the complete reservation inventory with usage; eligibility reads and issuer-local counters cannot initialize or replace it. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. + +The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. Account's default runtime leaves the capacity receiver, selected-owner readback and recovery worker unregistered. Controlled observations prove Account ledger transitions. Actual Game Session execution, closure and admitted-session teardown require their own retained owner receipts. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. The adapter participates only in the explicitly enabled protected LOGIN composition; default deployment behavior remains unchanged. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). Deployed authenticated issuance and timing parity remain unproved. @@ -318,7 +320,9 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. -The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. +The numeric runtime entitlement endpoint follows the [Account API refusal boundary](./api-contracts.md#endpoint-authentication-classes). The separate manually composed PLAYER_ADMISSION owner/receiver and Game Session client preserve canonical V2 scope/current-owner evidence under the [private purpose contract](./api-contracts.md#private-player-admission-entitlement-read); their presence does not wire or qualify a runtime cutover. Canonical UUID billing and the distinct unregistered `TENANT_OPERATION` source are prepared separately; the complete public `PLAYER_ADMISSION` consumer is not yet qualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-public-account-facade-receiving) owns public receiving proof and gaps. `V1040` prepares immutable capacity-evaluation, attempt-history, and recovery-evidence records plus guarded reservations, but no capacity-family retention entry, horizon, or owner-safe cleanup/archive contract is defined under [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). This remains an open Account activation limitation; existing guards and holds remain in force. + +Retained player-admission version-1 evidence remains immutable and held for owner-governed retention. Player-admission version 2 is required for new capacity requests and their replay. Before activation or reuse of predecessor-populated storage, establish the retained Account and Game Session SQL and Redis inventory and resolve its outstanding confirmation, replay, recovery and restore obligations under the [objective compatibility gates](../../decisions/adr-0081-objective-compatibility-gates-for-database-evolution.md). ### Playtest Grant Persistence and Authority Consequences diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index ea6dd50a10..3c6ee18739 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -13,7 +13,7 @@ Payment-instrument ownership, explicit per-subscription binding, initial billing ## Implementation Status -The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. Account now has unregistered customer-first-dispatch and exact-customer saved-method owner sources, but these prerequisites do not create a subscription or enable a caller path. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it lacks the caller-supplied stable `requestId`, exact instrument-selection input, and immutable creation-operation identities. Account computes the versioned `requestDigest` from normalized request fields; that digest is not a caller-supplied request field. Account must also resolve the authoritative billing owner, which is not supplied as a request field. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The durable authority/usage ledger and reservation lifecycle for strict capacity admission are also not implemented. +The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. Account now has unregistered customer-first-dispatch and exact-customer saved-method owner sources, but these prerequisites do not create a subscription or enable a caller path. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it lacks the caller-supplied stable `requestId`, exact instrument-selection input, and immutable creation-operation identities. Account computes the versioned `requestDigest` from normalized request fields; that digest is not a caller-supplied request field. Account must also resolve the authoritative billing owner, which is not supplied as a request field. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The strict capacity owner and durable usage/reservation source are locally prepared but remain unregistered and unqualified; see [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The target `CreateSubscription` request accepts a high-entropy stable caller-supplied `requestId` as the sole logical create-operation key, along with the normalized tenant, plan, and instrument-selection inputs. Account resolves the authoritative billing owner and computes a versioned `requestDigest` from those normalized inputs and the resolved owner; neither the digest nor billing-owner resolution is supplied as a request field. Account captures the resolved owner's authority version/generation and validates that exact fence in the same local intent/outbox transaction before persisting the pair or creating provider work; an owner change or generation/version mismatch fails closed. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same `subscriptionId`, durable operation, and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`. The provider `subscription_provisioning_request_id` and cleanup identity remain separate provider-operation keys and must not replace the caller identity. @@ -205,7 +205,7 @@ Downstream services depend on billing events for timely entitlement enforcement, - **Periodic refresh** – even when events are flowing, every healthy runtime consumer must refresh or reconcile cached entitlements at least once per 60 seconds so extended event outages meet the `<=60-second` delayed/missed-event SLA rather than causing unbounded drift. - `CreateSubscription` – Create one hosting subscription for an immutable `tenantId` and initial `plan_code`. The caller supplies a high-entropy stable `requestId`; Account resolves the authoritative billing owner and computes and persists a versioned `requestDigest` from the normalized create tuple, including that owner, immutable `tenantId`, initial `plan_code`, and exact instrument-selection input. The digest and resolved billing owner are not request fields. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same durable operation and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`; the caller identity is distinct from provider operation identities. It rejects an existing `subscriptionId`, expected row version, update operation ID, or any other update-only field. Creation must resolve the authoritative billing owner before its subscription row exists, capture the owner's authority version/generation, authorize the actor against that resolved owner (or require the explicit audited cross-tenant handoff), and require either an explicit saved `paymentInstrumentId` or deterministic instrument-selection input that resolves to exactly one saved instrument owned by that owner. In one local Account transaction, Account locks or CAS-validates the resolved owner and exact captured version/generation before committing the subscription operation, immutable internal `subscriptionId` and `tenantId`, owner, owner fence, customer-operation reference, confirmed provider customer when available, instrument binding and reserved instrument version, `pending` status, immutable `subscription_provisioning_request_id`, separate cleanup/cancellation provider-operation identity, and outbox work item before customer reconciliation or provider creation. An owner-fence mismatch fails closed before any provider operation. The worker may reconcile the customer operation while the row remains pending, but its provisioning claim atomically requires a confirmed matching customer and revalidates ownership, exact instrument version, and attachability; detach racing with provisioning is serialized by that reservation/version boundary and a stale claim fails before Stripe. Creation retries retain the creation identity for lookup; cleanup retries reuse the distinct cleanup identity. Stripe customer and provider defaults are prohibited. -- `CommitTenantCapacityAdmission` – Target Account-owned internal RPC and final capacity fence described above. Its canonical callers are Game Session and World Management; it requires stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by evaluation, bounded `capacityDelta`, and a versioned `mutationDigest` over the attempt identity, fence, and complete payload. An exact identity-and-payload retry replays; any changed bundle version, snapshot/evaluation identity, entitlement field, tuple, cutoff, checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation. The initial attempt needs no rearm CAS. A new attempt requires an Account-owned CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; that CAS advances the fence without creating a second reservation. Stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. It is the only contract that can turn a fresh entitlement snapshot into a strict capacity commitment. Downstream owners cannot replace it with a local compare or cached flag. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – Target Account-owned internal RPC and final capacity fence described above. Its canonical callers are Game Session and World Management; it requires stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by evaluation, bounded `capacityDelta`, and a versioned `mutationDigest` over the attempt identity, fence, and complete payload. An exact identity-and-payload retry replays; any changed bundle version, snapshot/evaluation identity, entitlement field, tuple, cutoff, checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation. The initial attempt needs no rearm CAS. A new attempt requires an Account-owned CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; that CAS advances the fence without creating a second reservation. Stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. It is the only contract that can turn a fresh entitlement snapshot into a strict capacity commitment. Downstream owners cannot replace it with a local compare or cached flag. The shared contract, Account durable owner and private receiver, and Game Session adapter are locally prepared without runtime registration or qualification; current source/proof limits remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `UpdateSubscription` – Apply one plan, instrument, cancellation, or other supported update to an existing immutable `subscriptionId`. Period-end and immediate cancellation both use this mutation; no separate `CancelSubscription` mutation exists. It requires the target subscription identity, a distinct immutable operation-specific request ID, and the expected subscription row version/CAS; it rejects `subscription_provisioning_request_id`, creation-only fields, and any attempted `tenantId` change. Retries reuse the same update identity and guard and never reuse the initial provisioning identity. Provider activation and billing require a confirmed provider subscription ID. Caller-bound tenant variants derive actor identity from auth context; cross-tenant admin variants are separate APIs. - `GetSubscriptionTenantHighLevel` / `ListSubscriptionsTenantHighLevel` – Query subscription state for one tenant, scoped by tenant authorization. - `ListSubscriptionsCrossTenantSupportSafe` – Cross-tenant support-safe high-level listing for troubleshooting only. diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 93293d9b42..721fbbcc52 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -3171,7 +3171,7 @@ routes: changed_attempt_without_rearm_ordering: rejected_before_any_mutation mutation_contract: account_owned_fenced_capacity_reservation_create_or_replay canonical_errors: - any_of: [CAPACITY_ADMISSION_STALE, CAPACITY_QUOTA_EXCEEDED, FENCE_REJECTED, IDEMPOTENCY_CONFLICT, AUTH_UNAVAILABLE] + any_of: [CAPACITY_ADMISSION_STALE, CAPACITY_QUOTA_EXCEEDED, TENANT_BILLING_BLOCKED, ENTITLEMENT_UNAVAILABLE, FENCE_REJECTED, IDEMPOTENCY_CONFLICT, AUTH_UNAVAILABLE, PERMISSION_DENIED, INVALID_ARGUMENT] fence_rejection_requirements: no_accept_no_runtime_mutation_proof - service: account-service route: GetTenantEntitlementsTenant diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index a43c074d23..eb6cb274f1 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -32,7 +32,7 @@ Purge failure status is also not durable in the current implementation: `Finaliz Asset repair now reads and verifies the existing durable version-scoped source snapshot and independently reads the retained export candidate, checks that candidate against the release attestation before writes, and conditionally writes content-addressed objects with exact object readback. Repair does not create a snapshot or candidate. This source implementation does not yet prove physical object-store or PostgreSQL behavior, restart recovery, or a global publication/purge fence; those remain unproved. -Capacity admission is also target-state only. Account's `CommitTenantCapacityAdmission` RPC and both caller integrations (Game Session and World Management) are unimplemented, as are the durable Account authority/usage ledger, the exact `capacityDelta` wire contract, the capacity-admission action-family schema and cross-language `mutationDigest/v1` golden vectors, and the reservation create/finalize/release/reconciliation lifecycle. The capacity-admission sections below are normative contracts and must not be read as evidence that these RPC, caller, ledger, schema/vector, or reservation components exist. +Capacity admission remains unregistered and unqualified. Prepared source, proof definitions and remaining activation gates are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation); the sections below remain normative target contracts rather than runtime qualification. The live Account runtime does not yet produce the complete authority evidence required by recovery and capacity-admission consumers. `roles`, `membershipAuthorityGeneration`, `authorityTuple`, and `outboxCheckpoints` remain target-state fields until Account exposes them together from one authoritative snapshot; these flows must not infer or synthesize them from the current partial response. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#implementation-status) for the owning implementation status. @@ -478,7 +478,7 @@ The serving operation is classified before the read: ### Capacity Delta Wire and Digest Contract -The target `CommitTenantCapacityAdmission` protobuf request declares `capacity_delta` as `optional int64`; its canonical JSON/proto-JSON spelling is `capacityDelta`, represented as a base-10 decimal string. Explicit protobuf presence is mandatory: generated `hasCapacityDelta()`/presence checks must be used, and a missing field, JSON `null`, wrapper message, or implicit scalar default is not the value zero. There is no accepted alternate field or numeric type. The signed wire type is intentional: negative values are representable for diagnostic rejection but are never valid capacity mutations. This is a target-state contract because the current Account proto does not expose this RPC. +The target `CommitTenantCapacityAdmission` protobuf request declares `capacity_delta` as `optional int64`; its canonical JSON/proto-JSON spelling is `capacityDelta`, represented as a base-10 decimal string. Explicit protobuf presence is mandatory: generated `hasCapacityDelta()`/presence checks must be used, and a missing field, JSON `null`, wrapper message, or implicit scalar default is not the value zero. There is no accepted alternate field or numeric type. The signed wire type is intentional: negative values are representable for diagnostic rejection but are never valid capacity mutations. Prepared wire support and remaining qualification are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The logical range is the non-negative signed-`int64` range `0 <= capacityDelta <= 9223372036854775807`, but presence and operation class are separate mandatory checks. An absent `capacityDelta` is always invalid; it must be rejected by Game Session and World Management before calling Account and again by Account before any commitment, reservation, usage mutation, or owner activation CAS. A present zero is valid only after the operation has been classified as eligible entitlement-preserving non-expanding recovery or one-for-one replacement and the complete Account evidence proves that classification; it reserves and changes no usage. A present positive value is valid only for a capacity-creating activation/cutover and must also be no greater than the operation's net requested capacity, available Account quota, and remaining plan entitlement. Account, Game Session, and World Management must apply these same absent/zero/positive rules, rather than relying on a generated getter, a local re-read, or the other caller's validation. Negative values, values outside the signed `int64` wire range, malformed decimal JSON spellings, and any parse or checked-arithmetic overflow are rejected before an Account commitment, reservation, usage mutation, or owner activation CAS. Account must perform checked addition and comparison for usage and quota; it must reject rather than wrap, saturate, narrow, or coerce through a floating-point type. @@ -486,7 +486,7 @@ For the capacity action-family schema, `capacityDelta` is a declared member of t The absent encoding exists only to produce a deterministic rejected digest vector; an absent request can never commit. -The capacity vector fixture is normative proof work for Account, Game Session, and World Management. It fixes every non-`capacityDelta` field in the published `capacity-admission/v1` schema, including the complete capacity shape used for non-expanding comparison, and publishes canonical preimage bytes plus the expected lowercase SHA-256 digest for `absent`, `present(0)`, a representative valid positive value such as `17`, and the boundary `present(9223372036854775807)`. It also publishes request candidates for `9223372036854775808`, signed negatives, malformed decimal spellings, signed-`int64`/JSON overflow, changed capacity-shape fields, and checked usage/quota addition overflow, with the expected rejection before commitment and no accepted mutation digest. Every implementation in Account and both callers must consume the same vectors and produce the same accepted/rejected result; until that schema/vector corpus and focused proof exist, capacity admission remains unsupported target state. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the focused proof and record fixture execution results in PR/CI or implementation-tracking evidence; it supplements these owner-local requirements and does not create an execution ledger. +The capacity vector fixture is normative proof work for Account, Game Session, and World Management. It fixes every non-`capacityDelta` field in the published `capacity-admission/v1` schema, including the complete capacity shape used for non-expanding comparison, and publishes canonical preimage bytes plus the expected lowercase SHA-256 digest for `absent`, `present(0)`, a representative valid positive value such as `17`, and the boundary `present(9223372036854775807)`. It also publishes request candidates for `9223372036854775808`, signed negatives, malformed decimal spellings, signed-`int64`/JSON overflow, changed capacity-shape fields, and checked usage/quota addition overflow, with the expected rejection before commitment and no accepted mutation digest. Every implementation in Account and both callers must consume the same vectors and produce the same accepted/rejected result. The [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the existing shared schema/vector fixtures and scoped proof; complete cross-language consumption, physical owner proof and runtime qualification remain required before capacity admission is enabled. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the focused proof and record fixture execution results in PR/CI or implementation-tracking evidence; it supplements these owner-local requirements and does not create an execution ledger. The changed-capacity-shape candidates in this fixture represent expanding or unvalidated changes and therefore must reject before commitment. A changed shape with Account-authenticated proof of a non-expanding effective resource delta is covered by the eligible replacement rule and is not an unconditional rejection case. 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 9b7a31ce69..c0a6812d65 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -26,6 +26,14 @@ This is an intentionally breaking preproduction format cutover of the manually c The Account source/transport foundation contains unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. These do not replace live PLAY authority. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, initial hosting provider-write source with its focused units, and dependent physical proof. Private FRESH/World preparation remains a separate receiving obligation. A functioning canonical PLAY replacement remains unqualified; no caller custody, runtime registration, admission or activation is established by these source boundaries. +### 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. + +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. + +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 requires 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 and activation holds. + ### Controlled player-admission transport composition The prepared `controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission` case in [AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java) connects the actual Account PostgreSQL entitlement owner and unregistered mTLS receiver to the actual Game Session client. It checks both absent and joined membership, unchanged membership count, exact canonical response bytes, credential exclusion and refusal after the custody callback becomes false. LOGIN issuance/currentness and protected Game Session/World target inputs remain explicit controlled doubles; this does not establish genuine custody, a complete source chain, admission or production registration. Local compilation, enabled integration static analysis, Java formatting, Markdown and link checks pass, but all four PostgreSQL cases were skipped because Docker is unavailable. Physical execution remains outstanding. Required full-stack smoke on `89ae1be` / `e8fa889` still fails at the intentionally denied numeric entitlement endpoint; this test preparation does not replace that evidence or change the default-off runtime. @@ -632,7 +640,7 @@ With canonical scope consumers absent from the default composition, Account conn | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. The default public bootstrap discovery, direct-scope, JOIN, and connect-token receiving composition returns `AUTH_UNAVAILABLE` before bootstrap/scope or legacy authority reads. Manually configured receivers follow the [Account API composition boundaries](../../architecture/microservices/account-service/api-contracts.md); connect-token validates bootstrap identity and reads scope but remains held before replay or issuance. The numeric runtime entitlement receiver returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. The held boundary, preserved positive component obligations, and proof history are in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving). Target current-authority and postcondition revalidation remain unproved. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. Prepared JOIN component behavior retains the subscription-row lock boundary, remote scope/target/entitlement checks outside the lock-holding transaction, and atomic membership, operation-outcome, and audit-outbox persistence. These components are not reachable through the default receiving facade. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal retained numeric subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; the canonical UUID billing-owner detection gap is recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving), and retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionProvisioner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java); [AccountHostingSubscriptionProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionProvisionerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java); [AccountHostingSubscriptionProvisioningServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java); [AccountHostingSubscriptionDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | -| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | +| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml); [bounded capacity owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java); [original-NEW final owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [Account/Game Session capacity composition](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java); [native final-admission evidence](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | Bounded reservation/final-admission source and focused proof are prepared but unregistered; [strict capacity status](#strict-tenant-capacity-owner-preparation) records the executed and unrun boundaries and remaining production qualification. The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [Authenticated TCP receiver](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java); [live LOGIN custody](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java); [verified TCP origin](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java); [dedicated mTLS Gateway client](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java); [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [authenticated receiver units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java); [live custody units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java); [Gateway mTLS client units](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java); [TCP listener admission integration](../../../services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Authenticated TCP receiving preserves the Gateway-verified origin over the dedicated exact-namespace mTLS hop and retains LOGIN custody on the original live backend generation. Missing protected owners or custody fail closed as `UNAVAILABLE`; malformed commands and missing local LOGIN/WORLDS/REALMS steps return bounded actionable errors. Source and controlled-component proof do not qualify a deployed authenticated LOGIN-to-PLAY chain, canonical admission, fresh-image runtime behavior, or production Redis/PKI/source custody. Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN has selectable default-off dispatch through the existing Account gRPC service and composition of its existing owner graph; genuine runtime caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | diff --git a/dev-tools/evidence_digest.py b/dev-tools/evidence_digest.py index 19ad420d04..9020866943 100644 --- a/dev-tools/evidence_digest.py +++ b/dev-tools/evidence_digest.py @@ -7,12 +7,12 @@ from typing import Any -def canonical_evidence_digest(record: dict[str, Any]) -> str: - """Hash a record, excluding only its top-level immutableArtifactId field. +def canonical_json_bytes(value: Any) -> bytes: + """Encode the restricted RFC 8785 evidence subset as canonical UTF-8 bytes. - Nested immutableArtifactId occurrences remain part of the canonical payload. + Evidence records intentionally reject floating-point values and integers outside + the interoperable range rather than applying JavaScript number rounding. """ - payload = {key: value for key, value in record.items() if key != "immutableArtifactId"} def encode(value: Any) -> str: if value is None: @@ -38,5 +38,15 @@ def encode(value: Any) -> str: return "[" + ",".join(encode(nested) for nested in value) + "]" raise TypeError(f"unsupported evidence value type: {type(value).__name__}") - encoded = encode(payload).encode("utf-8") + return encode(value).encode("utf-8") + + +def canonical_evidence_digest(record: dict[str, Any]) -> str: + """Hash a record, excluding only its top-level immutableArtifactId field. + + Nested immutableArtifactId occurrences remain part of the canonical payload. + """ + payload = {key: value for key, value in record.items() if key != "immutableArtifactId"} + + encoded = canonical_json_bytes(payload) return f"sha256:{hashlib.sha256(encoded).hexdigest()}" diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 56e6a9183f..0d5cc807cb 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -3,12 +3,15 @@ syntax = "proto3"; package account.v1; import "shared/v1/errors.proto"; +import "account/v1/tenant_capacity_admission.proto"; import "shared/v1/player_execution_context.proto"; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; service AccountService { + // Strict capacity owner. Available only through an explicitly composed bounded mTLS receiver. + rpc CommitTenantCapacityAdmission(CommitTenantCapacityAdmissionRequest) returns (CommitTenantCapacityAdmissionResponse); rpc Ping(PingRequest) returns (PingResponse); rpc CreateAccount(CreateAccountRequest) returns (CreateAccountResponse); rpc Authenticate(AuthenticateRequest) returns (AuthenticateResponse); diff --git a/protos/account/v1/tenant_capacity_admission.proto b/protos/account/v1/tenant_capacity_admission.proto new file mode 100644 index 0000000000..973bb17cc1 --- /dev/null +++ b/protos/account/v1/tenant_capacity_admission.proto @@ -0,0 +1,70 @@ +syntax = "proto3"; +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Singleton repeated envelopes preserve multiplicity for the strict bounded codec. +message TenantCapacityShape { + repeated int64 active_sessions = 1; + repeated int64 concurrent_game_instances = 2; + repeated int64 storage_bytes = 3; +} +// Exact PlayerExecutionContext content with strict singleton multiplicity preserved on this wire. +message TenantCapacityPlayerContext { + repeated string account_id = 1; + repeated string tenant_id = 2; + repeated string playable_state_namespace_id = 3; + repeated string game_instance_id = 4; + repeated string character_id = 5; + repeated string session_id = 6; + repeated string realm_id = 7; + repeated string request_id = 8; + repeated string playable_state_scope = 9; +} +message TenantCapacityWorldContext { + repeated string tenant_id = 1; + repeated string operation_id = 2; + repeated string lifecycle_id = 3; + repeated string game_instance_id = 4; + repeated string owner_id = 5; + repeated int64 owner_fence = 6; +} +message TenantCapacityAdmissionAttempt { + repeated string tenant_id = 1; + repeated string request_id = 2; + repeated string admission_id = 3; + repeated string admission_attempt_id = 4; + repeated int64 capacity_rearm_fence = 5; + repeated string target_namespace = 6; + // Exactly one typed alternative, never a caller-supplied workload identity. + repeated TenantCapacityPlayerContext player_context = 7; + repeated TenantCapacityWorldContext world_context = 8; + repeated string operation = 9; + repeated TenantCapacityShape prior_shape = 10; + repeated TenantCapacityShape requested_shape = 11; + // Exact existing Account canonical bundle; content parsing cannot register its authority. + repeated bytes canonical_account_evidence = 12; + repeated string mutation_digest = 13; +} +message CommitTenantCapacityAdmissionRequest { + repeated TenantCapacityAdmissionAttempt attempt = 1; + // Mandatory presence. Proto JSON is a canonical base-10 decimal string, not a JSON number. + optional int64 capacity_delta = 2; +} +message TenantCapacityAdmissionCommitment { + repeated string tenant_id = 1; + repeated string request_id = 2; + repeated string admission_id = 3; + repeated string admission_attempt_id = 4; + repeated int64 capacity_rearm_fence = 5; + repeated string mutation_digest = 6; + repeated string reservation_id = 7; + repeated int64 reservation_fence = 8; + repeated string expires_at = 9; + repeated string state = 10; + repeated string snapshot_identity = 11; + repeated string evaluation_identity = 12; +} +message CommitTenantCapacityAdmissionResponse { + repeated TenantCapacityAdmissionCommitment commitment = 1; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java new file mode 100644 index 0000000000..275bc5920a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -0,0 +1,255 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Clock; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-local primitives only, always in the owning writable transaction. No bean or seed API. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private owner transaction collaborator.") +public final class AccountTenantCapacityRepository { + private final DSLContext dsl; + + public AccountTenantCapacityRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Called by the actual Account player evaluator before its final source transaction commits. */ + public void retainPlayerEvaluation(RuntimePlayerAdmissionEntitlementEvidence source) { + retain(Evidence.player(source)); + } + + private void retain(Evidence evidence) { + transaction(); + int inserted = + dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations " + + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz) ON CONFLICT (evaluation_identity) DO NOTHING", + evidence.evaluationIdentity(), + evidence.snapshotIdentity(), + evidence.tenantId(), + evidence.callerWorkload(), + evidence.owner().service(), + evidence.canonicalBytes(), + at(evidence.evaluatedAt()), + at(evidence.expiresAt())); + if (inserted != 0 && inserted != 1) throw unavailable(); + requireRetained(evidence); + } + + public void requireRetained(Evidence evidence) { + transaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ? FOR SHARE", + evidence.evaluationIdentity()); + if (row == null + || !evidence.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !evidence.snapshotIdentity().equals(row.get("snapshot_identity", String.class)) + || !evidence.callerWorkload().equals(row.get("caller_workload", String.class)) + || !evidence.owner().service().equals(row.get("owner_service", String.class)) + || !Arrays.equals(evidence.canonicalBytes(), row.get("canonical_evidence", byte[].class)) + || !evidence + .evaluatedAt() + .truncatedTo(java.time.temporal.ChronoUnit.MICROS) + .equals(time(row, "evaluated_at")) + || !evidence + .expiresAt() + .truncatedTo(java.time.temporal.ChronoUnit.MICROS) + .equals(time(row, "expires_at"))) throw unavailable(); + } + + public Record find(Identity id) { + transaction(); + return dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? FOR UPDATE", + id.tenantId(), + id.requestId(), + id.admissionId()); + } + + public Record usage(Request request) { + transaction(); + Record usage = + dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = ? FOR UPDATE", + request.identity().tenantId(), + request.context().owner().service()); + if (usage == null) throw unavailable(); + return usage; + } + + public Result exact(Request request, Record row) { + if (!request.mutationDigest().equals(row.get("mutation_digest", String.class)) + || !request.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class)) + || request.capacityRearmFence() != number(row, "capacity_rearm_fence") + || !Arrays.equals( + CapacityAdmissionDigest.preimage(request), row.get("canonical_payload", byte[].class)) + || !request.evidence().callerWorkload().equals(row.get("caller_workload", String.class))) + throw conflict(); + return result(row); + } + + public void requirePriorHistory(Request prior, Request next) { + transaction(); + if (!prior.identity().equals(next.identity()) + || prior.admissionAttemptId().equals(next.admissionAttemptId()) + || next.capacityRearmFence() != Math.incrementExact(prior.capacityRearmFence())) + throw conflict(); + Record history = + dsl.fetchOne( + "SELECT * FROM account_tenant_capacity_attempt_history WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? FOR SHARE", + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId()); + if (history == null + || number(history, "capacity_rearm_fence") != prior.capacityRearmFence() + || !prior.mutationDigest().equals(history.get("mutation_digest", String.class)) + || !Arrays.equals( + CapacityAdmissionDigest.preimage(prior), history.get("canonical_payload", byte[].class)) + || history.get("owner_readback", byte[].class) == null) throw conflict(); + } + + public Result create(Request request, Instant expiresAt, Clock clock) { + Record usage = usage(request); + requireCurrentLifetime(request.evidence(), clock.instant()); + long delta = Objects.requireNonNull(request.capacityDelta()); + long occupied = Math.addExact(number(usage, "held_units"), number(usage, "used_units")); + if (delta > request.evidence().quota() - occupied) + throw new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED); + long held = Math.addExact(number(usage, "held_units"), delta); + updateUsage(request, usage, held, number(usage, "used_units")); + int created = + dsl.execute( + "INSERT INTO account_tenant_capacity_reservations " + + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, admission_attempt_id, capacity_rearm_fence, reservation_fence, mutation_digest, canonical_payload, evaluation_identity, capacity_delta, expires_at, reconcile_deadline, state, execution_status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING')", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + UUID.randomUUID(), + request.context().owner().service(), + request.evidence().callerWorkload(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + CapacityAdmissionDigest.preimage(request), + request.evidence().evaluationIdentity(), + delta, + at(expiresAt), + at(expiresAt.plusSeconds(60))); + if (created != 1) throw unavailable(); + return exact(request, Objects.requireNonNull(find(request.identity()))); + } + + public static void requireCurrentLifetime(Evidence evidence, Instant now) { + // PostgreSQL stores microseconds. Floor the bound, never round an expiry forward. + if (now.isBefore(evidence.evaluatedAt()) + || !now.isBefore(evidence.expiresAt().truncatedTo(ChronoUnit.MICROS))) { + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + } + } + + public void updateUsage(Request request, Record before, long held, long used) { + transaction(); + if (held < 0 || used < 0 || Math.addExact(held, used) < 0) throw unavailable(); + long revision = number(before, "usage_revision"); + int updated = + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = ?, used_units = ?, usage_revision = ? WHERE tenant_uuid = ? AND owner_service = ? AND usage_revision = ?", + held, + used, + Math.incrementExact(revision), + request.identity().tenantId(), + request.context().owner().service(), + revision); + if (updated != 1) throw unavailable(); + } + + public Result result(Record row) { + transaction(); + Record evaluation = + dsl.fetchOne( + "SELECT snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + row.get("evaluation_identity", String.class)); + if (evaluation == null) throw unavailable(); + return new Result( + new Identity( + row.get("tenant_uuid", UUID.class), + row.get("request_id", UUID.class), + row.get("admission_id", UUID.class)), + row.get("admission_attempt_id", UUID.class), + number(row, "capacity_rearm_fence"), + row.get("mutation_digest", String.class), + row.get("reservation_id", UUID.class), + number(row, "reservation_fence"), + time(row, "expires_at"), + State.valueOf(row.get("state", String.class)), + evaluation.get("snapshot_identity", String.class), + row.get("evaluation_identity", String.class)); + } + + public static long number(Record row, String name) { + Long value = row.get(name, Long.class); + if (value == null || value < 0) throw unavailable(); + return value; + } + + public static Instant time(Record row, String name) { + OffsetDateTime value = row.get(name, OffsetDateTime.class); + if (value == null) throw unavailable(); + return value.toInstant(); + } + + public static OffsetDateTime at(Instant instant) { + return instant.truncatedTo(java.time.temporal.ChronoUnit.MICROS).atOffset(ZoneOffset.UTC); + } + + public static void transaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw unavailable(); + } + + public static CapacityException conflict() { + return new CapacityException(Failure.IDEMPOTENCY_CONFLICT); + } + + public static CapacityException unavailable() { + return new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE); + } + + public static final class CapacityException extends IllegalStateException { + private final Failure code; + + public CapacityException(Failure code) { + super(code.name()); + this.code = code; + } + + public Failure code() { + return code; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java new file mode 100644 index 0000000000..88e1694a6f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.accountservice.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.util.Set; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Sole producer of the receiver's private exact-method TLS caller assertion. */ +public final class AccountTenantCapacityWorkloadGuard implements ServerInterceptor { + private final Context.Key caller = Context.key("tenant-capacity-authenticated-peer"); + private final Set allowed; + + public AccountTenantCapacityWorkloadGuard(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + allowed = + Set.of( + TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION), + TenantCapacityAdmission.expectedWorkload(namespace, Owner.WORLD_MANAGEMENT)); + } + + public String requireAuthenticatedCaller() { + String value = caller.get(); + if (!allowed.contains(value == null ? "" : value) || ambient()) + throw Status.UNAUTHENTICATED.asRuntimeException(); + return value; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + var peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); + if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); + if (ambient() + || !allowed.contains(peer.orElseThrow().uri()) + || !AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() + .getFullMethodName() + .equals(call.getMethodDescriptor().getFullMethodName())) + return deny(call, Status.PERMISSION_DENIED); + return Contexts.interceptCall( + Context.current().withValue(caller, peer.orElseThrow().uri()), call, headers, next); + } + + private static boolean ambient() { + return SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + private static ServerCall.Listener deny( + ServerCall call, Status status) { + call.close( + status.withDescription("Exact capacity owner workload and method required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index 9b6ddd5dc6..c8b384f56e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -573,7 +573,7 @@ private static void requireSupportedTarget( || !"PRESEEDED_ONLY".equals(target.characterCreationPolicy())) throw targetPrecondition(); } - private static RuntimePlayerAdmissionEntitlementEvidence capture( + private RuntimePlayerAdmissionEntitlementEvidence capture( Request request, CurrentPlayer player, PublishedRealmEvidence target, @@ -632,15 +632,21 @@ private static RuntimePlayerAdmissionEntitlementEvidence capture( RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); sources.put("worldCaptureId", world.captureId().toString()); sources.put("worldRowVersion", Long.toString(world.rowVersion())); - return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - request.requestId(), - request.authenticatedCallerWorkload(), - scope.scopeTokenHash(), - player.snapshot(), - binding, - facts, - sources, - time); + var evidence = + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + request.requestId(), + request.authenticatedCallerWorkload(), + scope.scopeTokenHash(), + player.snapshot(), + binding, + facts, + sources, + time); + // Retain only inside this actual evaluator's final source transaction. A supplied bundle + // cannot register itself as capacity authority, and commit failure returns no evidence. + new net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository(dsl) + .retainPlayerEvaluation(evidence); + return evidence; } private static Map facts( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java new file mode 100644 index 0000000000..87cb05708a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -0,0 +1,315 @@ +package net.firedevops.firemud.accountservice.service; + +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.number; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.requireCurrentLifetime; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Instant; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +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.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.dao.CannotSerializeTransactionException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered strict Account capacity authority. Caller identity must come from the bounded mTLS + * receiver. No caller can register a bundle, initialize usage, attest an execution result, or cause + * a final Game Session/World activation here. World capacity remains held without its current + * lifecycle/evaluation producer. The scalar shape is deliberately restricted to an exact new player + * binding; non-expanding recovery stays held until Account has authoritative prior-shape evidence. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private Account owner collaborators.") +public final class AccountTenantCapacityOwner { + private final DSLContext dsl; + private final AccountRepository accounts; + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships; + private final AccountGameplayDelegationIssuanceRepository issuances; + private final AccountConnectScopeRepository scopes; + private final AccountTenantCapacityRepository capacity; + private final TransactionTemplate transaction; + private final Clock clock; + private final String namespace; + + public AccountTenantCapacityOwner( + DSLContext dsl, + AccountRepository accounts, + AccountCanonicalRuntimeMembershipSnapshotRepository memberships, + AccountGameplayDelegationIssuanceRepository issuances, + AccountConnectScopeRepository scopes, + PlatformTransactionManager transactions, + Clock clock, + String namespace) { + this.dsl = Objects.requireNonNull(dsl); + this.accounts = Objects.requireNonNull(accounts); + this.memberships = Objects.requireNonNull(memberships); + this.issuances = Objects.requireNonNull(issuances); + this.scopes = Objects.requireNonNull(scopes); + this.capacity = new AccountTenantCapacityRepository(dsl); + this.clock = Objects.requireNonNull(clock); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setTimeout(5); + } + + public Result commit(Request request, String authenticatedCaller) { + requireCaller(request, authenticatedCaller); + request.requireStructurallyValid(); + return commitWithFreshSnapshot( + () -> { + lockPlayerAccount(request); + Record existing = capacity.find(request.identity()); + // Replay/conflict is resolved before current-source reads and any usage write. + if (existing != null) return capacity.exact(request, existing); + if (request.capacityRearmFence() != 1) throw conflict(); + current(request); + requireSupportedShape(request); + if (!request.evidence().permitsCreation()) + throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); + return capacity.create(request, request.evidence().expiresAt(), clock); + }); + } + + /** Only the Account-owned recovery worker calls this after storing terminal no-commit proof. */ + Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { + prior.requireCommittable(); + next.requireCommittable(); + if (!prior.identity().equals(next.identity()) + || prior.admissionAttemptId().equals(next.admissionAttemptId()) + || next.capacityRearmFence() != Math.incrementExact(prior.capacityRearmFence()) + || !prior.context().equals(next.context()) + || prior.operation() != next.operation() + || !prior.priorShape().equals(next.priorShape()) + || !prior.requestedShape().equals(next.requestedShape()) + || !Objects.equals(prior.capacityDelta(), next.capacityDelta()) + || !Objects.equals( + prior.evidence().fields().get("authorityTuple"), + next.evidence().fields().get("authorityTuple"))) throw conflict(); + return inTransaction( + () -> { + lockPlayerAccount(next); + Record row = capacity.find(prior.identity()); + if (row == null) throw conflict(); + if (next.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class))) { + capacity.requirePriorHistory(prior, next); + return capacity.exact(next, row); + } + capacity.exact(prior, row); + requireClaim(row, recoveryOwner, claimFence, clock.instant()); + if (!"RESERVED".equals(row.get("state", String.class)) + || !"NOT_EXECUTED_AFTER_AUTHORIZATION" + .equals(row.get("execution_status", String.class)) + || row.get("owner_readback", byte[].class) == null) throw conflict(); + current(next); + requireSupportedShape(next); + requireCurrentLifetime(next.evidence(), clock.instant()); + int history = + dsl.execute( + "INSERT INTO account_tenant_capacity_attempt_history " + + "(tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId(), + prior.capacityRearmFence(), + prior.mutationDigest(), + CapacityAdmissionDigest.preimage(prior), + row.get("owner_readback", byte[].class)); + if (history != 1) throw unavailable(); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, capacity_rearm_fence = ?, reservation_fence = ?, mutation_digest = ?, canonical_payload = ?, evaluation_identity = ?, expires_at = ?::timestamptz, reconcile_deadline = ?::timestamptz, next_reconcile_at = NULL, recovery_attempt_count = 0, execution_status = 'OWNER_EXECUTION_PENDING', owner_readback = NULL, owner_readback_digest = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND capacity_rearm_fence = ? AND mutation_digest = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", + next.admissionAttemptId(), + next.capacityRearmFence(), + Math.incrementExact(number(row, "reservation_fence")), + next.mutationDigest(), + CapacityAdmissionDigest.preimage(next), + next.evidence().evaluationIdentity(), + at(next.evidence().expiresAt()), + at(next.evidence().expiresAt().plusSeconds(60)), + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId(), + prior.capacityRearmFence(), + prior.mutationDigest(), + recoveryOwner, + claimFence); + if (changed != 1) throw conflict(); + // Reservation identity and both usage columns are deliberately untouched. + return capacity.exact(next, Objects.requireNonNull(capacity.find(next.identity()))); + }); + } + + private void current(Request request) { + var evidence = request.evidence(); + capacity.requireRetained(evidence); + Instant now = clock.instant(); + requireCurrentLifetime(evidence, now); + if (!(request.context() instanceof PlayerContext player)) throw unavailable(); + var parsed = + RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( + request.evidence().canonicalBytes()); + var current = + qualifiedSource(() -> memberships.readCurrent(player.accountId(), player.tenantId())); + if (!current.membershipExists() + || !current.gameplayAdmissionAllowed() + || !"ACTIVE".equals(current.membershipLifecycleState())) throw unavailable(); + var fields = evidence.fields(); + if (!current.equals(parsed.membershipSource())) { + var billing = + current + .authorityTuple() + .tenantBillingCutoff() + .map(cutoffs -> cutoffs.get(current.tenantId())) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + if (Long.parseLong(billing.tenantBillingSequence()) + > Long.parseLong((String) fields.get("tenantBillingSequence"))) + throw new CapacityException(Failure.CAPACITY_ADMISSION_STALE); + throw unavailable(); + } + if (!(fields.get("sourceReferences") instanceof Map source)) throw unavailable(); + var issuance = + qualifiedSource( + () -> + issuances.readCurrentCommittedCandidateByJti( + UUID.fromString((String) source.get("callerTokenJti")))) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + if (!issuance.identity().accountId().equals(player.accountId()) + || !issuance.identity().callerWorkload().equals(request.evidence().callerWorkload()) + || !issuance.identity().callerContextId().toString().equals(source.get("callerContextId")) + || !issuance.identity().operationId().toString().equals(source.get("callerOperationId")) + || !issuance.tokenSha256().equals(source.get("callerTokenSha256")) + || !issuance + .canonicalRegistryRecordSha256() + .equals(source.get("callerRegistryRecordSha256")) + || !issuance.commitProofSha256().equals(source.get("callerCommitProofSha256")) + || now.getEpochSecond() < issuance.identity().notBeforeEpochSecond() + || now.getEpochSecond() >= issuance.identity().expiresAtEpochSecond()) throw unavailable(); + var scope = + qualifiedSource( + () -> + scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash())) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + if (!scope.accountUuid().equals(player.accountId()) + || !scope.tenantUuid().equals(player.tenantId()) + || !scope.scopeDigest().equals(source.get("scopeDigest")) + || !scope.gameInstanceUuid().equals(player.gameInstanceId()) + || !scope.playableStateNamespaceUuid().equals(player.playableStateNamespaceId()) + || !scope.realmId().equals(player.realmId()) + || !scope.playableStateScope().equals(player.playableStateScope()) + || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) throw unavailable(); + } + + private static T qualifiedSource(Supplier read) { + try { + return read.get(); + } catch (IllegalArgumentException | IllegalStateException unqualifiedSource) { + throw unavailable(); + } + } + + private static void requireSupportedShape(Request request) { + if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION + || request.operation() != TenantCapacityAdmission.Operation.CAPACITY_CREATING + || !request.priorShape().equals(new TenantCapacityAdmission.Shape(0, 0, 0)) + || !request.requestedShape().equals(new TenantCapacityAdmission.Shape(1, 0, 0)) + || !Long.valueOf(1).equals(request.capacityDelta())) throw unavailable(); + } + + private void lockPlayerAccount(Request request) { + if (!(request.context() instanceof PlayerContext player)) throw unavailable(); + accounts + .findByAccountUuidForUpdate(player.accountId()) + .orElseThrow(AccountTenantCapacityRepository::unavailable); + } + + private void requireCaller(Request request, String caller) { + if (request == null || !namespace.equals(request.targetNamespace())) + throw new CapacityException(Failure.INVALID_ARGUMENT); + if (!TenantCapacityAdmission.expectedWorkload(namespace, request.context().owner()) + .equals(caller) + || !request.evidence().callerWorkload().equals(caller)) + throw new CapacityException(Failure.PERMISSION_DENIED); + } + + static void requireClaim(Record row, UUID owner, long fence, Instant now) { + if (owner == null + || !owner.equals(row.get("recovery_owner", UUID.class)) + || fence != number(row, "recovery_claim_fence") + || !now.isBefore(AccountTenantCapacityRepository.time(row, "recovery_claim_expires_at"))) + throw conflict(); + } + + private Result commitWithFreshSnapshot(Supplier action) { + try { + return inTransaction(action); + } catch (RuntimeException failure) { + // PostgreSQL has rolled back this serialization failure. The whole next transaction needs + // a new snapshot so a concurrent first attempt can become exact replay or conflict. + if (!serializationFailure(failure) || Context.current().isCancelled()) throw failure; + return inTransaction(action); + } + } + + private static boolean serializationFailure(RuntimeException failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof CannotSerializeTransactionException + || cause instanceof org.jooq.exception.DataAccessException jooq + && "40001".equals(jooq.sqlState()) + || cause instanceof SQLException sql && "40001".equals(sql.getSQLState())) return true; + } + return false; + } + + T inTransaction(Supplier action) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + return Objects.requireNonNull( + transaction.execute( + status -> { + AccountTenantCapacityRepository.transaction(); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() + != Connection.TRANSACTION_SERIALIZABLE) throw unavailable(); + }); + return action.get(); + })); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java new file mode 100644 index 0000000000..11997dbb02 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java @@ -0,0 +1,428 @@ +package net.firedevops.firemud.accountservice.service; + +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.number; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** + * Unregistered Account reservation recovery. Only this owner mutates reservation outcomes. Its + * protected selected-owner read client is a required dependency, not an automatically registered + * source or a caller-supplied attestation. Original-NEW Game Session has a bounded exact reader; + * World lifecycle and other action families remain unsupported. No timeout synthesizes no-commit. + */ +@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Private owner/source collaborators.") +public final class AccountTenantCapacityRecoveryWorker { + public enum Disposition { + COMMITTED, + NOT_EXECUTED_AFTER_AUTHORIZATION, + INDETERMINATE + } + + public enum NoCommitAction { + RETAIN_FOR_REARM, + RELEASE + } + + /** + * An implementation must use the exact selected owner's authenticated mTLS readback and validate + * its current owner fence and authoritative state, including durable original-attempt rejection + * and no mutation for NOT_EXECUTED_AFTER_AUTHORIZATION. Content construction is not authority. + * FENCE_REJECTED, FAILED, pending and ambiguous responses map only to INDETERMINATE. + */ + public interface ExecutionReadClient { + Observation readExact(Request request, Result reservation, Instant deadline); + } + + public record Observation( + String authenticatedOwnerWorkload, + Result reservation, + byte[] canonicalAttemptPayload, + Disposition disposition, + UUID proofId, + long currentOwnerFence, + String authoritativeStateDigest, + byte[] canonicalOwnerReadback) { + public Observation { + Objects.requireNonNull(reservation); + Objects.requireNonNull(disposition); + TenantCapacityAdmission.uuid(proofId); + if (authenticatedOwnerWorkload == null + || currentOwnerFence <= 0 + || authoritativeStateDigest == null + || !authoritativeStateDigest.matches("sha256:[0-9a-f]{64}") + || canonicalAttemptPayload == null + || canonicalAttemptPayload.length == 0 + || canonicalAttemptPayload.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES + || canonicalOwnerReadback == null + || canonicalOwnerReadback.length == 0 + || canonicalOwnerReadback.length > 256 * 1024) + throw new IllegalArgumentException("Complete owner readback required"); + canonicalAttemptPayload = canonicalAttemptPayload.clone(); + canonicalOwnerReadback = canonicalOwnerReadback.clone(); + } + + @Override + public byte[] canonicalAttemptPayload() { + return canonicalAttemptPayload.clone(); + } + + @Override + public byte[] canonicalOwnerReadback() { + return canonicalOwnerReadback.clone(); + } + + @Override + public String toString() { + return "CapacityOwnerObservation[redacted]"; + } + } + + private final AccountTenantCapacityOwner owner; + private final DSLContext dsl; + private final AccountTenantCapacityRepository capacity; + private final ExecutionReadClient source; + private final Clock clock; + private final UUID workerId = UUID.randomUUID(); + private final Set inFlight = ConcurrentHashMap.newKeySet(); + + public AccountTenantCapacityRecoveryWorker( + AccountTenantCapacityOwner owner, DSLContext dsl, ExecutionReadClient source, Clock clock) { + this.owner = Objects.requireNonNull(owner); + this.dsl = Objects.requireNonNull(dsl); + this.capacity = new AccountTenantCapacityRepository(dsl); + this.source = Objects.requireNonNull(source); + this.clock = Objects.requireNonNull(clock); + } + + /** Twelve bounded observations or the original deadline quarantine the same complete hold. */ + public Result reconcile(Request request, NoCommitAction noCommitAction) { + Objects.requireNonNull(noCommitAction); + request.requireCommittable(); + return withExclusiveOperation( + request.identity(), () -> reconcileClaim(request, noCommitAction)); + } + + private Result reconcileClaim(Request request, NoCommitAction noCommitAction) { + Claim claim = claim(request); + if (claim.reservation().state() != State.RESERVED) return claim.reservation(); + if (claim.noCommitProof() != null) { + if (noCommitAction == NoCommitAction.RETAIN_FOR_REARM) return claim.reservation(); + return owner.inTransaction( + () -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result current = capacity.exact(request, row); + AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); + if (!current.equals(claim.reservation()) + || !"NOT_EXECUTED_AFTER_AUTHORIZATION" + .equals(row.get("execution_status", String.class)) + || !Arrays.equals(claim.noCommitProof(), row.get("owner_readback", byte[].class))) + throw conflict(); + moveUsage(request, false); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = 'RELEASED', reservation_fence = ?, next_reconcile_at = NULL WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", + Math.incrementExact(current.reservationFence()), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + workerId, + claim.fence()); + if (changed != 1) throw conflict(); + return capacity.exact( + request, Objects.requireNonNull(capacity.find(request.identity()))); + }); + } + Observation candidate = null; + byte[] candidateProof = null; + if (claim.attempts() < 12) { + Instant started = clock.instant(); + boolean positiveOnly = !started.isBefore(claim.reconcileDeadline()); + Instant deadline = started.plusSeconds(5); + if (!positiveOnly && claim.reconcileDeadline().isBefore(deadline)) + deadline = claim.reconcileDeadline(); + try { + candidate = source.readExact(request, claim.reservation(), deadline); + if (!clock.instant().isBefore(deadline)) throw unavailable(); + requireExactSource(request, claim.reservation(), candidate); + // A delayed first reconciliation must still recognize an exact committed effect. The + // expired negative-evidence window never permits a late read to release the hold. + if (positiveOnly && candidate.disposition() != Disposition.COMMITTED) throw unavailable(); + candidateProof = proof(request, candidate); + } catch (RuntimeException unavailableSource) { + // Missing, malformed, late and failed reads are indeterminate, never no-commit proof. + candidate = null; + candidateProof = null; + } + } + final Observation observed = candidate; + final byte[] exactProof = candidateProof; + return owner.inTransaction( + () -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result current = capacity.exact(request, row); + AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); + if (!current.equals(claim.reservation())) throw conflict(); + int attempt = Math.incrementExact(Math.toIntExact(number(row, "recovery_attempt_count"))); + if (attempt > 12) throw unavailable(); + Instant now = clock.instant(); + boolean indeterminate = + observed == null || observed.disposition() == Disposition.INDETERMINATE; + boolean quarantine = + indeterminate && (attempt == 12 || !now.isBefore(claim.reconcileDeadline())); + String outcome = + quarantine + ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() + : observed == null ? "SOURCE_UNAVAILABLE" : observed.disposition().name(); + int retained = + dsl.execute( + "INSERT INTO account_tenant_capacity_recovery_evidence (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, recovery_policy_version, recovery_attempt_number, observed_at, outcome, canonical_readback, readback_digest) VALUES (?, ?, ?, ?, ?, 'capacity-recovery/1', ?, ?::timestamptz, ?, ?, ?)", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.admissionAttemptId(), + claim.fence(), + attempt, + at(now), + outcome, + exactProof, + exactProof == null ? null : sha256(exactProof)); + if (retained != 1) throw unavailable(); + if (indeterminate) { + int updated = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_attempt_count = ?, state = ?, recovery_escalated_at = ?::timestamptz, next_reconcile_at = ?::timestamptz WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", + attempt, + quarantine + ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() + : State.RESERVED.name(), + quarantine ? at(now) : null, + quarantine + ? null + : at( + now.plusSeconds(5).isBefore(claim.reconcileDeadline()) + ? now.plusSeconds(5) + : claim.reconcileDeadline()), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + workerId, + claim.fence()); + if (updated != 1) throw conflict(); + return capacity.exact( + request, Objects.requireNonNull(capacity.find(request.identity()))); + } + boolean committed = observed.disposition() == Disposition.COMMITTED; + State next = + committed + ? State.FINALIZED + : noCommitAction == NoCommitAction.RELEASE ? State.RELEASED : State.RESERVED; + if (committed || next == State.RELEASED) moveUsage(request, committed); + long reservationFence = + next == State.RELEASED + ? Math.incrementExact(current.reservationFence()) + : current.reservationFence(); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = ?, execution_status = ?, owner_readback = ?, owner_readback_digest = ?, reservation_fence = ?, recovery_attempt_count = ?, next_reconcile_at = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND mutation_digest = ? AND reservation_fence = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", + next.name(), + committed ? "COMMITTED" : "NOT_EXECUTED_AFTER_AUTHORIZATION", + exactProof, + sha256(exactProof), + reservationFence, + attempt, + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.admissionAttemptId(), + request.mutationDigest(), + current.reservationFence(), + workerId, + claim.fence()); + if (changed != 1) throw conflict(); + return capacity.exact(request, Objects.requireNonNull(capacity.find(request.identity()))); + }); + } + + private void moveUsage(Request request, boolean committed) { + Record usage = capacity.usage(request); + long delta = Objects.requireNonNull(request.capacityDelta()); + capacity.updateUsage( + request, + usage, + Math.subtractExact(number(usage, "held_units"), delta), + committed + ? Math.addExact(number(usage, "used_units"), delta) + : number(usage, "used_units")); + } + + public Result rearm(Request prior, Request next) { + prior.requireCommittable(); + next.requireCommittable(); + return withExclusiveOperation(prior.identity(), () -> rearmClaim(prior, next)); + } + + private Result rearmClaim(Request prior, Request next) { + java.util.Optional replay = + owner.inTransaction( + () -> { + Record row = capacity.find(next.identity()); + if (row != null + && next.admissionAttemptId() + .equals(row.get("admission_attempt_id", UUID.class))) { + capacity.requirePriorHistory(prior, next); + return java.util.Optional.of(capacity.exact(next, row)); + } + return java.util.Optional.empty(); + }); + if (replay.isPresent()) return replay.orElseThrow(); + Claim claim = claim(prior); + return owner.rearm(prior, next, workerId, claim.fence()); + } + + private Result withExclusiveOperation(Identity identity, Supplier operation) { + // This worker can advance its own live claim for a sequential retry or rearm. + if (!inFlight.add(identity)) throw unavailable(); + try { + return operation.get(); + } finally { + inFlight.remove(identity); + } + } + + private Claim claim(Request request) { + return owner.inTransaction( + () -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result result = capacity.exact(request, row); + if (result.state() != State.RESERVED) + return new Claim( + result, + number(row, "recovery_claim_fence"), + Math.toIntExact(number(row, "recovery_attempt_count")), + AccountTenantCapacityRepository.time(row, "reconcile_deadline"), + row.get("owner_readback", byte[].class)); + Instant now = clock.instant(); + if (row.get("recovery_owner", UUID.class) != null + && !workerId.equals(row.get("recovery_owner", UUID.class)) + && now.isBefore( + AccountTenantCapacityRepository.time(row, "recovery_claim_expires_at"))) + throw unavailable(); + long fence = Math.incrementExact(number(row, "recovery_claim_fence")); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = ?, recovery_claim_expires_at = ?::timestamptz, next_reconcile_at = LEAST(?::timestamptz, reconcile_deadline) " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_claim_fence = ?", + workerId, + fence, + at(now.plusSeconds(15)), + at(now.plusSeconds(5)), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + number(row, "recovery_claim_fence")); + if (changed != 1) throw conflict(); + return new Claim( + result, + fence, + Math.toIntExact(number(row, "recovery_attempt_count")), + AccountTenantCapacityRepository.time(row, "reconcile_deadline"), + row.get("owner_readback", byte[].class)); + }); + } + + private static void requireExactSource(Request request, Result expected, Observation observed) { + if (observed == null + || !expected.equals(observed.reservation()) + || !TenantCapacityAdmission.expectedWorkload( + request.targetNamespace(), request.context().owner()) + .equals(observed.authenticatedOwnerWorkload()) + || !Arrays.equals( + CapacityAdmissionDigest.preimage(request), observed.canonicalAttemptPayload())) + throw unavailable(); + } + + private static byte[] proof(Request request, Observation observed) { + // Fixed content binding includes the entire attempt and exact owner readback, not a boolean. + var output = new java.io.ByteArrayOutputStream(); + for (byte[] bytes : + new byte[][] { + "account-capacity-owner-readback/v1".getBytes(java.nio.charset.StandardCharsets.US_ASCII), + CapacityAdmissionDigest.preimage(request), + observed + .reservation() + .reservationId() + .toString() + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + Long.toString(observed.reservation().reservationFence()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed + .authenticatedOwnerWorkload() + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.disposition().name().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.proofId().toString().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + Long.toString(observed.currentOwnerFence()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.authoritativeStateDigest().getBytes(java.nio.charset.StandardCharsets.US_ASCII), + observed.canonicalOwnerReadback() + }) { + output.writeBytes( + Integer.toString(bytes.length).getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + byte[] proof = output.toByteArray(); + if (proof.length > 1024 * 1024) throw unavailable(); + return proof; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + private record Claim( + Result reservation, + long fence, + int attempts, + Instant reconcileDeadline, + byte[] noCommitProof) { + private Claim { + noCommitProof = noCommitProof == null ? null : noCommitProof.clone(); + } + + @Override + public byte[] noCommitProof() { + return noCommitProof == null ? null : noCommitProof.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java new file mode 100644 index 0000000000..22a326f5f3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Objects; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit private composition only. Other Account RPCs remain UNIMPLEMENTED on this server. */ +public final class AccountTenantCapacityGrpcService + extends AccountServiceGrpc.AccountServiceImplBase { + private final AccountTenantCapacityOwner owner; + private final AccountTenantCapacityWorkloadGuard guard; + + public AccountTenantCapacityGrpcService(AccountTenantCapacityOwner owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + guard = new AccountTenantCapacityWorkloadGuard(namespace); + } + + public Server createUnregisteredServer( + String address, KeyManagerFactory keys, TrustManagerFactory trust) { + var factory = + new BoundedGrpcServerFactory( + Objects.requireNonNull(address), + List.of(), + Objects.requireNonNull(keys), + Objects.requireNonNull(trust), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES); + factory.addService(ServerInterceptors.interceptForward(this, guard)); + return factory.createServer(); + } + + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String peer; + try { + peer = guard.requireAuthenticatedCaller(); + } catch (StatusRuntimeException denied) { + observer.onError(Failure.AUTH_UNAVAILABLE.toStatusException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError( + Failure.ENTITLEMENT_UNAVAILABLE.toStatusException(Status.Code.FAILED_PRECONDITION)); + return; + } + final net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request; + try { + request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + } catch (IllegalArgumentException | ArithmeticException invalid) { + observer.onError(Failure.INVALID_ARGUMENT.toStatusException()); + return; + } + if (!request.evidence().callerWorkload().equals(peer)) { + observer.onError(Failure.PERMISSION_DENIED.toStatusException()); + return; + } + final CommitTenantCapacityAdmissionResponse result; + try { + result = TenantCapacityAdmissionGrpcCodec.toResponse(request, owner.commit(request, peer)); + } catch (CapacityException denied) { + observer.onError(denied.code().toStatusException()); + return; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException unavailable) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); + return; + } catch (RuntimeException internal) { + observer.onError(Status.INTERNAL.asRuntimeException()); + return; + } + try { + observer.onNext(result); + observer.onCompleted(); + } catch (RuntimeException callback) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql b/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql new file mode 100644 index 0000000000..ceec667db8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql @@ -0,0 +1,321 @@ +-- Existing tenants are deliberately not initialized from missing usage or eligibility snapshots. +ALTER TABLE account_fresh_tenant_identity_associations ADD COLUMN capacity_birth_transaction VARCHAR(20); +ALTER TABLE account_fresh_tenant_identity_associations ALTER COLUMN capacity_birth_transaction SET DEFAULT pg_current_xact_id()::TEXT; + +CREATE TABLE account_tenant_capacity_usage ( + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + owner_service VARCHAR(40) NOT NULL CHECK (owner_service IN ('game-session-service', 'world-management-service')), + bootstrap_request_id UUID NOT NULL REFERENCES account_tenant_creation_bootstrap_operations(request_id), + creation_evidence_digest VARCHAR(71) NOT NULL CHECK (creation_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + held_units BIGINT NOT NULL CHECK (held_units >= 0), + used_units BIGINT NOT NULL CHECK (used_units >= 0), + usage_revision BIGINT NOT NULL CHECK (usage_revision > 0), + PRIMARY KEY (tenant_uuid, owner_service), + CHECK (held_units <= 9223372036854775807 - used_units) +); + +CREATE TABLE account_tenant_capacity_evaluations ( + evaluation_identity VARCHAR(71) PRIMARY KEY CHECK (evaluation_identity ~ '^sha256:[0-9a-f]{64}$'), + snapshot_identity VARCHAR(71) NOT NULL CHECK (snapshot_identity ~ '^sha256:[0-9a-f]{64}$'), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + caller_workload VARCHAR(253) NOT NULL, + owner_service VARCHAR(40) NOT NULL CHECK (owner_service IN ('game-session-service', 'world-management-service')), + canonical_evidence BYTEA NOT NULL CHECK (octet_length(canonical_evidence) BETWEEN 1 AND 262144), + evaluated_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > evaluated_at) +); + +CREATE TABLE account_tenant_capacity_reservations ( + tenant_uuid UUID NOT NULL, + request_id UUID NOT NULL CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + admission_id UUID NOT NULL CHECK (admission_id <> '00000000-0000-0000-0000-000000000000'::UUID), + reservation_id UUID NOT NULL UNIQUE CHECK (reservation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + owner_service VARCHAR(40) NOT NULL, + caller_workload VARCHAR(253) NOT NULL, + admission_attempt_id UUID NOT NULL UNIQUE, + capacity_rearm_fence BIGINT NOT NULL CHECK (capacity_rearm_fence > 0), + reservation_fence BIGINT NOT NULL CHECK (reservation_fence > 0), + mutation_digest CHAR(64) NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + canonical_payload BYTEA NOT NULL CHECK (octet_length(canonical_payload) BETWEEN 1 AND 524288), + evaluation_identity VARCHAR(71) NOT NULL REFERENCES account_tenant_capacity_evaluations(evaluation_identity), + capacity_delta BIGINT NOT NULL CHECK (capacity_delta >= 0), + expires_at TIMESTAMPTZ NOT NULL, + state VARCHAR(64) NOT NULL CHECK (state IN ('RESERVED', 'FINALIZED', 'RELEASED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), + execution_status VARCHAR(48) NOT NULL CHECK (execution_status IN ('OWNER_EXECUTION_PENDING', 'COMMITTED', 'NOT_EXECUTED_AFTER_AUTHORIZATION')), + recovery_owner UUID, + recovery_claim_fence BIGINT NOT NULL DEFAULT 0 CHECK (recovery_claim_fence >= 0), + recovery_claim_expires_at TIMESTAMPTZ, + next_reconcile_at TIMESTAMPTZ, + reconcile_deadline TIMESTAMPTZ NOT NULL, + recovery_policy_version VARCHAR(32) NOT NULL DEFAULT 'capacity-recovery/1' CHECK (recovery_policy_version = 'capacity-recovery/1'), + recovery_attempt_count INT NOT NULL DEFAULT 0 CHECK (recovery_attempt_count BETWEEN 0 AND 12), + recovery_escalated_at TIMESTAMPTZ, + owner_readback BYTEA CHECK (octet_length(owner_readback) BETWEEN 1 AND 1048576), + owner_readback_digest CHAR(64) CHECK (owner_readback_digest ~ '^[0-9a-f]{64}$'), + PRIMARY KEY (tenant_uuid, request_id, admission_id), + FOREIGN KEY (tenant_uuid, owner_service) REFERENCES account_tenant_capacity_usage(tenant_uuid, owner_service), + CHECK ((execution_status = 'OWNER_EXECUTION_PENDING') = (owner_readback IS NULL)), + CHECK ((owner_readback IS NULL) = (owner_readback_digest IS NULL)), + CHECK ((state = 'FINALIZED') = (execution_status = 'COMMITTED')), + CHECK ((state = 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION') = (recovery_escalated_at IS NOT NULL)), + CHECK (state <> 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION' OR execution_status = 'OWNER_EXECUTION_PENDING'), + CHECK (state <> 'RELEASED' OR execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'), + CHECK ((recovery_owner IS NULL) = (recovery_claim_expires_at IS NULL)) +); + +CREATE TABLE account_tenant_capacity_attempt_history ( + tenant_uuid UUID NOT NULL, + request_id UUID NOT NULL, + admission_id UUID NOT NULL, + admission_attempt_id UUID NOT NULL UNIQUE, + capacity_rearm_fence BIGINT NOT NULL CHECK (capacity_rearm_fence > 0), + mutation_digest CHAR(64) NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + canonical_payload BYTEA NOT NULL CHECK (octet_length(canonical_payload) BETWEEN 1 AND 524288), + owner_readback BYTEA NOT NULL CHECK (octet_length(owner_readback) BETWEEN 1 AND 1048576), + PRIMARY KEY (tenant_uuid, request_id, admission_id, admission_attempt_id), + FOREIGN KEY (tenant_uuid, request_id, admission_id) REFERENCES account_tenant_capacity_reservations(tenant_uuid, request_id, admission_id) +); + +CREATE TABLE account_tenant_capacity_recovery_evidence ( + tenant_uuid UUID NOT NULL, + request_id UUID NOT NULL, + admission_id UUID NOT NULL, + admission_attempt_id UUID NOT NULL, + recovery_claim_fence BIGINT NOT NULL CHECK (recovery_claim_fence > 0), + recovery_policy_version VARCHAR(32) NOT NULL CHECK (recovery_policy_version = 'capacity-recovery/1'), + recovery_attempt_number INT NOT NULL CHECK (recovery_attempt_number BETWEEN 1 AND 12), + observed_at TIMESTAMPTZ NOT NULL, + outcome VARCHAR(64) NOT NULL CHECK (outcome IN ('INDETERMINATE', 'SOURCE_UNAVAILABLE', 'COMMITTED', 'NOT_EXECUTED_AFTER_AUTHORIZATION', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), + canonical_readback BYTEA CHECK (octet_length(canonical_readback) BETWEEN 1 AND 1048576), + readback_digest CHAR(64) CHECK (readback_digest ~ '^[0-9a-f]{64}$'), + PRIMARY KEY (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence), + UNIQUE (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_attempt_number), + FOREIGN KEY (tenant_uuid, request_id, admission_id) REFERENCES account_tenant_capacity_reservations(tenant_uuid, request_id, admission_id), + CHECK ((canonical_readback IS NULL) = (readback_digest IS NULL)), + CHECK (outcome NOT IN ('COMMITTED', 'NOT_EXECUTED_AFTER_AUTHORIZATION') OR canonical_readback IS NOT NULL) +); + +-- [jooq ignore start] +-- Only a genuinely new same-transaction fresh tenant completion can establish zero usage. +-- Replaying/importing a previously committed tenant cannot turn unknown usage into zero. +CREATE FUNCTION account_tenant_capacity_bootstrap_new_tenant() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE birth account_fresh_tenant_identity_associations%ROWTYPE; +BEGIN + IF OLD.status = 'IN_PROGRESS' AND NEW.status = 'COMMITTED' THEN + SELECT * INTO birth FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid FOR SHARE; + IF birth.capacity_birth_transaction IS DISTINCT FROM pg_current_xact_id()::TEXT THEN + RETURN NEW; + END IF; + IF birth.operation_id IS DISTINCT FROM NEW.creation_operation_id + OR birth.creation_request_id IS DISTINCT FROM NEW.creation_request_id + OR NEW.baseline_event_sequence <> 0 + OR NEW.gameplay_admission_allowed IS DISTINCT FROM FALSE + OR EXISTS (SELECT 1 FROM account_tenant_membership + WHERE tenant_uuid = NEW.tenant_uuid AND gameplay_admission_allowed IS TRUE) + OR EXISTS (SELECT 1 FROM account_tenant_capacity_usage WHERE tenant_uuid = NEW.tenant_uuid) THEN + RAISE EXCEPTION 'Fresh tenant capacity baseline is not demonstrably empty' USING ERRCODE = '23514'; + END IF; + INSERT INTO account_tenant_capacity_usage + (tenant_uuid, owner_service, bootstrap_request_id, creation_evidence_digest, held_units, used_units, usage_revision) + VALUES (NEW.tenant_uuid, 'game-session-service', NEW.request_id, birth.evidence_digest, 0, 0, 1), + (NEW.tenant_uuid, 'world-management-service', NEW.request_id, birth.evidence_digest, 0, 0, 1); + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_fresh_bootstrap AFTER UPDATE ON account_tenant_creation_bootstrap_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_bootstrap_new_tenant(); + +CREATE FUNCTION account_tenant_capacity_immutable_evaluation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Capacity evaluation and historical attempt evidence is immutable' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER account_tenant_capacity_evaluation_guard BEFORE UPDATE OR DELETE ON account_tenant_capacity_evaluations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_history_guard BEFORE UPDATE OR DELETE ON account_tenant_capacity_attempt_history + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_recovery_evidence_guard BEFORE UPDATE OR DELETE ON account_tenant_capacity_recovery_evidence + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); + +CREATE FUNCTION account_tenant_capacity_usage_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.held_units <> 0 OR NEW.used_units <> 0 OR NEW.usage_revision <> 1 OR NOT EXISTS ( + SELECT 1 FROM account_tenant_creation_bootstrap_operations bootstrap + JOIN account_fresh_tenant_identity_associations birth ON birth.canonical_tenant_id = bootstrap.tenant_uuid + WHERE bootstrap.request_id = NEW.bootstrap_request_id AND bootstrap.tenant_uuid = NEW.tenant_uuid + AND bootstrap.status = 'COMMITTED' AND bootstrap.gameplay_admission_allowed IS FALSE + AND bootstrap.baseline_event_sequence = 0 + AND bootstrap.creation_operation_id = birth.operation_id + AND birth.evidence_digest = NEW.creation_evidence_digest + AND birth.capacity_birth_transaction = pg_current_xact_id()::TEXT) THEN + RAISE EXCEPTION 'Capacity usage initialization requires same-transaction new-tenant bootstrap' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_usage_birth BEFORE INSERT ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_usage_insert_guard(); + +CREATE FUNCTION account_tenant_capacity_usage_update_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid OR NEW.owner_service IS DISTINCT FROM OLD.owner_service + OR NEW.bootstrap_request_id IS DISTINCT FROM OLD.bootstrap_request_id + OR NEW.creation_evidence_digest IS DISTINCT FROM OLD.creation_evidence_digest + OR NEW.usage_revision <> OLD.usage_revision + 1 THEN + RAISE EXCEPTION 'Capacity usage identity is immutable and revision must advance once' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_usage_revision BEFORE UPDATE ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_usage_update_guard(); + +CREATE FUNCTION account_tenant_capacity_reservation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_tenant_capacity_evaluations evaluation + WHERE evaluation.evaluation_identity = NEW.evaluation_identity + AND evaluation.tenant_uuid = NEW.tenant_uuid AND evaluation.caller_workload = NEW.caller_workload + AND evaluation.owner_service = NEW.owner_service) THEN + RAISE EXCEPTION 'Capacity reservation lacks its exact retained Account evaluation' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' OR NEW.admission_attempt_id IS DISTINCT FROM OLD.admission_attempt_id) + AND EXISTS (SELECT 1 FROM account_tenant_capacity_attempt_history WHERE admission_attempt_id = NEW.admission_attempt_id) THEN + RAISE EXCEPTION 'Capacity admission attempt identity must be fresh' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'RESERVED' OR NEW.execution_status <> 'OWNER_EXECUTION_PENDING' + OR NEW.capacity_rearm_fence <> 1 OR NEW.reservation_fence <> 1 + OR NEW.recovery_owner IS NOT NULL OR NEW.recovery_claim_fence <> 0 OR NEW.owner_readback IS NOT NULL + OR NEW.recovery_attempt_count <> 0 OR NEW.recovery_escalated_at IS NOT NULL THEN + RAISE EXCEPTION 'Capacity reservation must begin as the original pending attempt' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.admission_id IS DISTINCT FROM OLD.admission_id OR NEW.reservation_id IS DISTINCT FROM OLD.reservation_id + OR NEW.owner_service IS DISTINCT FROM OLD.owner_service OR NEW.caller_workload IS DISTINCT FROM OLD.caller_workload + OR NEW.capacity_delta IS DISTINCT FROM OLD.capacity_delta OR NEW.recovery_claim_fence < OLD.recovery_claim_fence + OR NEW.recovery_policy_version IS DISTINCT FROM OLD.recovery_policy_version THEN + RAISE EXCEPTION 'Capacity reservation identity and hold are immutable' USING ERRCODE = '23514'; + END IF; + IF NEW.recovery_owner IS DISTINCT FROM OLD.recovery_owner + OR NEW.recovery_claim_expires_at IS DISTINCT FROM OLD.recovery_claim_expires_at + OR NEW.recovery_claim_fence <> OLD.recovery_claim_fence THEN + IF NEW.recovery_claim_fence <> OLD.recovery_claim_fence + 1 OR NEW.recovery_owner IS NULL + OR NEW.recovery_claim_expires_at <= clock_timestamp() + OR (OLD.recovery_owner IS DISTINCT FROM NEW.recovery_owner + AND OLD.recovery_claim_expires_at > clock_timestamp()) THEN + RAISE EXCEPTION 'Capacity recovery claim must monotonically fence its exact current owner' USING ERRCODE = '23514'; + END IF; + END IF; + IF NEW.admission_attempt_id IS DISTINCT FROM OLD.admission_attempt_id THEN + IF OLD.state <> 'RESERVED' OR OLD.execution_status <> 'NOT_EXECUTED_AFTER_AUTHORIZATION' + OR OLD.owner_readback IS NULL OR OLD.recovery_owner IS NULL + OR OLD.recovery_claim_expires_at <= clock_timestamp() + OR NEW.recovery_owner IS DISTINCT FROM OLD.recovery_owner + OR NEW.recovery_claim_fence <> OLD.recovery_claim_fence + OR NEW.capacity_rearm_fence <> OLD.capacity_rearm_fence + 1 + OR NEW.reservation_fence <> OLD.reservation_fence + 1 + OR NEW.state <> 'RESERVED' OR NEW.execution_status <> 'OWNER_EXECUTION_PENDING' + OR NEW.recovery_attempt_count <> 0 OR NEW.recovery_escalated_at IS NOT NULL + OR NEW.owner_readback IS NOT NULL OR NEW.owner_readback_digest IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM account_tenant_capacity_attempt_history history + WHERE history.tenant_uuid = OLD.tenant_uuid AND history.request_id = OLD.request_id + AND history.admission_id = OLD.admission_id AND history.admission_attempt_id = OLD.admission_attempt_id + AND history.capacity_rearm_fence = OLD.capacity_rearm_fence + AND history.mutation_digest = OLD.mutation_digest AND history.canonical_payload = OLD.canonical_payload + AND history.owner_readback = OLD.owner_readback) THEN + RAISE EXCEPTION 'Capacity rearm requires exact durable terminal no-commit and current recovery claim' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.capacity_rearm_fence <> OLD.capacity_rearm_fence + OR NEW.mutation_digest IS DISTINCT FROM OLD.mutation_digest OR NEW.canonical_payload IS DISTINCT FROM OLD.canonical_payload + OR NEW.evaluation_identity IS DISTINCT FROM OLD.evaluation_identity OR NEW.expires_at IS DISTINCT FROM OLD.expires_at + OR NEW.reconcile_deadline IS DISTINCT FROM OLD.reconcile_deadline THEN + RAISE EXCEPTION 'Changed capacity attempt is an idempotency conflict' USING ERRCODE = '23514'; + END IF; + IF OLD.state <> 'RESERVED' THEN + IF NEW IS DISTINCT FROM OLD THEN + RAISE EXCEPTION 'Terminal capacity result is immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NEW.recovery_attempt_count <> OLD.recovery_attempt_count THEN + IF NEW.recovery_attempt_count <> OLD.recovery_attempt_count + 1 + OR NEW.recovery_owner IS NULL OR NEW.recovery_claim_expires_at <= clock_timestamp() + OR NOT EXISTS (SELECT 1 FROM account_tenant_capacity_recovery_evidence evidence + WHERE evidence.tenant_uuid = OLD.tenant_uuid AND evidence.request_id = OLD.request_id + AND evidence.admission_id = OLD.admission_id AND evidence.admission_attempt_id = OLD.admission_attempt_id + AND evidence.recovery_claim_fence = NEW.recovery_claim_fence + AND evidence.recovery_attempt_number = NEW.recovery_attempt_count) THEN + RAISE EXCEPTION 'Capacity recovery must retain each bounded observation under its current claim' USING ERRCODE = '23514'; + END IF; + END IF; + IF NEW.state = 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION' THEN + IF OLD.execution_status <> 'OWNER_EXECUTION_PENDING' + OR (NEW.recovery_attempt_count < 12 AND clock_timestamp() < OLD.reconcile_deadline) + OR NEW.recovery_escalated_at IS NULL + OR NEW.next_reconcile_at IS NOT NULL THEN + RAISE EXCEPTION 'Capacity quarantine requires exhausted bounded recovery and preserves the original hold' USING ERRCODE = '23514'; + END IF; + END IF; + IF OLD.execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION' + AND (NEW.execution_status <> OLD.execution_status OR NEW.owner_readback IS DISTINCT FROM OLD.owner_readback + OR NEW.owner_readback_digest IS DISTINCT FROM OLD.owner_readback_digest) THEN + RAISE EXCEPTION 'Terminal capacity no-commit evidence cannot be replaced' USING ERRCODE = '23514'; + END IF; + IF NEW.state <> OLD.state OR NEW.execution_status <> OLD.execution_status THEN + IF NEW.recovery_owner IS NULL OR NEW.recovery_claim_fence = 0 + OR NEW.recovery_claim_expires_at <= clock_timestamp() + OR (NEW.state <> 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION' AND NEW.owner_readback IS NULL) THEN + RAISE EXCEPTION 'Only current Account recovery claim may transition capacity evidence' USING ERRCODE = '23514'; + END IF; + END IF; + IF (NEW.state = 'RELEASED' AND NEW.reservation_fence <> OLD.reservation_fence + 1) + OR (NEW.state <> 'RELEASED' AND NEW.reservation_fence <> OLD.reservation_fence) THEN + RAISE EXCEPTION 'Capacity release must durably fence the original reservation' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_tenant_capacity_reservation_fences BEFORE INSERT OR UPDATE ON account_tenant_capacity_reservations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_reservation_guard(); + +-- The complete durable reservation inventory, not a local issuer counter, owns usage. +CREATE FUNCTION account_tenant_capacity_exact_usage() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE held NUMERIC; used NUMERIC; actual account_tenant_capacity_usage%ROWTYPE; +BEGIN + SELECT * INTO actual FROM account_tenant_capacity_usage + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service FOR UPDATE; + SELECT COALESCE(sum(capacity_delta) FILTER (WHERE state IN ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0), + COALESCE(sum(capacity_delta) FILTER (WHERE state = 'FINALIZED'), 0) + INTO held, used FROM account_tenant_capacity_reservations + WHERE tenant_uuid = NEW.tenant_uuid AND owner_service = NEW.owner_service; + IF actual.tenant_uuid IS NULL OR held <> actual.held_units OR used <> actual.used_units THEN + RAISE EXCEPTION 'Capacity usage differs from its complete durable reservation inventory' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_tenant_capacity_usage_complete AFTER INSERT OR UPDATE ON account_tenant_capacity_usage + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_exact_usage(); +CREATE CONSTRAINT TRIGGER account_tenant_capacity_reservation_complete AFTER INSERT OR UPDATE ON account_tenant_capacity_reservations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_exact_usage(); +CREATE TRIGGER account_tenant_capacity_usage_no_delete BEFORE DELETE ON account_tenant_capacity_usage + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_reservation_no_delete BEFORE DELETE ON account_tenant_capacity_reservations + FOR EACH ROW EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_usage_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_usage + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_reservation_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_reservations + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_evaluation_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_evaluations + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_history_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_attempt_history + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +CREATE TRIGGER account_tenant_capacity_recovery_evidence_no_truncate BEFORE TRUNCATE ON account_tenant_capacity_recovery_evidence + FOR EACH STATEMENT EXECUTE FUNCTION account_tenant_capacity_immutable_evaluation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java new file mode 100644 index 0000000000..2e71e3b8ac --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java @@ -0,0 +1,332 @@ +package net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mockingDetails; + +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.stub.MetadataUtils; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; +import net.firedevops.firemud.accountservice.client.EntityManagementClient; +import net.firedevops.firemud.accountservice.client.GameSessionClient; +import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.security.AccountPlayerAdmissionEntitlementWorkloadGuard; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker; +import net.firedevops.firemud.accountservice.service.impl.AccountGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.impl.AccountTenantCapacityGrpcService; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.test.TlsTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.context.ApplicationContext; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Full default Account application, real database/Redis and ordinary REQUIRE-mTLS listener. Empty + * capacity cohorts prove no durable creation only. Populated-family preservation, + * retention/erasure, production PKI, admission and owner activation are not qualified here. + */ +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = AccountServiceApplication.class, + webEnvironment = WebEnvironment.RANDOM_PORT, + properties = { + "spring.config.import=classpath:account-main-application.yml", + "spring.grpc.server.port=0", + "spring.grpc.server.ssl.enabled=true", + "spring.grpc.server.ssl.bundle=firemud-grpc", + "spring.grpc.server.ssl.client-auth=REQUIRE", + "firemud.grpc.workload-namespace=test", + "firemud.mail.verification-url=https://account.test/verify-email?token=%s" + }) +class AccountRuntimeEntitlementNoWriteIntegrationTest { + private static final String METHOD = "account.v1.AccountService/GetTenantEntitlementsForRuntime"; + private static final List CAPACITY_TABLES = + List.of( + "account_tenant_capacity_evaluations", + "account_tenant_capacity_usage", + "account_tenant_capacity_reservations", + "account_tenant_capacity_attempt_history", + "account_tenant_capacity_recovery_evidence"); + private static final GetTenantEntitlementsForRuntimeRequest REQUEST = + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("default-runtime-entitlement-no-write") + .build(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private static Path tlsDirectory; + private static LoopbackMtlsTestPki.Pki pki; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) throws Exception { + PostgresBackedServiceTestSupport.registerPostgresService(registry, postgres, "account_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + tlsDirectory = Files.createTempDirectory("account-runtime-no-write-mtls-"); + pki = + LoopbackMtlsTestPki.create( + tlsDirectory, + "Account default runtime no-write CA", + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", true), + new IdentitySpec( + "game-session", "spiffe://firemud/ns/test/sa/game-session-service", false), + new IdentitySpec( + "world", "spiffe://firemud/ns/test/sa/world-management-service", false), + new IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/entity-management-service", false), + new IdentitySpec( + "cross-namespace", "spiffe://firemud/ns/other/sa/game-session-service", false)); + var server = pki.clientProperties(tlsDirectory, pki.identity("account")); + registry.add("FIREMUD_GRPC_CERT_CHAIN_PATH", server::getCertChain); + registry.add("FIREMUD_GRPC_PRIVATE_KEY_PATH", server::getPrivateKey); + registry.add("FIREMUD_GRPC_CA_CERT_PATH", server::getCaCert); + } + + @Autowired private ApplicationContext context; + @Autowired private DataSource dataSource; + @Autowired private DSLContext dsl; + @Autowired private AccountService accountService; + @Autowired private AccountServiceImpl accountFacade; + @Autowired private AccountGrpcService accountGrpcService; + @Autowired private GrpcServerLifecycle listener; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private JavaMailSender mailSender; + + @BeforeEach + void assertActualDefaultRegistration() { + assertThat(listener.isRunning()).isTrue(); + assertThat(listener.getPort()).isPositive(); + assertThat(listener.getFactory()).isSameAs(context.getBean(GrpcServerFactory.class)); + assertThat(listener.getFactory()).isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(accountService).isSameAs(accountFacade); + for (Object actual : + List.of( + accountService, + accountGrpcService, + dataSource, + dsl, + context.getBean(GrpcPeerIdentityInterceptor.class))) { + assertThat(mockingDetails(actual).isMock()).isFalse(); + } + assertThat(context.getBeansOfType(GrpcPeerIdentityInterceptor.class)).hasSize(1); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(METHOD) + .doesNotContain("account.v1.AccountService/*"); + assertThat(context.getBeansOfType(AccountPlayerAdmissionEntitlementOwner.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountPlayerAdmissionEntitlementGrpcService.class)) + .isEmpty(); + assertThat(context.getBeansOfType(AccountPlayerAdmissionEntitlementWorkloadGuard.class)) + .isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityRepository.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityOwner.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityGrpcService.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityRecoveryWorker.class)).isEmpty(); + assertThat(context.getBeansOfType(AccountTenantCapacityWorkloadGuard.class)).isEmpty(); + assertThat(dsl.fetchValue("SELECT current_schema()", String.class)) + .isEqualTo("account_service"); + } + + @ParameterizedTest + @ValueSource(strings = {"game-session", "world"}) + void authorizedNumericRefusalAndExactRetryCreateNoCapacityRows(String identity) throws Exception { + Map before = emptyCapacityImages(); + ManagedChannel channel = channel(identity); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + for (int attempt = 0; attempt < 2; attempt++) { + assertRefusal( + stub.withDeadlineAfter(5, TimeUnit.SECONDS).getTenantEntitlementsForRuntime(REQUEST), + "ENTITLEMENT_UNAVAILABLE"); + assertThat(capacityImages()).isEqualTo(before); + } + } finally { + close(channel); + } + } + + @ParameterizedTest + @ValueSource(strings = {"wrong-service", "cross-namespace"}) + void deniedCertificateAndSpoofedMetadataCreateNoCapacityRows(String identity) throws Exception { + Map before = emptyCapacityImages(); + ManagedChannel channel = channel(identity); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + assertRefusal( + stub.withDeadlineAfter(5, TimeUnit.SECONDS).getTenantEntitlementsForRuntime(REQUEST), + "PERMISSION_DENIED"); + assertThat(capacityImages()).isEqualTo(before); + assertRefusal( + stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(fakePeer())) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getTenantEntitlementsForRuntime(REQUEST), + "PERMISSION_DENIED"); + assertThat(capacityImages()).isEqualTo(before); + } finally { + close(channel); + } + } + + @Test + void missingClientCertificateIsRefusedByTlsWithoutCapacityCreation() throws Exception { + Map before = emptyCapacityImages(); + ManagedChannel channel = channel(null); + try { + assertThatThrownBy( + () -> + AccountServiceGrpc.newBlockingStub(channel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(fakePeer())) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getTenantEntitlementsForRuntime(REQUEST)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + assertThat(capacityImages()).isEqualTo(before); + } finally { + close(channel); + } + } + + private static void assertRefusal(GetTenantEntitlementsForRuntimeResponse response, String code) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo(code); + assertThat(response.toBuilder().clearError().build()) + .isEqualTo(GetTenantEntitlementsForRuntimeResponse.getDefaultInstance()); + } + + private static Metadata fakePeer() { + Metadata headers = new Metadata(); + String claim = "spiffe://firemud/ns/test/sa/game-session-service"; + for (String name : + List.of("x-firemud-peer-identity", "x-spiffe-id", "x-forwarded-client-cert")) { + headers.put(Metadata.Key.of(name, Metadata.ASCII_STRING_MARSHALLER), claim); + } + return headers; + } + + private ManagedChannel channel(String identity) throws Exception { + var tls = GrpcSslContexts.forClient().trustManager(pki.trustManagerFactory()); + if (identity != null) tls.keyManager(pki.keyManagerFactory(pki.identity(identity))); + return NettyChannelBuilder.forAddress("localhost", listener.getPort()) + .sslContext(tls.build()) + .build(); + } + + private static void close(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private Map emptyCapacityImages() throws Exception { + Map images = capacityImages(); + assertThat(images).hasSize(5); + images.forEach( + (table, image) -> { + assertThat(image.count()).as(table).isZero(); + assertThat(image.rows()).as(table).isEmpty(); + }); + return images; + } + + private Map capacityImages() throws Exception { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + Map images = new LinkedHashMap<>(); + // Fresh autocommit connections observe committed postimages, never a shared test rollback. + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.getAutoCommit()).isTrue(); + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_READ_COMMITTED); + assertThat(connection.getMetaData().getDatabaseProductName()).isEqualTo("PostgreSQL"); + assertThat(connection.getCatalog()).isEqualTo(postgres.getDatabaseName()); + assertThat(connection.getSchema()).isEqualTo("account_service"); + for (String table : CAPACITY_TABLES) { + long count; + try (var statement = connection.createStatement(); + var result = statement.executeQuery("SELECT COUNT(*) FROM account_service." + table)) { + assertThat(result.next()).isTrue(); + count = result.getLong(1); + } + List rows = new ArrayList<>(); + try (var statement = connection.createStatement(); + var result = + statement.executeQuery( + "SELECT to_jsonb(t)::text, t.xmin::text FROM account_service." + + table + + " t ORDER BY 1, 2")) { + while (result.next()) rows.add(new RowImage(result.getString(1), result.getString(2))); + } + assertThat(rows).hasSize(Math.toIntExact(count)); + images.put(table, new TableImage(count, List.copyOf(rows))); + } + } + return Map.copyOf(images); + } + + @AfterAll + static void removeOwnedTlsFixture() throws Exception { + if (tlsDirectory != null) { + try (var files = Files.walk(tlsDirectory)) { + for (Path file : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(file); + } + } + } + + private record RowImage(String json, String xmin) {} + + private record TableImage(long count, List rows) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index 79c1169e9b..9ca9d6efb5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -284,7 +284,7 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE } @Test - void receivingUpgradeFromParent1036Through1038PreservesCanonicalRowsAndHistory() { + void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() { String schema = createSchema("canonical_join_scope_"); DriverManagerDataSource dataSource = postgres.dataSource(schema); Flyway parent = accountFlyway(dataSource, schema, "1036"); @@ -357,24 +357,28 @@ void receivingUpgradeFromParent1036Through1038PreservesCanonicalRowsAndHistory() "V1037__canonical_join_failure_and_attempt_diagnostics.sql", "V1038__canonical_join_existing_membership_terminal.sql"); - Flyway current = accountFlyway(dataSource, schema, "1038"); + Flyway current = accountFlyway(dataSource, schema, "1040"); current.migrate(); current.validate(); assertThat(current.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1038")); + .isEqualTo(MigrationVersion.fromVersion("1040")); List> upgradedHistory = flywayHistory(setupDsl); - assertThat(upgradedHistory).hasSize(parentHistory.size() + 2); + assertThat(upgradedHistory).hasSize(parentHistory.size() + 4); assertThat(upgradedHistory.subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); List> addedHistory = upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); - assertThat(addedHistory).extracting(row -> row.get("version")).containsExactly("1037", "1038"); + assertThat(addedHistory) + .extracting(row -> row.get("version")) + .containsExactly("1037", "1038", "1039", "1040"); assertThat(addedHistory) .extracting(row -> row.get("script")) .containsExactly( "V1037__canonical_join_failure_and_attempt_diagnostics.sql", - "V1038__canonical_join_existing_membership_terminal.sql"); + "V1038__canonical_join_existing_membership_terminal.sql", + "V1039__hosting_unclaimed_wallet_settlement.sql", + "V1040__account_tenant_capacity_owner.sql"); assertThat(addedHistory) .allSatisfy( row -> { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..7f67a85b2e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -0,0 +1,219 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** Real forward migration with retained tenant provenance. No existing usage is guessed. */ +class AccountTenantCapacityMigrationPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @Test + void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { + String schema = "capacity_migration_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1038") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var repository = new FreshTenantIdentityAssociationRepository(dsl, "prod"); + var operations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var existing = source(); + var historical = + Objects.requireNonNull( + transaction.execute( + status -> { + repository.importVerified(existing); + return claimBootstrap( + operations, new AccountRepository(dsl).save(creator()), existing); + })); + assertThat(historical.status()).isEqualTo("IN_PROGRESS"); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var retained = transaction.execute(status -> repository.read(existing.canonicalTenantId())); + assertThat(retained).contains(existing); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT capacity_birth_transaction FROM account_fresh_tenant_identity_associations WHERE canonical_tenant_id = ?", + existing.canonicalTenantId())) + .get("capacity_birth_transaction")) + .isNull(); + var completed = + Objects.requireNonNull( + transaction.execute( + status -> { + var operation = operations.findForUpdate(historical.requestId()).orElseThrow(); + assertThat(operation.status()).isEqualTo("IN_PROGRESS"); + assertThat(operation.creationOperationId()).isEqualTo(existing.operationId()); + assertThat(operation.requestPayload()).isEqualTo(historical.requestPayload()); + return operations.complete(operation.requestId(), completion(operation)); + })); + assertThat(completed.status()).isEqualTo("COMMITTED"); + assertThat(completed.tenantUuid()).isEqualTo(existing.canonicalTenantId()); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); + var later = source(); + transaction.executeWithoutResult(status -> repository.importVerified(later)); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT capacity_birth_transaction FROM account_fresh_tenant_identity_associations WHERE canonical_tenant_id = ?", + later.canonicalTenantId())) + .get("capacity_birth_transaction")) + .isNotNull(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static Account creator() { + String suffix = UUID.randomUUID().toString().replace("-", ""); + var account = new Account(); + account.setUsername("capacity-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("test-only-password-hash"); + account.setRole("player"); + return account; + } + + private static StoredOperation claimBootstrap( + AccountTenantCreationBootstrapOperationRepository operations, + Account creator, + FreshTenantCreationEvidence creation) { + UUID accountId = creator.getAccountUuid(); + UUID authorizationId = UUID.randomUUID(); + String authorizationDigest = + AccountTenantCreationBootstrapDigest.sha256( + "fixture authorization".getBytes(StandardCharsets.UTF_8)); + var evidence = + new FreshTenantCreatorEvidence( + 1, + creation, + accountId, + authorizationId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, accountId, authorizationId, authorizationDigest)); + byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + byte[] sourcePayload = "fixture source snapshot".getBytes(StandardCharsets.UTF_8); + byte[] requestPayload = + AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); + var claim = + operations.claim( + evidence, + creatorPayload, + sourcePayload, + AccountTenantCreationBootstrapDigest.sha256(sourcePayload), + requestPayload, + AccountTenantCreationBootstrapDigest.sha256(requestPayload), + 1, + 1); + assertThat(claim.claimed()).isTrue(); + return claim.operation(); + } + + private static Completion completion(StoredOperation operation) { + // Controlled completion receipts exercise the real storage owner's guarded transition. + byte[] event = "fixture membership event".getBytes(StandardCharsets.UTF_8); + byte[] audit = "fixture bootstrap audit".getBytes(StandardCharsets.UTF_8); + byte[] result = "fixture bootstrap result".getBytes(StandardCharsets.UTF_8); + return new Completion( + 1, + operation.baselineMembershipVersion() + 1, + operation.baselineMembershipAuthorityGeneration(), + "ACTIVE", + false, + "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + operation.initiatingAccountUuid() + + "/" + + operation.tenantUuid(), + operation.requestId().toString(), + 1, + "fixture-membership-event", + AccountTenantCreationBootstrapDigest.sha256(event), + false, + event, + UUID.randomUUID(), + "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", + Instant.now().truncatedTo(ChronoUnit.MICROS), + AccountTenantCreationBootstrapDigest.sha256(audit), + audit, + result, + AccountTenantCreationBootstrapDigest.sha256(result)); + } + + private static FreshTenantCreationEvidence source() { + UUID request = UUID.randomUUID(), operation = UUID.randomUUID(), tenant = UUID.randomUUID(); + String slug = "capacity-" + UUID.randomUUID().toString().substring(0, 8); + String digest = GameTenantCreationDigest.requestDigest("prod", request, slug, "Capacity", null); + long row = Math.abs((long) tenant.hashCode()) + 1; + return new FreshTenantCreationEvidence( + 1, + "prod", + request, + operation, + digest, + tenant, + row, + slug, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", request, operation, digest, tenant, row, slug, "NEW_GAME_ROW")); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 6c0028a33e..32b82b90e3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -61,6 +61,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -331,12 +332,26 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { .containsExactlyEntriesOf(Map.of(f.tenantId.toString(), "2")); assertThat(value.membershipSource().membershipAuthorityGeneration()).isEqualTo("1"); assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); - assertThat(value.verifiedConnectScopeTokenHash()) - .isEqualTo(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + var retained = + f.dsl.fetchOne( + "SELECT canonical_evidence, snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + value.fields().get("evaluationIdentity")); + assertThat(retained).isNotNull(); + byte[] retainedEvidence = retained.get("canonical_evidence", byte[].class); assertThat( - new String(value.canonicalBytes(), StandardCharsets.UTF_8) - .contains(f.scope.connectScopeId())) + new String(retainedEvidence, StandardCharsets.UTF_8).contains(f.scope.connectScopeId())) .isFalse(); + assertThat(retainedEvidence).containsExactly(value.canonicalBytes()); + var decoded = RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(retainedEvidence); + assertThat(decoded.verifiedConnectScopeTokenHash()) + .isEqualTo(AccountJoinDigest.tokenHash(f.scope.connectScopeId())); + assertThat(decoded.fields()).doesNotContainKey("verifiedConnectScopeId"); + assertThat(retained.get("snapshot_identity", String.class)) + .isEqualTo(value.fields().get("snapshotIdentity")); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + // This old fixture tenant was imported before creator completion. Eligibility evaluation + // never invents an empty capacity baseline for it. + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); var binding = (Map) value.fields().get("target"); assertThat(binding.get("realmId")).isEqualTo(f.scope.realmId().toString()); assertThat(binding.get("playableStateNamespaceId")) @@ -419,6 +434,7 @@ public void beforeCommit(boolean readOnly) { assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) .hasMessageContaining("controlled final source commit refusal"); assertThat(competingWriterRefused.get()).isTrue(); + assertThat(f.dsl.fetchCount(DSL.table("account_tenant_capacity_evaluations"))).isZero(); var unlocked = f.transaction.execute( status -> f.accounts.findByAccountUuidForUpdate(f.account.getAccountUuid())); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 0d552450fc..0def873ad4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -25,6 +25,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; @@ -57,11 +58,13 @@ import net.firedevops.firemud.accountservice.repository.RetainedSubscriptionEvidenceRepository; import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountTenantCreationAdmissionRepository.Admitted; import net.firedevops.firemud.accountservice.service.session.AccountTenantCreationIntentRepository.OriginalIntent; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; @@ -360,6 +363,559 @@ void fullStoredOwnerCompletionCommitsAllReceiptsAndExactReplayWithoutReconsumpti assertThat(c.dsl.fetchCount(DSL.table("account_audit_outbox"))).isEqualTo(2); } + @Test + void capacityOwnerPersistenceFinalizesOneOriginalReservationAndUsageExactlyOnce() { + var f = capacityPersistenceFixture(); + var calls = new java.util.concurrent.atomic.AtomicInteger(); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + calls.incrementAndGet(); + return capacityObservation( + request, + reservation, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.COMMITTED); + }, + java.time.Clock.systemUTC()); + var result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.FINALIZED); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(1); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("used_units", Long.class)) + .isEqualTo(17); + } + + @Test + void overlappingRecoveryCallsCannotInvalidateTheSameWorkersLiveClaim() throws Exception { + var f = capacityPersistenceFixture(); + var next = + new TenantCapacityAdmission.Request( + f.request.identity(), + UUID.randomUUID(), + f.request.capacityRearmFence() + 1, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(); + var readStarted = new CountDownLatch(1); + var resumeRead = new CountDownLatch(1); + var calls = new AtomicInteger(); + var secondWorkerCalls = new AtomicInteger(); + var recoveryClock = Clock.fixed(f.request.evidence().evaluatedAt(), ZoneOffset.UTC); + var recovery = + new AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + if (calls.incrementAndGet() == 1) { + readStarted.countDown(); + try { + assertThat(resumeRead.await(10, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError("Interrupted while waiting to resume read", interrupted); + } + } + return capacityObservation( + request, reservation, AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED); + }, + recoveryClock); + var secondWorker = + new AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + secondWorkerCalls.incrementAndGet(); + return capacityObservation( + request, reservation, AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED); + }, + recoveryClock); + var action = AccountTenantCapacityRecoveryWorker.NoCommitAction.RELEASE; + try (var executor = Executors.newSingleThreadExecutor()) { + var pending = executor.submit(() -> recovery.reconcile(f.request, action)); + try { + assertThat(readStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> recovery.reconcile(f.request, action)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> recovery.rearm(f.request, next)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> secondWorker.reconcile(f.request, action)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThatThrownBy(() -> secondWorker.rearm(f.request, next)) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + assertThat(calls).hasValue(1); + assertThat(secondWorkerCalls).hasValue(0); + } finally { + resumeRead.countDown(); + } + var result = pending.get(10, TimeUnit.SECONDS); + assertThat(result.state()).isEqualTo(TenantCapacityAdmission.State.FINALIZED); + assertThat(recovery.reconcile(f.request, action)).isEqualTo(result); + assertThat(calls).hasValue(1); + assertThat(secondWorkerCalls).hasValue(0); + } + } + + @Test + void capacityIndeterminateReadbackCannotReleaseAndTerminalNoCommitReleasesSameHold() { + var f = capacityPersistenceFixture(); + var disposition = + new java.util.concurrent.atomic.AtomicReference<>( + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.INDETERMINATE); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> + capacityObservation(request, reservation, disposition.get()), + java.time.Clock.systemUTC()); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(f.initial); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isEqualTo(17); + // This is controlled source/claim proof, not production selected-owner CAS qualification. + disposition.set( + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.NOT_EXECUTED_AFTER_AUTHORIZATION); + var released = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(released.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.RELEASED); + assertThat(released.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(released.reservationFence()).isEqualTo(f.initial.reservationFence() + 1); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(released); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isZero(); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))) + .isEqualTo(1); + } + + @Test + void capacityChangedAttemptConflictsWithoutUsageMutationAndIncompleteLedgerCannotBeSeeded() { + var f = capacityPersistenceFixture(); + var changed = + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( + f.request.identity(), + UUID.randomUUID(), + f.request.capacityRearmFence(), + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(); + assertThatThrownBy( + () -> + f.context.transaction.execute( + status -> f.repository.exact(changed, f.repository.find(changed.identity())))) + .hasMessage("IDEMPOTENCY_CONFLICT"); + assertThatThrownBy( + () -> + f.context.transaction.executeWithoutResult( + status -> + f.context.dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units + 1, usage_revision = usage_revision + 1 WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()))) + .isInstanceOf(RuntimeException.class); + assertThat( + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId())) + .get("held_units", Long.class)) + .isEqualTo(17); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))) + .isEqualTo(1); + } + + @Test + void boundedIndeterminateCapacityRecoveryQuarantinesTheOriginalCompleteHold() { + var f = capacityPersistenceFixture(); + var calls = new java.util.concurrent.atomic.AtomicInteger(); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + calls.incrementAndGet(); + throw new IllegalStateException("Controlled selected-owner unavailability"); + }, + java.time.Clock.systemUTC()); + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result result = + f.initial; + for (int attempt = 0; attempt < 12; attempt++) { + result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.reservationFence()).isEqualTo(f.initial.reservationFence()); + } + assertThat(result.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State + .QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); + assertThat(calls).hasValue(12); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(12); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_recovery_evidence"))) + .isEqualTo(12); + var usage = + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()), + "Capacity usage row is absent"); + assertThat(usage.get("held_units", Long.class)).isEqualTo(17); + assertThat(usage.get("used_units", Long.class)).isZero(); + var retained = + Objects.requireNonNull( + f.context.dsl.fetchOne( + "SELECT recovery_attempt_count, recovery_escalated_at, next_reconcile_at FROM account_tenant_capacity_reservations WHERE reservation_id = ?", + result.reservationId()), + "Capacity reservation row is absent"); + assertThat(retained.get("recovery_attempt_count", Integer.class)).isEqualTo(12); + assertThat(retained.get("recovery_escalated_at")).isNotNull(); + assertThat(retained.get("next_reconcile_at")).isNull(); + } + + @Test + void firstRecoveryAfterDeadlineFinalizesAnExactPositiveOnce() { + var f = capacityPersistenceFixture(true); + assertThat(Instant.now()).isAfter(f.initial.expiresAt().plusSeconds(60)); + var calls = new java.util.concurrent.atomic.AtomicInteger(); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + calls.incrementAndGet(); + assertThat(deadline).isAfter(Instant.now()); + assertThat(deadline).isBeforeOrEqualTo(Instant.now().plusSeconds(5)); + return capacityObservation( + request, + reservation, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition.COMMITTED); + }, + java.time.Clock.systemUTC()); + var result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.state()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State.FINALIZED); + assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.reservationFence()).isEqualTo(f.initial.reservationFence()); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(1); + var usage = + f.context.dsl.fetchSingle( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()); + assertThat(usage.get("held_units", Long.class)).isZero(); + assertThat(usage.get("used_units", Long.class)).isEqualTo(17); + assertThat(f.context.dsl.fetchCount(DSL.table("account_tenant_capacity_recovery_evidence"))) + .isEqualTo(1); + } + + @Test + void firstLateNegativeMalformedUnavailableAndOverBudgetReadsQuarantineWithoutReleasing() { + for (String outcome : + List.of("negative", "indeterminate", "malformed", "unavailable", "late")) { + var f = capacityPersistenceFixture(true); + assertThat(Instant.now()).isAfter(f.initial.expiresAt().plusSeconds(60)); + var now = new java.util.concurrent.atomic.AtomicReference<>(Instant.now()); + var recoveryClock = + new java.time.Clock() { + @Override + public java.time.ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public java.time.Clock withZone(java.time.ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now.get(); + } + }; + var calls = new java.util.concurrent.atomic.AtomicInteger(); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, + f.context.dsl, + (request, reservation, deadline) -> { + calls.incrementAndGet(); + assertThat(deadline).isEqualTo(now.get().plusSeconds(5)); + if (outcome.equals("unavailable")) + throw new IllegalStateException("Controlled source unavailable"); + if (outcome.equals("late")) now.set(deadline); + var disposition = + outcome.equals("negative") + ? net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Disposition + .NOT_EXECUTED_AFTER_AUTHORIZATION + : outcome.equals("indeterminate") + ? net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Disposition.INDETERMINATE + : net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Disposition.COMMITTED; + var observation = capacityObservation(request, reservation, disposition); + if (!outcome.equals("malformed")) return observation; + return new net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.Observation( + "spiffe://firemud/ns/prod/sa/wrong-owner", + observation.reservation(), + observation.canonicalAttemptPayload(), + observation.disposition(), + observation.proofId(), + observation.currentOwnerFence(), + observation.authoritativeStateDigest(), + observation.canonicalOwnerReadback()); + }, + recoveryClock); + var result = + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE); + assertThat(result.state()) + .as(outcome) + .isEqualTo( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State + .QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION); + assertThat(result.reservationId()).isEqualTo(f.initial.reservationId()); + assertThat(result.reservationFence()).isEqualTo(f.initial.reservationFence()); + assertThat( + recovery.reconcile( + f.request, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RELEASE)) + .isEqualTo(result); + assertThat(calls).hasValue(1); + var usage = + f.context.dsl.fetchSingle( + "SELECT held_units, used_units FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()); + assertThat(usage.get("held_units", Long.class)).isEqualTo(17); + assertThat(usage.get("used_units", Long.class)).isZero(); + var retained = + f.context.dsl.fetchSingle( + "SELECT outcome, canonical_readback FROM account_tenant_capacity_recovery_evidence"); + assertThat(retained.get("outcome", String.class)) + .isEqualTo("QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION"); + assertThat(retained.get("canonical_readback")).isNull(); + } + } + + /** Genuine same-transaction fresh creation; controlled entitlement and owner execution source. */ + private static CapacityPersistenceFixture capacityPersistenceFixture() { + return capacityPersistenceFixture(false); + } + + private static CapacityPersistenceFixture capacityPersistenceFixture(boolean expired) { + StorageContext c = storageContext(); + var fixture = storageFixture(c); + var assembled = assembleStoredOwner(c, fixture, new AccountAuditOutboxRepository(c.dsl)); + assembled.owner.complete( + fixture.intent.creationOperationId(), + assembled.terminal, + assembled.environment, + assembled.recent); + UUID tenant = assembled.terminal.evidence().receipt().orElseThrow().canonicalTenantId(); + var base = + net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.worldRequest( + 17L); + // A retained historical reservation is inserted through the same controlled source fixture. + // No live producer accepts stale evidence, and no immutable row or database clock is changed. + var now = + java.time.Instant.now() + .minusSeconds(expired ? 120 : 0) + .truncatedTo(java.time.temporal.ChronoUnit.MICROS); + String json = + new String(base.evidence().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) + .replace(base.identity().tenantId().toString(), tenant.toString()) + .replace( + net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture.NOW + .toString(), + now.toString()); + var evidence = + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence.parse( + json.getBytes(java.nio.charset.StandardCharsets.UTF_8), + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner + .WORLD_MANAGEMENT); + var context = + (net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext) + base.context(); + var request = + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request( + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity( + tenant, base.identity().requestId(), base.identity().admissionId()), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .WorldContext( + tenant, + context.operationId(), + context.lifecycleId(), + context.gameInstanceId(), + context.ownerId(), + context.ownerFence()), + base.operation(), + base.priorShape(), + base.requestedShape(), + evidence, + base.capacityDelta(), + null) + .withDigest(); + var repository = + new net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository(c.dsl); + var initial = + c.transaction.execute( + status -> { + // Controlled fixture evidence deliberately bypasses the absent World producer. + // Production + // has no route to perform this insertion and World admission remains unavailable. + c.dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", + evidence.evaluationIdentity(), + evidence.snapshotIdentity(), + tenant, + evidence.callerWorkload(), + evidence.owner().service(), + evidence.canonicalBytes(), + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository + .at(evidence.evaluatedAt()), + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository + .at(evidence.expiresAt())); + return repository.create( + request, + evidence.expiresAt(), + Clock.fixed(evidence.evaluatedAt(), ZoneOffset.UTC)); + }); + var owner = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner( + c.dsl, + c.accounts, + mock( + net.firedevops.firemud.accountservice.repository + .AccountCanonicalRuntimeMembershipSnapshotRepository.class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountGameplayDelegationIssuanceRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + .class), + c.manager, + java.time.Clock.systemUTC(), + "prod"); + return new CapacityPersistenceFixture(c, request, repository, owner, initial); + } + + private static net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Observation + capacityObservation( + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result reservation, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Disposition + disposition) { + return new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .Observation( + request.evidence().callerWorkload(), + reservation, + net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest.preimage(request), + disposition, + request.admissionAttemptId(), + 7, + "sha256:" + "e".repeat(64), + "controlled-owner-readback".getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + } + + private record CapacityPersistenceFixture( + StorageContext context, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request, + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository repository, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner owner, + net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result initial) {} + @Test void expiredCreatedSettlesSharedSourceHoldWithoutAnyAccountCreatorCompletion() { StorageContext c = storageContext(15, 0); @@ -763,6 +1319,8 @@ c.dsl, new DraftAuthorizationFenceRepository(c.dsl)), } private static void assertAtomicRowsBeforeFinal(StorageContext c) { + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isEqualTo(2); + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); for (String table : List.of( "account_fresh_tenant_identity_associations", @@ -776,6 +1334,9 @@ private static void assertAtomicRowsBeforeFinal(StorageContext c) { } private static void assertAtomicRows(StorageContext c, int expected) { + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))) + .isEqualTo(2 * expected); + assertThat(c.dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); for (String table : List.of( "account_fresh_tenant_identity_associations", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java new file mode 100644 index 0000000000..6c8482d5ec --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Context; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class AccountTenantCapacityWorkloadGuardTest { + private final AccountTenantCapacityWorkloadGuard guard = + new AccountTenantCapacityWorkloadGuard("firemud"); + + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void onlyExactTlsGameSessionAndMethodCanInstallPrivateAssertion() throws Exception { + var method = AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod(); + assertThat( + invoke( + method, + tls("firemud", "game-session-service"), + "spiffe://firemud/ns/firemud/sa/game-session-service")) + .isNull(); + assertThat( + invoke( + method, + tls("firemud", "world-management-service"), + "spiffe://firemud/ns/firemud/sa/world-management-service")) + .isNull(); + assertThatThrownBy(guard::requireAuthenticatedCaller) + .isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, tls("other", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(invoke(method, tls("firemud", "account-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + invoke(AccountServiceGrpc.getGetProfileMethod(), tls("firemud", "game-session-service")) + .getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + @Test + void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { + var method = AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/game-session-service") + .orElseThrow()) + .run( + () -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedCaller) + .isInstanceOf(StatusRuntimeException.class); + }); + for (boolean internal : List.of(true, false)) { + if (internal) + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "instance"); + else SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, tls("firemud", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + } + } + + private Status invoke(MethodDescriptor method, SSLSession ssl) { + return invoke(method, ssl, null); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private Status invoke(MethodDescriptor method, SSLSession ssl, String expectedCallerUri) { + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(method); + when(call.getAttributes()) + .thenReturn( + ssl == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, ssl).build()); + AtomicInteger starts = new AtomicInteger(); + ServerCallHandler next = + (ignored, headers) -> { + assertThat(guard.requireAuthenticatedCaller()).isEqualTo(expectedCallerUri); + starts.incrementAndGet(); + return new ServerCall.Listener() {}; + }; + guard.interceptCall(call, new Metadata(), next); + var captured = ArgumentCaptor.forClass(Status.class); + verify(call, org.mockito.Mockito.atMostOnce()).close(captured.capture(), any(Metadata.class)); + assertThat(starts.get()).isEqualTo(captured.getAllValues().isEmpty() ? 1 : 0); + return captured.getAllValues().isEmpty() ? null : captured.getValue(); + } + + private static SSLSession tls(String namespace, String service) throws Exception { + var leaf = mock(X509Certificate.class); + when(leaf.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/" + namespace + "/sa/" + service))); + var ssl = mock(SSLSession.class); + when(ssl.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + return ssl; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index 05a2f6e1bc..28f9af32c8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -134,10 +134,16 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa assertThat(value.fields()).containsEntry("variant", "PLAYER_ADMISSION"); assertThat(value.fields().get("requestId")).isEqualTo(f.request.requestId().toString()); assertThat(value.fields().get("callerWorkload")).isEqualTo(PEER); + assertThat(f.retainedCapacity).hasSize(1); assertThat( new String(value.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) .contains(f.scope.connectScopeId())) .isFalse(); + assertThat( + f.retainedCapacity + .get(value.fields().get("evaluationIdentity")) + .get("canonical_evidence", byte[].class)) + .containsExactly(value.canonicalBytes()); assertThat(value.membershipSource().accountId()).isEqualTo(ACCOUNT.toString()); assertThat(value.membershipSource().tenantId()).isEqualTo(TENANT.toString()); assertThat(value.membershipSource().membershipExists()).isFalse(); @@ -163,6 +169,17 @@ void missingMembershipRemainsAnExplicitNonadmittingBaselineWithActualCallerAndTa verifyNoInteractions(f.hosting, f.observer); } + @Test + void capacityRetentionFailureRollsBackSourceCaptureWithoutReturningEvidence() throws Exception { + Fixture f = new Fixture(true); + f.refuseCapacityRetention = true; + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isInstanceOf(DataAccessException.class) + .hasMessage("Controlled capacity retention refusal"); + assertThat(f.retainedCapacity).isEmpty(); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + @Test void existingMembershipCarriesItsIndependentVersionAndPositiveCheckpoint() throws Exception { Fixture f = new Fixture(true); @@ -940,6 +957,8 @@ private static final class Fixture { private final CanonicalGameplayAdmissionDecisionReadClient targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); private final RecordingTransactions transactions = new RecordingTransactions(); + private final Map retainedCapacity = new LinkedHashMap<>(); + private boolean refuseCapacityRetention; private final java.util.concurrent.atomic.AtomicReference time = new java.util.concurrent.atomic.AtomicReference<>(NOW); private final FreshTenantCreationEvidence source = source(); @@ -1027,6 +1046,43 @@ private Fixture(boolean exists, String stateScope) throws Exception { PEER); controlledTarget(targets); var dsl = mock(DSLContext.class); + // Controlled retention content, not physical atomicity or Account source authentication. + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (!sql.startsWith("INSERT INTO account_tenant_capacity_evaluations ")) + throw new AssertionError(sql); + if (refuseCapacityRetention) + throw new DataAccessException("Controlled capacity retention refusal"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + Object[] values = (Object[]) invocation.getRawArguments()[1]; + String id = (String) values[0]; + if (retainedCapacity.containsKey(id)) return 0; + var row = mock(org.jooq.Record.class); + when(row.get("evaluation_identity", String.class)).thenReturn(id); + when(row.get("snapshot_identity", String.class)).thenReturn((String) values[1]); + when(row.get("tenant_uuid", UUID.class)).thenReturn((UUID) values[2]); + when(row.get("caller_workload", String.class)).thenReturn((String) values[3]); + when(row.get("owner_service", String.class)).thenReturn((String) values[4]); + when(row.get("canonical_evidence", byte[].class)) + .thenReturn(((byte[]) values[5]).clone()); + when(row.get("evaluated_at", java.time.OffsetDateTime.class)) + .thenReturn((java.time.OffsetDateTime) values[6]); + when(row.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn((java.time.OffsetDateTime) values[7]); + retainedCapacity.put(id, row); + return 1; + }); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (!sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) + throw new AssertionError(sql); + Object[] values = (Object[]) invocation.getRawArguments()[1]; + return retainedCapacity.get((String) values[0]); + }); var connection = mock(Connection.class); when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); doAnswer( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java new file mode 100644 index 0000000000..58751d1b71 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -0,0 +1,497 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.time.ZoneOffset; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Controlled ordering/denial only. Physical transaction and positive current-source proof are + * separate. + */ +class AccountTenantCapacityOwnerTest { + @AfterEach + void clear() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + for (var vector : corpus.path("rejectedUsage")) { + DSLContext dsl = mock(DSLContext.class); + Record usage = mock(Record.class); + when(usage.get("held_units", Long.class)) + .thenReturn(TenantCapacityAdmission.decimal(vector.path("held").asText())); + when(usage.get("used_units", Long.class)) + .thenReturn(TenantCapacityAdmission.decimal(vector.path("usage").asText())); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(usage); + var request = + CapacityAdmissionTestFixture.worldRequest( + TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText())); + request.requireCommittable(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + new AccountTenantCapacityRepository(dsl) + .create( + request, + request.evidence().expiresAt(), + Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC))) + .as(vector.path("name").asText()) + .hasMessage(vector.path("expected").asText()); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + } + } + + @Test + void expiryWhileWaitingForUsageDoesNotReserveCapacity() { + var request = CapacityAdmissionTestFixture.playerRequest(); + DSLContext dsl = mock(DSLContext.class); + Clock clock = mock(Clock.class); + when(clock.instant()).thenThrow(new AssertionError("read before acquiring usage row")); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + org.mockito.Mockito.doReturn(request.evidence().expiresAt()).when(clock).instant(); + return mock(Record.class); + }); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + new AccountTenantCapacityRepository(dsl) + .create(request, request.evidence().expiresAt(), clock)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() + throws Exception { + var f = new Fixture(true); + var result = f.owner.commit(f.request, f.request.evidence().callerWorkload()); + assertThat(result.reservationId()).isEqualTo(f.reservation); + assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload())).isEqualTo(result); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void serializationFailureRetriesOnceAndReplaysInAFreshTransaction() throws Exception { + var f = new Fixture(true); + var aborted = + new org.jooq.exception.DataAccessException( + "concurrent reservation", new SQLException("serialization failure", "40001")); + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenThrow(aborted) + .thenReturn(Optional.of(new Account())); + + assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload()).reservationId()) + .isEqualTo(f.reservation); + verify(f.accounts, times(2)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void changedAttemptOrPayloadOrFenceConflictsBeforeAnyCurrentSourceOrUsageMutation() + throws Exception { + var f = new Fixture(false); + for (Request changed : + java.util.List.of( + CapacityAdmissionTestFixture.playerRequest(false), + new Request( + f.request.identity(), + UUID.randomUUID(), + f.request.capacityRearmFence(), + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(), + new Request( + f.request.identity(), + f.request.admissionAttemptId(), + 2, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(), + new Request( + f.request.identity(), + f.request.admissionAttemptId(), + f.request.capacityRearmFence(), + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission + .Shape(2, 0, 0), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest())) { + assertThatThrownBy(() -> f.owner.commit(changed, changed.evidence().callerWorkload())) + .hasMessage("IDEMPOTENCY_CONFLICT"); + } + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void matchingContentWithoutAccountRetainedAuthorityCannotCreateUsage() throws Exception { + var f = new Fixture(false); + f.existing = false; + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void wrongPeerOrAbsentDeltaNeverStartsAccountWork() throws Exception { + var f = new Fixture(false); + assertThatThrownBy( + () -> f.owner.commit(f.request, "spiffe://firemud/ns/prod/sa/world-management-service")) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.PERMISSION_DENIED); + assertThat(failure.code().toStatusException().getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED); + }); + var absent = + new Request( + f.request.identity(), + f.request.admissionAttemptId(), + 1, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + null, + null) + .withDigest(); + assertThatThrownBy(() -> f.owner.commit(absent, absent.evidence().callerWorkload())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + + @Test + void authenticatedGameSessionCannotSelectWorldOwnerBeforeAccountWork() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.worldRequest(1L)); + assertThatThrownBy(() -> f.owner.commit(f.request, CapacityAdmissionTestFixture.PEER)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.PERMISSION_DENIED)); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + + @Test + void wrongTargetNamespaceOrMissingRequestIsInvalidBeforeAccountWork() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.playerRequest(), "staging"); + for (String peer : + java.util.List.of( + CapacityAdmissionTestFixture.PEER, + "spiffe://firemud/ns/staging/sa/game-session-service")) { + assertThatThrownBy(() -> f.owner.commit(f.request, peer)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.INVALID_ARGUMENT); + assertThat(failure.code().toStatusException().getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.INVALID_ARGUMENT); + }); + } + assertThatThrownBy(() -> f.owner.commit(null, CapacityAdmissionTestFixture.PEER)) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.INVALID_ARGUMENT)); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + + @Test + void unretainedNonCreatingEvidenceRemainsUnavailableWithoutAnyUsageWrite() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.playerRequest(false)); + f.existing = false; + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void exactRetainedNonCreatingEvidenceOutsideWindowIsStale() throws Exception { + var f = new Fixture(true, CapacityAdmissionTestFixture.playerRequest(false)); + f.existing = false; + f.retained = true; + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("CAPACITY_ADMISSION_STALE"); + verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void qualifiedNewerBillingCutoffMakesExactRetainedEvaluationStale() throws Exception { + var f = new Fixture(false); + f.existing = false; + f.retained = true; + var current = mock(Snapshot.class); + var tuple = mock(AuthorityTuple.class); + var tenant = f.request.identity().tenantId().toString(); + var sequence = + Long.parseLong((String) f.request.evidence().fields().get("tenantBillingSequence")); + when(current.membershipExists()).thenReturn(true); + when(current.membershipLifecycleState()).thenReturn("ACTIVE"); + when(current.gameplayAdmissionAllowed()).thenReturn(true); + when(current.tenantId()).thenReturn(tenant); + when(current.authorityTuple()).thenReturn(tuple); + when(tuple.tenantBillingCutoff()) + .thenReturn( + Optional.of( + Map.of( + tenant, + new TenantBillingCutoff("1", Long.toString(sequence + 1), "billing", "2")))); + when(f.memberships.readCurrent( + CapacityAdmissionTestFixture.ACCOUNT, f.request.identity().tenantId())) + .thenReturn(current); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("CAPACITY_ADMISSION_STALE"); + verifyNoInteractions(f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void currentOwnerReadWithoutQualifiedEvidenceIsUnavailable() throws Exception { + var f = new Fixture(false); + f.existing = false; + f.retained = true; + when(f.memberships.readCurrent( + CapacityAdmissionTestFixture.ACCOUNT, f.request.identity().tenantId())) + .thenThrow(new IllegalStateException("Missing committed source")); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .hasMessage("ENTITLEMENT_UNAVAILABLE"); + verifyNoInteractions(f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void nonCreatingEvidenceCannotStartRecoveryOrRearmWork() throws Exception { + var f = new Fixture(false); + var source = + mock( + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .ExecutionReadClient.class); + var recovery = + new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker( + f.owner, f.dsl, source, Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC)); + var denied = CapacityAdmissionTestFixture.playerRequest(false); + var next = + new Request( + denied.identity(), + UUID.randomUUID(), + 2, + denied.targetNamespace(), + denied.context(), + denied.operation(), + denied.priorShape(), + denied.requestedShape(), + denied.evidence(), + denied.capacityDelta(), + null) + .withDigest(); + assertThatThrownBy(() -> recovery.rearm(f.request, next)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + recovery.reconcile( + denied, + net.firedevops.firemud.accountservice.service + .AccountTenantCapacityRecoveryWorker.NoCommitAction.RETAIN_FOR_REARM)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes, source); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships = + mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class); + private final AccountGameplayDelegationIssuanceRepository issuances = + mock(AccountGameplayDelegationIssuanceRepository.class); + private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + private final Request request; + private final UUID reservation = UUID.randomUUID(); + private final AccountTenantCapacityOwner owner; + private boolean existing = true; + private boolean retained; + + private Fixture(boolean expired) throws Exception { + this(expired, CapacityAdmissionTestFixture.playerRequest()); + } + + private Fixture(boolean expired, Request request) throws Exception { + this(expired, request, "prod"); + } + + private Fixture(boolean expired, Request request, String namespace) throws Exception { + this.request = request; + when(accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenReturn(Optional.of(new Account())); + Connection connection = mock(Connection.class); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); + doAnswer( + invocation -> { + invocation.getArgument(0, ConnectionRunnable.class).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + Record row = mock(Record.class); + when(row.get("tenant_uuid", UUID.class)).thenReturn(request.identity().tenantId()); + when(row.get("request_id", UUID.class)).thenReturn(request.identity().requestId()); + when(row.get("admission_id", UUID.class)).thenReturn(request.identity().admissionId()); + when(row.get("admission_attempt_id", UUID.class)).thenReturn(request.admissionAttemptId()); + when(row.get("reservation_id", UUID.class)).thenReturn(reservation); + when(row.get("capacity_rearm_fence", Long.class)).thenReturn(1L); + when(row.get("reservation_fence", Long.class)).thenReturn(1L); + when(row.get("mutation_digest", String.class)).thenReturn(request.mutationDigest()); + when(row.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(request)); + when(row.get("caller_workload", String.class)) + .thenReturn(request.evidence().callerWorkload()); + when(row.get("evaluation_identity", String.class)) + .thenReturn(request.evidence().evaluationIdentity()); + when(row.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(request.evidence().expiresAt())); + when(row.get("state", String.class)).thenReturn("RESERVED"); + Record evaluation = mock(Record.class); + when(evaluation.get("snapshot_identity", String.class)) + .thenReturn(request.evidence().snapshotIdentity()); + var evidence = request.evidence(); + when(evaluation.get("tenant_uuid", UUID.class)).thenReturn(evidence.tenantId()); + when(evaluation.get("caller_workload", String.class)).thenReturn(evidence.callerWorkload()); + when(evaluation.get("owner_service", String.class)).thenReturn(evidence.owner().service()); + when(evaluation.get("canonical_evidence", byte[].class)) + .thenReturn(evidence.canonicalBytes()); + when(evaluation.get("evaluated_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(evidence.evaluatedAt())); + when(evaluation.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(evidence.expiresAt())); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0, String.class); + if (sql.startsWith("SELECT * FROM account_tenant_capacity_reservations ")) + return existing ? row : null; + if (sql.startsWith( + "SELECT snapshot_identity FROM account_tenant_capacity_evaluations ")) + return evaluation; + if (sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) + return retained ? evaluation : null; + throw new AssertionError(sql); + }); + owner = + new AccountTenantCapacityOwner( + dsl, + accounts, + memberships, + issuances, + scopes, + new ControlledTransactions(), + Clock.fixed( + CapacityAdmissionTestFixture.NOW.plusSeconds(expired ? 60 : 1), ZoneOffset.UTC), + namespace); + } + } + + private static final class ControlledTransactions implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction( + @org.jspecify.annotations.Nullable TransactionDefinition definition) { + assertThat(definition).isNotNull(); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getTimeout()).isEqualTo(5); + assertThat(definition.isReadOnly()).isFalse(); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java new file mode 100644 index 0000000000..0bda32761b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; +import io.grpc.stub.StreamObserver; +import java.util.stream.Stream; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedConstruction; + +/** Controlled handler classification only, not authenticated transport or owner-source proof. */ +class AccountTenantCapacityGrpcServiceTest { + @Test + void malformedWireAndStructurallyInvalidRequestsRefuseBeforeOwner() { + var valid = + TenantCapacityAdmissionGrpcCodec.toRequest(CapacityAdmissionTestFixture.playerRequest()); + for (var wire : + new CommitTenantCapacityAdmissionRequest[] { + null, + CommitTenantCapacityAdmissionRequest.getDefaultInstance(), + valid.toBuilder().setCapacityDelta(0).build() + }) { + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + StreamObserver observer = mock(); + + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission(wire, observer); + + assertFailure(observer, Failure.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + } + } + + @ParameterizedTest + @MethodSource("ownerEvidenceFailures") + void unexpectedOwnerFailuresAreSanitizedInternal(RuntimeException cause) { + var request = CapacityAdmissionTestFixture.playerRequest(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)).thenThrow(cause); + StreamObserver observer = mock(); + + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + Status status = Status.fromThrowable(error.getValue()); + assertThat(status.getCode()).isEqualTo(Status.Code.INTERNAL); + assertThat(status.getDescription()).isNull(); + assertThat(status.getCause()).isNull(); + assertThat(error.getValue().getCause()).isNull(); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + verify(owner).commit(request, CapacityAdmissionTestFixture.PEER); + } + } + + @Test + void typedOwnerEvidenceUnavailableKeepsItsPublicFailure() { + var request = CapacityAdmissionTestFixture.playerRequest(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) + .thenThrow(new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE)); + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + assertFailure(observer, Failure.ENTITLEMENT_UNAVAILABLE); + } + } + + private static Stream ownerEvidenceFailures() { + return Stream.of( + new NumberFormatException("Controlled retained billing parse failure"), + new IllegalArgumentException("Controlled retained enum or evidence parse failure"), + new ArithmeticException("Controlled retained arithmetic failure")); + } + + private static MockedConstruction authenticatedCaller() { + return mockConstruction( + AccountTenantCapacityWorkloadGuard.class, + (guard, context) -> + when(guard.requireAuthenticatedCaller()).thenReturn(CapacityAdmissionTestFixture.PEER)); + } + + private static void assertFailure( + StreamObserver observer, Failure expected) { + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + var expectedFailure = expected.toStatusException(); + assertThat(Status.fromThrowable(error.getValue()).getCode()) + .isEqualTo(expectedFailure.getStatus().getCode()); + assertThat(StatusProto.fromThrowable(error.getValue())) + .isEqualTo(StatusProto.fromThrowable(expectedFailure)); + assertThat(error.getValue().getCause()).isNull(); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java new file mode 100644 index 0000000000..5536f68777 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.Normalizer; +import java.util.Base64; +import java.util.HexFormat; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Shape; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext; + +/** The capacity-admission/1 action-family mapping of ADR 0047 mutationDigest/v1. */ +public final class CapacityAdmissionDigest { + public static final int MAX_PREIMAGE_BYTES = 512 * 1024; + public static final int MAX_SEGMENT_BYTES = 384 * 1024; + public static final int MAX_STRING_BYTES = 352 * 1024; + + private CapacityAdmissionDigest() {} + + public static byte[] preimage(Request request) { + var output = new ByteArrayOutputStream(); + segment(output, ascii("mutationDigest/v1")); + field(output, "actionFamilySchemaId", string(TenantCapacityAdmission.SCHEMA_ID)); + field(output, "actionFamilySchemaVersion", string(TenantCapacityAdmission.SCHEMA_VERSION)); + field( + output, + "scope", + object( + "tenantId", string(request.identity().tenantId().toString()), + "requestId", string(request.identity().requestId().toString()), + "admissionId", string(request.identity().admissionId().toString()))); + byte[] context; + if (request.context() instanceof PlayerContext player) { + context = + object( + "accountId", + string(player.accountId().toString()), + "tenantId", + string(player.tenantId().toString()), + "playableStateNamespaceId", + string(player.playableStateNamespaceId().toString()), + "gameInstanceId", + string(player.gameInstanceId().toString()), + "characterId", + string(player.characterId().toString()), + "sessionId", + string(player.sessionId().toString()), + "realmId", + string(player.realmId().toString()), + "requestId", + string(player.requestId().toString()), + "playableStateScope", + string(player.playableStateScope())); + } else { + var world = (WorldContext) request.context(); + context = + object( + "tenantId", + string(world.tenantId().toString()), + "operationId", + string(world.operationId().toString()), + "lifecycleId", + string(world.lifecycleId().toString()), + "gameInstanceId", + string(world.gameInstanceId().toString()), + "ownerId", + string(world.ownerId().toString()), + "ownerFence", + number(world.ownerFence())); + } + field( + output, + "target", + object( + "ownerService", + string(request.context().owner().service()), + "targetNamespace", + string(request.targetNamespace()), + "ownerContext", + context)); + field( + output, + "expectedVersion", + object( + "admissionAttemptId", string(request.admissionAttemptId().toString()), + "capacityRearmFence", number(request.capacityRearmFence()))); + field( + output, + "mutation", + object( + "operation", + string(request.operation().name()), + "priorShape", + shape(request.priorShape()), + "requestedShape", + shape(request.requestedShape()), + "accountEvidence", + string(Base64.getEncoder().encodeToString(request.evidence().canonicalBytes())), + "capacityDelta", + request.capacityDelta() == null + ? value("absent", false, new byte[0]) + : number(request.capacityDelta()))); + field(output, "auditReason", string("capacity-admission")); + if (output.size() > MAX_PREIMAGE_BYTES) throw invalid(); + return output.toByteArray(); + } + + public static String digest(Request request) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage(request))); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + private static byte[] shape(Shape shape) { + return object( + "activeSessions", + number(shape.activeSessions()), + "concurrentGameInstances", + number(shape.concurrentGameInstances()), + "storageBytes", + number(shape.storageBytes())); + } + + private static byte[] number(long value) { + if (value < 0) throw invalid(); + return value("number", true, ascii(Long.toString(value))); + } + + private static byte[] string(String value) { + if (value == null || value.length() > MAX_STRING_BYTES) throw invalid(); + for (int index = 0; index < value.length(); index++) { + char c = value.charAt(index); + if (Character.isHighSurrogate(c)) { + if (++index >= value.length() || !Character.isLowSurrogate(value.charAt(index))) + throw invalid(); + } else if (Character.isLowSurrogate(c)) throw invalid(); + } + byte[] bytes = + Normalizer.normalize(value, Normalizer.Form.NFC).getBytes(StandardCharsets.UTF_8); + if (bytes.length > MAX_STRING_BYTES) throw invalid(); + return value("string", true, bytes); + } + + private static byte[] object(Object... fields) { + if (fields.length % 2 != 0 || fields.length > 32) throw invalid(); + var output = new ByteArrayOutputStream(); + segment(output, ascii(Integer.toString(fields.length / 2))); + for (int index = 0; index < fields.length; index += 2) { + field(output, (String) fields[index], (byte[]) fields[index + 1]); + } + return value("object", true, output.toByteArray()); + } + + private static byte[] value(String type, boolean present, byte[] payload) { + var output = new ByteArrayOutputStream(); + segment(output, ascii(type)); + output.write(present ? '1' : '0'); + segment(output, payload); + return output.toByteArray(); + } + + private static void field(ByteArrayOutputStream output, String name, byte[] value) { + segment(output, ascii(name)); + output.writeBytes(value); + if (output.size() > MAX_PREIMAGE_BYTES) throw invalid(); + } + + private static void segment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_SEGMENT_BYTES) throw invalid(); + output.writeBytes(ascii(Integer.toString(bytes.length))); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid capacity-admission/1 canonical value"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java new file mode 100644 index 0000000000..2632939b7d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Exact original-NEW execution binding. Content is not an Account grant or owner attestation. */ +public record OriginalNewCapacityExecution( + TenantCapacityAdmission.Request request, + TenantCapacityAdmission.Result reservation, + UUID transitionId, + String candidateDigest, + String selectedOwnerId, + long selectedOwnerFence) { + public OriginalNewCapacityExecution { + Objects.requireNonNull(request).requireCommittable(); + Objects.requireNonNull(reservation).requireBinding(request); + TenantCapacityAdmission.uuid(transitionId); + if (selectedOwnerId == null || !selectedOwnerId.matches("[A-Za-z0-9._:-]{1,120}")) + throw new IllegalArgumentException("Exact selected owner instance required"); + if (!(request.context() instanceof TenantCapacityAdmission.PlayerContext player) + || !"SHARED".equals(player.playableStateScope()) + || request.operation() != TenantCapacityAdmission.Operation.CAPACITY_CREATING + || !Long.valueOf(1).equals(request.capacityDelta()) + || !request.priorShape().equals(new TenantCapacityAdmission.Shape(0, 0, 0)) + || !request.requestedShape().equals(new TenantCapacityAdmission.Shape(1, 0, 0)) + || (reservation.state() != TenantCapacityAdmission.State.RESERVED + && reservation.state() != TenantCapacityAdmission.State.FINALIZED) + || !request.identity().admissionId().equals(transitionId) + || selectedOwnerFence <= 0 + || candidateDigest == null + || !candidateDigest.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("Exact original NEW capacity execution required"); + } + + /** All strings have closed grammars; the complete canonical attempt includes Account evidence. */ + public byte[] canonicalBytes() { + Map fields = new LinkedHashMap<>(); + fields.put("schema", "gs-original-new-capacity-execution/v1"); + fields.put("tenantId", request.identity().tenantId().toString()); + fields.put("requestId", request.identity().requestId().toString()); + fields.put("admissionId", request.identity().admissionId().toString()); + fields.put("admissionAttemptId", request.admissionAttemptId().toString()); + fields.put("capacityRearmFence", Long.toString(request.capacityRearmFence())); + fields.put("mutationDigest", request.mutationDigest()); + fields.put("reservationId", reservation.reservationId().toString()); + fields.put("reservationFence", Long.toString(reservation.reservationFence())); + // Floor milliseconds, never extend Account's microsecond expiry at Redis's TIME boundary. + fields.put("expiresAtMillis", Long.toString(reservation.expiresAt().toEpochMilli())); + fields.put("expiresAt", reservation.expiresAt().toString()); + fields.put("snapshotIdentity", reservation.snapshotIdentity()); + fields.put("evaluationIdentity", reservation.evaluationIdentity()); + fields.put("transitionId", transitionId.toString()); + fields.put("candidateDigest", candidateDigest); + fields.put("selectedOwnerId", selectedOwnerId); + fields.put("selectedOwnerFence", Long.toString(selectedOwnerFence)); + fields.put( + "canonicalAttemptPayload", + Base64.getEncoder().encodeToString(CapacityAdmissionDigest.preimage(request))); + StringBuilder json = new StringBuilder("{"); + fields.forEach( + (name, value) -> { + if (json.length() > 1) json.append(','); + json.append('"').append(name).append("\":\"").append(value).append('"'); + }); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(json.append('}').toString()); + } catch (java.io.IOException malformed) { + throw new IllegalArgumentException("Invalid capacity execution", malformed); + } + } + + public String digest() { + return "sha256:" + sha256(canonicalBytes()); + } + + public static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + public byte[] terminalEvidence(String disposition, String physicalDigest, String receiptDigest) { + if (!("COMMITTED".equals(disposition) || "NOT_EXECUTED_AFTER_AUTHORIZATION".equals(disposition)) + || physicalDigest == null + || !physicalDigest.matches("sha256:[0-9a-f]{64}") + || receiptDigest == null + || !receiptDigest.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("Exact terminal owner evidence required"); + var output = new java.io.ByteArrayOutputStream(); + for (byte[] item : + new byte[][] { + "gs-original-new-capacity-result/v1".getBytes(StandardCharsets.US_ASCII), + digest().getBytes(StandardCharsets.US_ASCII), + disposition.getBytes(StandardCharsets.US_ASCII), + physicalDigest.getBytes(StandardCharsets.US_ASCII), + receiptDigest.getBytes(StandardCharsets.US_ASCII) + }) { + output.writeBytes(Integer.toString(item.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(item); + } + return output.toByteArray(); + } + + @Override + public String toString() { + return "OriginalNewCapacityExecution[redacted]"; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java new file mode 100644 index 0000000000..5da6d9b77a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java @@ -0,0 +1,407 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Content contract only. Neither construction nor a digest authenticates Account or an owner. */ +public final class TenantCapacityAdmission { + public static final String SCHEMA_ID = "capacity-admission"; + public static final String SCHEMA_VERSION = "1"; + public static final int MAX_EVIDENCE_BYTES = 256 * 1024; + + private TenantCapacityAdmission() {} + + public enum Owner { + GAME_SESSION("game-session-service", "maxActiveSessions"), + WORLD_MANAGEMENT("world-management-service", "maxConcurrentGameInstances"); + + private final String service; + private final String quota; + + Owner(String service, String quota) { + this.service = service; + this.quota = quota; + } + + public String service() { + return service; + } + + public String quota() { + return quota; + } + } + + public enum Operation { + CAPACITY_CREATING, + NON_EXPANDING_RECOVERY + } + + public enum State { + RESERVED, + FINALIZED, + RELEASED, + QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION + } + + public record Identity(UUID tenantId, UUID requestId, UUID admissionId) { + public Identity { + uuid(tenantId); + uuid(requestId); + uuid(admissionId); + } + } + + /** Complete target resource shape, not the aggregate tenant usage counter. */ + public record Shape(long activeSessions, long concurrentGameInstances, long storageBytes) { + public Shape { + if (activeSessions < 0 || concurrentGameInstances < 0 || storageBytes < 0) throw invalid(); + } + + public long units(Owner owner) { + return owner == Owner.GAME_SESSION ? activeSessions : concurrentGameInstances; + } + } + + public sealed interface OwnerContext permits PlayerContext, WorldContext { + Owner owner(); + + UUID tenantId(); + + UUID gameInstanceId(); + } + + /** The exact typed PlayerExecutionContext, validated against Account's retained evaluation. */ + public record PlayerContext( + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + UUID gameInstanceId, + UUID characterId, + UUID sessionId, + UUID realmId, + UUID requestId, + String playableStateScope) + implements OwnerContext { + public PlayerContext { + uuid(accountId); + uuid(tenantId); + uuid(playableStateNamespaceId); + uuid(gameInstanceId); + uuid(characterId); + uuid(sessionId); + uuid(realmId); + uuid(requestId); + if (!"SHARED".equals(playableStateScope) && !"PRIVATE".equals(playableStateScope)) + throw invalid(); + } + + @Override + public Owner owner() { + return Owner.GAME_SESSION; + } + } + + /** Separate tenant/operation lifecycle context; never inferred from a player context. */ + public record WorldContext( + UUID tenantId, + UUID operationId, + UUID lifecycleId, + UUID gameInstanceId, + UUID ownerId, + long ownerFence) + implements OwnerContext { + public WorldContext { + uuid(tenantId); + uuid(operationId); + uuid(lifecycleId); + uuid(gameInstanceId); + uuid(ownerId); + if (ownerFence <= 0) throw invalid(); + } + + @Override + public Owner owner() { + return Owner.WORLD_MANAGEMENT; + } + } + + /** Exact, strictly decoded existing Account bundle. Bytes are never replaced by a subset/hash. */ + public static final class Evidence { + private final byte[] bytes; + private final Owner owner; + private final Map fields; + + private Evidence(byte[] bytes, Owner owner) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_EVIDENCE_BYTES) throw invalid(); + this.owner = Objects.requireNonNull(owner); + this.bytes = bytes.clone(); + fields = + owner == Owner.GAME_SESSION + ? RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(bytes).fields() + : RuntimeTenantOperationEntitlementEvidence.parseCanonical(bytes).fields(); + } + + public static Evidence player(RuntimePlayerAdmissionEntitlementEvidence value) { + return new Evidence(Objects.requireNonNull(value).canonicalBytes(), Owner.GAME_SESSION); + } + + public static Evidence world(RuntimeTenantOperationEntitlementEvidence value) { + return new Evidence(Objects.requireNonNull(value).canonicalBytes(), Owner.WORLD_MANAGEMENT); + } + + public static Evidence parse(byte[] bytes, Owner owner) { + return new Evidence(bytes, owner); + } + + public byte[] canonicalBytes() { + return bytes.clone(); + } + + public Map fields() { + return owner == Owner.GAME_SESSION + ? RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(bytes).fields() + : RuntimeTenantOperationEntitlementEvidence.parseCanonical(bytes).fields(); + } + + public Owner owner() { + return owner; + } + + public UUID tenantId() { + return UUID.fromString(text("tenantId")); + } + + public String snapshotIdentity() { + return text("snapshotIdentity"); + } + + public String evaluationIdentity() { + return text("evaluationIdentity"); + } + + public String callerWorkload() { + return text("callerWorkload"); + } + + public Instant evaluatedAt() { + return Instant.parse(text("evaluatedAt")); + } + + public Instant expiresAt() { + Instant freshness = evaluatedAt().plusSeconds(15); + if (owner == Owner.GAME_SESSION) { + Instant validity = Instant.parse(text("validUntil")); + if (validity.isBefore(freshness)) return validity; + } + return freshness; + } + + public void requireCurrent(Instant now) { + if (now.isBefore(evaluatedAt()) || !now.isBefore(expiresAt())) throw invalid(); + } + + public long quota() { + Object raw = fields.get("quotas"); + if (!(raw instanceof Map quotas) + || !(quotas.get(owner.quota()) instanceof String value)) throw invalid(); + return decimal(value); + } + + public boolean permitsCreation() { + return Boolean.TRUE.equals(fields.get("gameplayAvailable")) + && Boolean.TRUE.equals( + fields.get( + owner == Owner.GAME_SESSION + ? "allowNewGameplayBindings" + : "allowNewInstanceStarts")); + } + + private String text(String field) { + if (!(fields.get(field) instanceof String value)) throw invalid(); + return value; + } + + @Override + public boolean equals(Object other) { + return other instanceof Evidence value + && owner == value.owner + && Arrays.equals(bytes, value.bytes); + } + + @Override + public int hashCode() { + return 31 * owner.hashCode() + Arrays.hashCode(bytes); + } + + @Override + public String toString() { + return "CapacityEvidence[redacted]"; + } + } + + public record Request( + Identity identity, + UUID admissionAttemptId, + long capacityRearmFence, + String targetNamespace, + OwnerContext context, + Operation operation, + Shape priorShape, + Shape requestedShape, + Evidence evidence, + Long capacityDelta, + String mutationDigest) { + public Request { + Objects.requireNonNull(identity); + uuid(admissionAttemptId); + if (capacityRearmFence <= 0 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw invalid(); + Objects.requireNonNull(context); + Objects.requireNonNull(operation); + Objects.requireNonNull(priorShape); + Objects.requireNonNull(requestedShape); + Objects.requireNonNull(evidence); + if (!identity.tenantId().equals(context.tenantId()) + || !identity.tenantId().equals(evidence.tenantId()) + || context.owner() != evidence.owner() + || !expectedWorkload(targetNamespace, context.owner()).equals(evidence.callerWorkload())) + throw invalid(); + if (capacityDelta != null && capacityDelta < 0) throw invalid(); + if (mutationDigest != null && !mutationDigest.matches("[0-9a-f]{64}")) throw invalid(); + } + + public Request withDigest() { + return new Request( + identity, + admissionAttemptId, + capacityRearmFence, + targetNamespace, + context, + operation, + priorShape, + requestedShape, + evidence, + capacityDelta, + CapacityAdmissionDigest.digest(this)); + } + + /** Strong guard for rearm and selected-owner execution; content alone grants no authority. */ + public void requireCommittable() { + requireStructurallyValid(); + if (operation == Operation.CAPACITY_CREATING && !evidence.permitsCreation()) throw invalid(); + } + + /** Account resolves exact replay/conflict and current policy after this content check. */ + public void requireStructurallyValid() { + if (capacityDelta == null + || mutationDigest == null + || !mutationDigest.equals(CapacityAdmissionDigest.digest(this)) + || !identity.requestId().toString().equals(evidence.fields().get("requestId"))) + throw invalid(); + long net = + Math.subtractExact( + requestedShape.units(context.owner()), priorShape.units(context.owner())); + if (operation == Operation.CAPACITY_CREATING) { + if (capacityDelta <= 0 || net <= 0 || capacityDelta > net) throw invalid(); + // A scalar commitment cannot hide expansion in another resource dimension. + if (context.owner() == Owner.GAME_SESSION + ? requestedShape.concurrentGameInstances() > priorShape.concurrentGameInstances() + : requestedShape.activeSessions() > priorShape.activeSessions()) throw invalid(); + if (requestedShape.storageBytes() > priorShape.storageBytes()) throw invalid(); + } else if (capacityDelta != 0 + || requestedShape.activeSessions() > priorShape.activeSessions() + || requestedShape.concurrentGameInstances() > priorShape.concurrentGameInstances() + || requestedShape.storageBytes() > priorShape.storageBytes()) throw invalid(); + if (context instanceof PlayerContext player) { + if (!identity.requestId().equals(player.requestId())) throw invalid(); + var fields = evidence.fields(); + if (!player.accountId().toString().equals(fields.get("callerAccountId")) + || !(fields.get("target") instanceof Map target) + || !targetNamespace.equals(target.get("targetNamespace")) + || !player.realmId().toString().equals(target.get("realmId")) + || !player + .playableStateNamespaceId() + .toString() + .equals(target.get("playableStateNamespaceId")) + || !player.gameInstanceId().toString().equals(target.get("gameInstanceId")) + || !player.playableStateScope().equals(target.get("playableStateScope"))) + throw invalid(); + } else if (!identity.requestId().equals(((WorldContext) context).operationId())) + throw invalid(); + } + + @Override + public String toString() { + return "TenantCapacityRequest[redacted]"; + } + } + + public record Result( + Identity identity, + UUID admissionAttemptId, + long capacityRearmFence, + String mutationDigest, + UUID reservationId, + long reservationFence, + Instant expiresAt, + State state, + String snapshotIdentity, + String evaluationIdentity) { + public Result { + Objects.requireNonNull(identity); + uuid(admissionAttemptId); + uuid(reservationId); + if (capacityRearmFence <= 0 + || reservationFence <= 0 + || mutationDigest == null + || !mutationDigest.matches("[0-9a-f]{64}")) throw invalid(); + Objects.requireNonNull(expiresAt); + Objects.requireNonNull(state); + if (snapshotIdentity == null + || !snapshotIdentity.matches("sha256:[0-9a-f]{64}") + || evaluationIdentity == null + || !evaluationIdentity.matches("sha256:[0-9a-f]{64}")) throw invalid(); + } + + public void requireBinding(Request request) { + if (!identity.equals(request.identity()) + || !admissionAttemptId.equals(request.admissionAttemptId()) + || capacityRearmFence != request.capacityRearmFence() + || !mutationDigest.equals(request.mutationDigest()) + || !snapshotIdentity.equals(request.evidence().snapshotIdentity()) + || !evaluationIdentity.equals(request.evidence().evaluationIdentity()) + || !expiresAt.isAfter(request.evidence().evaluatedAt()) + || expiresAt.isAfter(request.evidence().expiresAt())) throw invalid(); + } + } + + public static long decimal(String value) { + if (value == null || !value.matches("0|[1-9][0-9]{0,18}")) throw invalid(); + try { + return Long.parseLong(value); + } catch (NumberFormatException overflow) { + throw invalid(); + } + } + + public static String expectedWorkload(String namespace, Owner owner) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw invalid(); + return "spiffe://firemud/ns/" + namespace + "/sa/" + owner.service(); + } + + public static UUID uuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) throw invalid(); + return value; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact bounded tenant capacity admission required"); + } +} diff --git a/services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json b/services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json new file mode 100644 index 0000000000..9048e0c312 --- /dev/null +++ b/services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json @@ -0,0 +1,19 @@ +{ + "actionFamilySchemaId": "capacity-admission", + "actionFamilySchemaVersion": "1", + "encoding": "mutationDigest/v1", + "outerFieldOrder": ["actionFamilySchemaId", "actionFamilySchemaVersion", "scope", "target", "expectedVersion", "mutation", "auditReason"], + "scope": {"order": ["tenantId", "requestId", "admissionId"], "types": ["string", "string", "string"]}, + "target": {"order": ["ownerService", "targetNamespace", "ownerContext"], "types": ["string", "string", "object"]}, + "playerContext": {"order": ["accountId", "tenantId", "playableStateNamespaceId", "gameInstanceId", "characterId", "sessionId", "realmId", "requestId", "playableStateScope"], "types": ["string", "string", "string", "string", "string", "string", "string", "string", "string"]}, + "worldContext": {"order": ["tenantId", "operationId", "lifecycleId", "gameInstanceId", "ownerId", "ownerFence"], "types": ["string", "string", "string", "string", "string", "number"]}, + "expectedVersion": {"order": ["admissionAttemptId", "capacityRearmFence"], "types": ["string", "number"]}, + "mutation": {"order": ["operation", "priorShape", "requestedShape", "accountEvidence", "capacityDelta"], "types": ["string", "object", "object", "string", "number-or-absent"]}, + "shape": {"order": ["activeSessions", "concurrentGameInstances", "storageBytes"], "types": ["number", "number", "number"]}, + "accountEvidence": {"content": "RFC 4648 padded base64 of the complete strict canonical account-auth-evidence-bundle/v1 bytes", "variants": {"game-session-service": "PLAYER_ADMISSION", "world-management-service": "TENANT_OPERATION"}, "validation": "Decode with the existing closed variant codec, including canonical re-encoding equality, before framing. This member binds every byte including bundleVersion, snapshotIdentity, evaluationIdentity, entitlement fields, complete authorityTuple, tenantBillingCutoff and outboxCheckpoints. No digest/subset/loose JSON substitute is accepted."}, + "auditReason": {"type": "string", "constant": "capacity-admission"}, + "capacityDelta": {"wire": "optional int64", "json": "canonical unsigned ASCII decimal string", "minimum": "0", "maximum": "9223372036854775807", "absentEncodingOnly": true, "absentCommitment": "REJECT", "null": "REJECT", "negative": "REJECT"}, + "limits": {"requestWireBytes": 294912, "evidenceBytes": 262144, "preimageBytes": 524288, "segmentBytes": 393216, "normalizedStringBytes": 360448, "objectMembers": 16, "numericBytes": 19, "numericScale": 0, "maximumCompositeDepth": 5}, + "sourceLimits": "The existing PLAYER_ADMISSION and TENANT_OPERATION strict decoders apply their bounded raw UTF-8, duplicate-key, nesting, token, member, array and canonical-reencoding checks before this family is framed.", + "status": "Published source contract and proof definitions only. World lifecycle and authoritative zero-delta prior-shape producers are held; this schema does not activate them." +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java new file mode 100644 index 0000000000..64cb4d0d06 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -0,0 +1,383 @@ +package net.firedevops.firemud.common.account.capacity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Operation; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Shape; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +/** Shared vectors prove content encoding only, never a current Account or runtime grant. */ +class CapacityAdmissionDigestTest { + @Test + void sharedCorpusFixesCompleteEvidenceAndAbsentZeroPositiveBoundaryPreimages() throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + for (var vector : corpus.path("vectors")) { + Long delta = + vector.path("capacityDelta").isNull() + ? null + : TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText()); + Request base = CapacityAdmissionTestFixture.worldRequest(delta); + assertThat(Base64.getEncoder().encodeToString(base.evidence().canonicalBytes())) + .isEqualTo(corpus.path("request").path("canonicalAccountEvidenceBase64").asText()); + Request action = base; + if (vector.has("operation")) { + var prior = vector.path("priorShape"); + var requested = vector.path("requestedShape"); + action = + new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + Operation.valueOf(vector.path("operation").asText()), + new Shape( + TenantCapacityAdmission.decimal(prior.get(0).asText()), + TenantCapacityAdmission.decimal(prior.get(1).asText()), + TenantCapacityAdmission.decimal(prior.get(2).asText())), + new Shape( + TenantCapacityAdmission.decimal(requested.get(0).asText()), + TenantCapacityAdmission.decimal(requested.get(1).asText()), + TenantCapacityAdmission.decimal(requested.get(2).asText())), + base.evidence(), + delta, + null) + .withDigest(); + } + assertThat(HexFormat.of().formatHex(CapacityAdmissionDigest.preimage(action))) + .as(vector.path("name").asText()) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(CapacityAdmissionDigest.digest(action)) + .isEqualTo(vector.path("sha256").asText()); + Request exact = action; + if (vector.path("commitAllowed").asBoolean()) exact.requireCommittable(); + else + assertThatThrownBy(exact::requireCommittable) + .isInstanceOf(IllegalArgumentException.class); + } + } + assertThat(CapacityAdmissionTestFixture.worldRequest(null).mutationDigest()) + .isNotEqualTo(CapacityAdmissionTestFixture.worldRequest(0L).mutationDigest()); + } + + @Test + void sharedPlayerCorpusFixesIndependentPreimageAndDistinctCharacterAndSessionBindings() + throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + var request = corpus.path("playerRequest"); + var context = request.path("ownerContext"); + var vector = corpus.path("playerVector"); + var player = + new PlayerContext( + UUID.fromString(context.path("accountId").asText()), + UUID.fromString(context.path("tenantId").asText()), + UUID.fromString(context.path("playableStateNamespaceId").asText()), + UUID.fromString(context.path("gameInstanceId").asText()), + UUID.fromString(context.path("characterId").asText()), + UUID.fromString(context.path("sessionId").asText()), + UUID.fromString(context.path("realmId").asText()), + UUID.fromString(context.path("requestId").asText()), + context.path("playableStateScope").asText()); + assertThat( + List.of( + player.accountId(), + player.tenantId(), + player.playableStateNamespaceId(), + player.gameInstanceId(), + player.characterId(), + player.sessionId(), + player.realmId(), + player.requestId())) + .doesNotHaveDuplicates(); + assertThat(request.path("ownerService").asText()).isEqualTo(player.owner().service()); + Request action = + new Request( + new Identity( + UUID.fromString(request.path("tenantId").asText()), + UUID.fromString(request.path("requestId").asText()), + UUID.fromString(request.path("admissionId").asText())), + UUID.fromString(request.path("admissionAttemptId").asText()), + TenantCapacityAdmission.decimal(request.path("capacityRearmFence").asText()), + request.path("targetNamespace").asText(), + player, + Operation.valueOf(request.path("operation").asText()), + vectorShape(request.path("priorShape")), + vectorShape(request.path("requestedShape")), + Evidence.parse( + Base64.getDecoder() + .decode(request.path("canonicalAccountEvidenceBase64").asText()), + Owner.GAME_SESSION), + TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText()), + null) + .withDigest(); + action.requireCommittable(); + assertThat(HexFormat.of().formatHex(CapacityAdmissionDigest.preimage(action))) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(CapacityAdmissionDigest.digest(action)).isEqualTo(vector.path("sha256").asText()); + UUID changed = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + for (var ids : + List.of( + List.of(changed, player.sessionId()), + List.of(player.characterId(), changed), + List.of(player.sessionId(), player.characterId()))) { + var mutation = + new PlayerContext( + player.accountId(), + player.tenantId(), + player.playableStateNamespaceId(), + player.gameInstanceId(), + ids.get(0), + ids.get(1), + player.realmId(), + player.requestId(), + player.playableStateScope()); + Request altered = + new Request( + action.identity(), + action.admissionAttemptId(), + action.capacityRearmFence(), + action.targetNamespace(), + mutation, + action.operation(), + action.priorShape(), + action.requestedShape(), + action.evidence(), + action.capacityDelta(), + null) + .withDigest(); + altered.requireCommittable(); + assertThat(altered.mutationDigest()).isNotEqualTo(action.mutationDigest()); + } + } + } + + private static Shape vectorShape(tools.jackson.databind.JsonNode shape) { + return new Shape( + TenantCapacityAdmission.decimal(shape.get(0).asText()), + TenantCapacityAdmission.decimal(shape.get(1).asText()), + TenantCapacityAdmission.decimal(shape.get(2).asText())); + } + + @Test + void sharedRejectedEvidenceAndRequestsReachCanonicalValidators() throws Exception { + var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); + assertThat(resource).isNotNull(); + try (resource) { + var corpus = JsonMapper.builder().build().readTree(resource); + for (var vector : corpus.path("rejectedEvidence")) { + byte[] bytes = + Base64.getDecoder().decode(vector.path("canonicalAccountEvidenceBase64").asText()); + assertThatThrownBy(() -> Evidence.parse(bytes, Owner.WORLD_MANAGEMENT)) + .as(vector.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + for (var vector : corpus.path("rejectedRequests")) { + Request base = CapacityAdmissionTestFixture.worldRequest(17L); + Shape requested = base.requestedShape(); + if (vector.has("requestedShape")) { + var shape = vector.path("requestedShape"); + requested = + new Shape( + TenantCapacityAdmission.decimal(shape.get(0).asText()), + TenantCapacityAdmission.decimal(shape.get(1).asText()), + TenantCapacityAdmission.decimal(shape.get(2).asText())); + } + Long delta = + vector.has("capacityDelta") + ? (vector.path("capacityDelta").isNull() + ? null + : TenantCapacityAdmission.decimal(vector.path("capacityDelta").asText())) + : base.capacityDelta(); + Request rejected = + new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + base.operation(), + base.priorShape(), + requested, + base.evidence(), + delta, + null) + .withDigest(); + assertThatThrownBy(rejected::requireStructurallyValid) + .as(vector.path("name").asText()) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void nonCreatingEvidenceIsValidContentButCannotAuthorizeExecution() { + Request denied = CapacityAdmissionTestFixture.playerRequest(false); + denied.requireStructurallyValid(); + assertThat(denied.evidence().permitsCreation()).isFalse(); + assertThat(CapacityAdmissionTestFixture.playerRequest().evidence().permitsCreation()).isTrue(); + assertThat(denied.mutationDigest()) + .isNotEqualTo(CapacityAdmissionTestFixture.playerRequest().mutationDigest()); + assertThatThrownBy(denied::requireCommittable).isInstanceOf(IllegalArgumentException.class); + var reservation = + new TenantCapacityAdmission.Result( + denied.identity(), + denied.admissionAttemptId(), + denied.capacityRearmFence(), + denied.mutationDigest(), + java.util.UUID.fromString("b1111111-1111-4111-8111-111111111111"), + 1, + denied.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + denied.evidence().snapshotIdentity(), + denied.evidence().evaluationIdentity()); + assertThatThrownBy( + () -> + new OriginalNewCapacityExecution( + denied, + reservation, + denied.identity().admissionId(), + "sha256:" + "a".repeat(64), + "owner-1", + 1)) + .isInstanceOf(IllegalArgumentException.class); + + for (Request invalid : + List.of( + playerMutation(denied, null, denied.requestedShape(), null).withDigest(), + playerMutation(denied, 1L, denied.requestedShape(), null), + playerMutation(denied, 1L, denied.requestedShape(), "b".repeat(64)), + playerMutation(denied, 0L, denied.requestedShape(), null).withDigest(), + playerMutation(denied, 2L, denied.requestedShape(), null).withDigest(), + playerMutation(denied, 1L, denied.priorShape(), null).withDigest(), + playerMutation(denied, 1L, new Shape(1, 1, 0), null).withDigest(), + playerMutation(denied, 1L, new Shape(1, 0, 1), null).withDigest())) { + assertThatThrownBy(invalid::requireStructurallyValid) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(invalid::requireCommittable).isInstanceOf(IllegalArgumentException.class); + } + } + + private static Request playerMutation(Request base, Long delta, Shape requested, String digest) { + return new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + base.operation(), + base.priorShape(), + requested, + base.evidence(), + delta, + digest); + } + + @Test + void decimalWireGrammarRejectsNegativesOverflowAndMalformedSpellingsBeforeHash() { + for (String value : + List.of("9223372036854775808", "-1", "+1", "01", "1e0", "1.0", " 1", "1 ")) { + assertThatThrownBy(() -> TenantCapacityAdmission.decimal(value)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat(TenantCapacityAdmission.decimal("0")).isZero(); + assertThat(TenantCapacityAdmission.decimal("9223372036854775807")).isEqualTo(Long.MAX_VALUE); + assertThatThrownBy(() -> assertThat(Math.addExact(Long.MAX_VALUE, 1)).isPositive()) + .isInstanceOf(ArithmeticException.class); + } + + @Test + void evidenceIsStrictCanonicalAndCompleteChangedFieldsAlterDigest() { + Request original = CapacityAdmissionTestFixture.worldRequest(17L); + String json = new String(original.evidence().canonicalBytes(), StandardCharsets.UTF_8); + for (String changed : + List.of( + " " + json, + json.replaceFirst("\"outboxSequence\":\"3\"", "\"outboxSequence\":\"4\""), + "{\"bundleVersion\":\"1\"," + json.substring(1))) { + assertThatThrownBy( + () -> + Evidence.parse(changed.getBytes(StandardCharsets.UTF_8), Owner.WORLD_MANAGEMENT)) + .isInstanceOf(IllegalArgumentException.class); + } + Evidence changed = + Evidence.parse( + json.replace("\"entitlementVersion\":\"7\"", "\"entitlementVersion\":\"8\"") + .getBytes(StandardCharsets.UTF_8), + Owner.WORLD_MANAGEMENT); + Request mutation = + new Request( + original.identity(), + original.admissionAttemptId(), + original.capacityRearmFence(), + original.targetNamespace(), + original.context(), + original.operation(), + original.priorShape(), + original.requestedShape(), + changed, + original.capacityDelta(), + null) + .withDigest(); + assertThat(mutation.mutationDigest()).isNotEqualTo(original.mutationDigest()); + byte[] copy = changed.canonicalBytes(); + copy[0] = 0; + assertThat(changed.canonicalBytes()[0]).isEqualTo((byte) '{'); + } + + @Test + void zeroCannotHideAnyChangedExpandingShape() { + Request original = CapacityAdmissionTestFixture.worldRequest(0L); + Request zero = + new Request( + original.identity(), + original.admissionAttemptId(), + original.capacityRearmFence(), + original.targetNamespace(), + original.context(), + Operation.NON_EXPANDING_RECOVERY, + new Shape(0, 1, 0), + new Shape(0, 1, 0), + original.evidence(), + 0L, + null) + .withDigest(); + zero.requireCommittable(); + for (Shape shape : List.of(new Shape(1, 1, 0), new Shape(0, 2, 0), new Shape(0, 1, 1))) { + var expanding = + new Request( + zero.identity(), + zero.admissionAttemptId(), + zero.capacityRearmFence(), + zero.targetNamespace(), + zero.context(), + zero.operation(), + zero.priorShape(), + shape, + zero.evidence(), + 0L, + null) + .withDigest(); + assertThatThrownBy(expanding::requireCommittable) + .isInstanceOf(IllegalArgumentException.class); + assertThat(expanding.mutationDigest()).isNotEqualTo(zero.mutationDigest()); + } + } +} diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java new file mode 100644 index 0000000000..3dbb82c187 --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java @@ -0,0 +1,430 @@ +package net.firedevops.firemud.common.account.capacity; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.RuntimeTenantOperationEntitlementEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; + +/** + * Controlled content only. Nothing here authenticates a source, initializes usage or admits play. + */ +public final class CapacityAdmissionTestFixture { + public static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + public static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + public static final UUID REQUEST = UUID.fromString("33333333-3333-4333-8333-333333333333"); + public static final UUID ADMISSION = UUID.fromString("44444444-4444-4444-8444-444444444444"); + public static final UUID ATTEMPT = UUID.fromString("55555555-5555-4555-8555-555555555555"); + public static final UUID PLAYABLE_STATE_NAMESPACE = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + public static final UUID GAME_INSTANCE = UUID.fromString("77777777-7777-4777-8777-777777777777"); + public static final UUID CHARACTER = UUID.fromString("88888888-8888-4888-8888-888888888888"); + public static final UUID SESSION = UUID.fromString("99999999-9999-4999-8999-999999999999"); + public static final UUID REALM = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + public static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; + public static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); + private static final String HASH = "a".repeat(64); + + private CapacityAdmissionTestFixture() {} + + public static RuntimePlayerAdmissionEntitlementEvidence playerEvidence() { + return capture(target(), facts(), sources(), NOW); + } + + public static TenantCapacityAdmission.Request playerRequest() { + return playerRequest(true); + } + + /** Controlled policy content, never proof of current Account entitlement custody. */ + public static TenantCapacityAdmission.Request playerRequest(boolean permitsCreation) { + Map policyFacts = facts(); + policyFacts.put("allowNewGameplayBindings", permitsCreation); + var evidence = capture(target(), policyFacts, sources(), NOW); + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(TENANT, REQUEST, ADMISSION), + ATTEMPT, + 1, + "prod", + new TenantCapacityAdmission.PlayerContext( + ACCOUNT, + TENANT, + PLAYABLE_STATE_NAMESPACE, + GAME_INSTANCE, + CHARACTER, + SESSION, + REALM, + REQUEST, + "SHARED"), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(1, 0, 0), + TenantCapacityAdmission.Evidence.player(evidence), + 1L, + null) + .withDigest(); + } + + /** Controlled complete content for a native owner component fixture, not Account authority. */ + public static TenantCapacityAdmission.Request playerRequestFor( + TenantCapacityAdmission.PlayerContext player, + UUID admission, + UUID attempt, + String namespace, + Map target, + Instant at) { + Map source = new LinkedHashMap<>(sources()); + source.put("callerTokenExpiresAt", at.plusSeconds(90).toString()); + var evidence = + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + player.requestId(), + TenantCapacityAdmission.expectedWorkload( + namespace, TenantCapacityAdmission.Owner.GAME_SESSION), + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash("controlled-scope"), + admittingMembership(player.accountId(), player.tenantId(), player.requestId()), + target, + facts(), + source, + at); + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(player.tenantId(), player.requestId(), admission), + attempt, + 1, + namespace, + player, + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(1, 0, 0), + TenantCapacityAdmission.Evidence.player(evidence), + 1L, + null) + .withDigest(); + } + + public static TenantCapacityAdmission.Request worldRequest(Long delta) { + String tenant = TENANT.toString(); + String stream = "account:auth-authority:v1:tenant/" + tenant; + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-auth-evidence-bundle/v1"); + fields.put("variant", "TENANT_OPERATION"); + fields.put("bundleVersion", "1"); + fields.put("authorityAvailability", "AVAILABLE"); + fields.put("tenantId", tenant); + fields.put("requestId", REQUEST.toString()); + fields.put("callerWorkload", "spiffe://firemud/ns/prod/sa/world-management-service"); + fields.put("sourceKind", "PAID_HOSTING"); + fields.put("subscriptionStatus", "active"); + fields.put("provisioningStatus", null); + fields.put("gameplayAvailable", true); + fields.put("allowPublicJoin", true); + fields.put("allowNewGameplayBindings", true); + fields.put("allowNewInstanceStarts", true); + fields.put( + "quotas", + Map.of( + "maxActiveSessions", + "100", + "maxConcurrentGameInstances", + Long.toString(Long.MAX_VALUE), + "maxStorageBytes", + "1048576")); + fields.put("entitlementVersion", "7"); + fields.put("tenantBillingSequence", "11"); + fields.put("tenantAuthorityGeneration", "5"); + fields.put("evaluatedAt", NOW.toString()); + fields.put("snapshotIdentity", "sha256:" + "a".repeat(64)); + fields.put("evaluationIdentity", "sha256:" + "b".repeat(64)); + fields.put( + "authorityTuple", + Map.of( + "tenantAuthorityGeneration", + Map.of(tenant, "5"), + "tenantBillingCutoff", + Map.of( + tenant, + Map.of( + "tenantAuthorityGeneration", + "5", + "tenantBillingSequence", + "11", + "outboxStreamKey", + stream, + "outboxSequence", + "3")))); + fields.put( + "outboxCheckpoints", + List.of( + Map.of( + "outboxStreamKey", + stream, + "outboxSequence", + "3", + "sourceEventId", + ACCOUNT.toString(), + "sourceEventDigest", + "sha256:" + "a".repeat(64)))); + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(TENANT, REQUEST, ADMISSION), + ATTEMPT, + 1, + "prod", + new TenantCapacityAdmission.WorldContext( + TENANT, REQUEST, ADMISSION, ACCOUNT, ATTEMPT, 7), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(0, Long.MAX_VALUE, 0), + TenantCapacityAdmission.Evidence.world( + RuntimeTenantOperationEntitlementEvidence.fromOwnerEvaluation(fields)), + delta, + null) + .withDigest(); + } + + private static RuntimePlayerAdmissionEntitlementEvidence capture( + Map target, + Map facts, + Map source, + Instant at) { + return RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, + PEER, + RuntimePlayerAdmissionEntitlementEvidence.connectScopeTokenHash("controlled-scope"), + membership(), + target, + facts, + source, + at); + } + + private static Map target() { + Map target = new LinkedHashMap<>(); + target.put("targetClass", "PUBLIC_PRODUCTION"); + target.put("characterCreationPolicy", "PRESEEDED_ONLY"); + target.put("targetNamespace", "prod"); + target.put("tenantId", TENANT.toString()); + target.put("tenantSlug", "tenant"); + target.put("worldSlug", "world"); + target.put("realmId", REALM.toString()); + target.put("realmSlug", "production"); + target.put("playableStateNamespaceId", PLAYABLE_STATE_NAMESPACE.toString()); + target.put("playableStateScope", "SHARED"); + target.put("gameInstanceId", GAME_INSTANCE.toString()); + target.put("canonicalVersionId", REQUEST.toString()); + target.put("catalogRevision", "7"); + target.put("pointerVersion", "3"); + target.put("activeWorldEpoch", "5"); + target.put("evaluatedAt", NOW.minusSeconds(20).toString()); + target.put("connectScopeExpiresAt", NOW.plusSeconds(120).toString()); + return target; + } + + private static Map facts() { + Map facts = new LinkedHashMap<>(); + facts.put("sourceKind", "NON_PAID_DEMO"); + facts.put("subscriptionStatus", null); + facts.put("provisioningStatus", null); + for (String flag : + List.of( + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts")) facts.put(flag, true); + facts.put( + "quotas", + Map.of( + "maxActiveSessions", + "3", + "maxConcurrentGameInstances", + "2", + "maxStorageBytes", + "4096")); + facts.put("entitlementVersion", "1"); + facts.put("tenantBillingSequence", "1"); + facts.put("tenantAuthorityGeneration", "2"); + return facts; + } + + private static Map sources() { + Map source = new LinkedHashMap<>(); + source.put("callerTokenExpiresAt", NOW.plusSeconds(90).toString()); + source.put("paidReceiptValidUntil", null); + for (String key : + List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + source.put(key, REQUEST.toString()); + for (String key : + List.of( + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "admissionPointerSnapshotDigest")) source.put(key, HASH); + for (String key : + List.of( + "scopeDigest", + "entitlementSourceDigest", + "gameSessionOwnerProofDigest", + "publishedPolicySetDigest", + "worldLifecycleDigest")) source.put(key, "sha256:" + HASH); + source.put("worldRowVersion", "0"); + return source; + } + + private static Snapshot membership() { + return membership(ACCOUNT, TENANT, REQUEST, false); + } + + private static Snapshot admittingMembership(UUID account, UUID tenantId, UUID requestId) { + return membership(account, tenantId, requestId, true); + } + + private static Snapshot membership( + UUID account, UUID tenantId, UUID requestId, boolean admitted) { + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, "world", "World", null); + var source = + new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + requestId, + requestDigest, + tenantId, + 17, + "world", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + requestId, + requestDigest, + tenantId, + 17, + "world", + "NEW_GAME_ROW")); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + requestId, + "sha256:" + HASH, + tenantId, + source.creationRequestId(), + source.requestDigest()); + var billing = + new TenantAuthorityEventV1Codec.BillingReceipt( + tenantId, + requestId, + "sha256:" + HASH, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(tenantId), + 1, + TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), + "sha256:" + HASH); + var event = TenantAuthorityEventV1Codec.seal(request, source, 2, 2, 1, billing); + String prefix = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + var tuple = + new AuthorityTuple( + "1", + "1", + Map.of(tenantId.toString(), "2"), + Map.of(tenantId.toString(), "1"), + List.of(), + Optional.empty(), + Optional.of( + Map.of( + tenantId.toString(), + new TenantBillingCutoff("2", "1", event.outboxStreamKey(), "1")))); + String membershipStream = prefix + "membership/" + account + "/" + tenantId; + var tenantSource = + new SourceEvidence( + event.outboxStreamKey(), + "1", + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8)); + List sourceEvidence; + if (admitted) { + Map eventFields = new LinkedHashMap<>(); + eventFields.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + eventFields.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + eventFields.put("eventId", "membership-event-" + requestId); + eventFields.put("requestId", requestId.toString()); + eventFields.put("outboxStreamKey", membershipStream); + eventFields.put("outboxSequence", "1"); + eventFields.put("sourceScope", "membership/" + account + "/" + tenantId); + eventFields.put("accountId", account.toString()); + eventFields.put("tenantId", tenantId.toString()); + eventFields.put("membershipExists", true); + eventFields.put("membershipLifecycleState", "ACTIVE"); + eventFields.put("membershipVersion", Map.of(tenantId.toString(), "1")); + eventFields.put("membershipAuthorityGeneration", "1"); + eventFields.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenantId.toString(), "2"), + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), "1"), + "privateRealmGrantVersions", + List.of(), + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + "2", + "tenantBillingSequence", + "1", + "outboxStreamKey", + event.outboxStreamKey(), + "outboxSequence", + "1")))); + eventFields.put("issuanceFence", "1"); + eventFields.put("roles", List.of("player")); + eventFields.put("gameplayAdmissionAllowed", true); + eventFields.put("callerBoundAuthorityInvalidated", false); + var membershipEvent = MembershipAuthorityEventV1Codec.seal(eventFields); + sourceEvidence = + List.of( + new SourceEvidence( + membershipStream, + "1", + membershipEvent.eventId(), + membershipEvent.eventDigest(), + membershipEvent.canonicalJson()), + tenantSource); + } else { + sourceEvidence = List.of(tenantSource); + } + return new Snapshot( + "firemud-account-service", + account.toString(), + tenantId.toString(), + admitted, + admitted ? "ACTIVE" : "MISSING", + admitted, + Map.of(tenantId.toString(), "1"), + "1", + admitted ? List.of("player") : List.of(), + tuple, + "1", + List.of( + new Checkpoint(prefix + "account/" + account, "0"), + new Checkpoint(prefix + "issuer/firemud-account-service", "0"), + new Checkpoint(membershipStream, admitted ? "1" : "0"), + new Checkpoint(event.outboxStreamKey(), "1")), + sourceEvidence); + } +} diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json new file mode 100644 index 0000000000..e557b9147e --- /dev/null +++ b/services/common-platform-core/src/testFixtures/resources/capacity/capacity-admission-v1-vectors.json @@ -0,0 +1,238 @@ +{ + "schema": "capacity-admission/1", + "validation": "Encoding vectors and separate native request/Account usage rejection fixtures; not source or runtime authority", + "request": { + "tenantId": "22222222-2222-4222-8222-222222222222", + "requestId": "33333333-3333-4333-8333-333333333333", + "admissionId": "44444444-4444-4444-8444-444444444444", + "admissionAttemptId": "55555555-5555-4555-8555-555555555555", + "capacityRearmFence": "1", + "targetNamespace": "prod", + "ownerService": "world-management-service", + "ownerContext": { + "tenantId": "22222222-2222-4222-8222-222222222222", + "operationId": "33333333-3333-4333-8333-333333333333", + "lifecycleId": "44444444-4444-4444-8444-444444444444", + "gameInstanceId": "11111111-1111-4111-8111-111111111111", + "ownerId": "55555555-5555-4555-8555-555555555555", + "ownerFence": "7" + }, + "operation": "CAPACITY_CREATING", + "priorShape": [ + "0", + "0", + "0" + ], + "requestedShape": [ + "0", + "9223372036854775807", + "0" + ], + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5VHVwbGUiOnsidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiI1In0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiMyIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiI1IiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMTEifX19LCJidW5kbGVWZXJzaW9uIjoiMSIsImNhbGxlcldvcmtsb2FkIjoic3BpZmZlOi8vZmlyZW11ZC9ucy9wcm9kL3NhL3dvcmxkLW1hbmFnZW1lbnQtc2VydmljZSIsImVudGl0bGVtZW50VmVyc2lvbiI6IjciLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDJUMDA6MDA6MDBaIiwiZXZhbHVhdGlvbklkZW50aXR5Ijoic2hhMjU2OmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLCJnYW1lcGxheUF2YWlsYWJsZSI6dHJ1ZSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMyIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInNvdXJjZUV2ZW50RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzb3VyY2VFdmVudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIn1dLCJwcm92aXNpb25pbmdTdGF0dXMiOm51bGwsInF1b3RhcyI6eyJtYXhBY3RpdmVTZXNzaW9ucyI6IjEwMCIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiOTIyMzM3MjAzNjg1NDc3NTgwNyIsIm1heFN0b3JhZ2VCeXRlcyI6IjEwNDg1NzYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwic2NoZW1hIjoiYWNjb3VudC1hdXRoLWV2aWRlbmNlLWJ1bmRsZS92MSIsInNuYXBzaG90SWRlbnRpdHkiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInNvdXJjZUtpbmQiOiJQQUlEX0hPU1RJTkciLCJzdWJzY3JpcHRpb25TdGF0dXMiOiJhY3RpdmUiLCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjoiNSIsInRlbmFudEJpbGxpbmdTZXF1ZW5jZSI6IjExIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YXJpYW50IjoiVEVOQU5UX09QRVJBVElPTiJ9" + }, + "vectors": [ + { + "name": "absent", + "capacityDelta": null, + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323431383a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a616273656e7430303a31313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "34da579bb6e881688bc1481a3d8fc910a7e4eee81bc008c5991d31fce179e845", + "commitAllowed": false + }, + { + "name": "present-zero", + "capacityDelta": "0", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323431393a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d62657231313a3031313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "3c80f1967fdb3d87875fc852e306681d7d8b86521f286b7f3896696ded5a9c59", + "commitAllowed": false + }, + { + "name": "present-seventeen", + "capacityDelta": "17", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323432303a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d62657231323a313731313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "61877a450478b0ce6b980f8d502ff027e5248c736444897c9dc536d924b1ee55", + "commitAllowed": true + }, + { + "name": "present-int64-max", + "capacityDelta": "9223372036854775807", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323433383a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a656374313131363a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d6265723131393a3932323333373230333638353437373538303731323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d6265723131393a3932323333373230333638353437373538303731313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "04ba8983d5c1b5f82ed29498bbec78a6e4b8390839525112ec2c8c969f1831bc", + "commitAllowed": true + }, + { + "name": "non-expanding-zero", + "capacityDelta": "0", + "operation": "NON_EXPANDING_RECOVERY", + "priorShape": [ + "0", + "1", + "0" + ], + "requestedShape": [ + "0", + "1", + "0" + ], + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313434373a313a3331323a6f776e657253657276696365363a737472696e673132343a776f726c642d6d616e6167656d656e742d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313333323a313a36383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231313a6f7065726174696f6e4964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a6c6966656379636c654964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431343a67616d65496e7374616e63654964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131373a6f776e65724964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531303a6f776e657246656e6365363a6e756d62657231313a3731353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431323430343a313a35393a6f7065726174696f6e363a737472696e673132323a4e4f4e5f455850414e44494e475f5245434f5645525931303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3131323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3131323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731323034383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523556485677624755694f6e73696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694931496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694931496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d544569665831394c434a696457356b624756575a584a7a61573975496a6f694d534973496d4e686247786c636c6476636d74736232466b496a6f69633342705a6d5a6c4f6938765a6d6c795a5731315a43397563793977636d396b4c334e684c336476636d786b4c573168626d466e5a57316c626e517463325679646d6c6a5a534973496d567564476c30624756745a573530566d567963326c7662694936496a63694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d444a554d4441364d4441364d444261496977695a585a686248566864476c76626b6c6b5a57353061585235496a6f69633268684d6a55324f6d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d4a69596d49694c434a6e5957316c634778686555463259576c7359574a735a53493664484a315a53776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d794973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e4e7664584a6a5a5556325a57353052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a6233567959325646646d567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d544578496e31644c434a77636d393261584e7062323570626d64546447463064584d694f6d353162477773496e4631623352686379493665794a745958684259335270646d56545a584e7a6157397563794936496a45774d434973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694f5449794d7a4d334d6a417a4e6a67314e4463334e5467774e794973496d316865464e3062334a685a3256436558526c63794936496a45774e4467314e7a596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4969776963324e6f5a573168496a6f6959574e6a62335675644331686458526f4c5756326157526c626d4e6c4c574a31626d52735a5339324d534973496e4e755958427a614739305357526c626e527064486b694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4e7664584a6a5a557470626d51694f694a5151556c45583068505531524a546b63694c434a7a64574a7a59334a7063485270623235546447463064584d694f694a6859335270646d55694c434a305a573568626e52426458526f62334a7064486c485a57356c636d463061573975496a6f694e534973496e526c626d467564454a7062477870626d64545a5846315a57356a5a534936496a4578496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a3259584a7059573530496a6f695645564f515535555830395152564a4256456c5054694a3931333a636170616369747944656c7461363a6e756d62657231313a3031313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "c93ecc41111c5440dfa53da14b7a564a5148a5411221abe15251ad59859ee3cb", + "commitAllowed": true + } + ], + "rejected": [ + { + "name": "delta-0", + "capacityDelta": "9223372036854775808", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-1", + "capacityDelta": "-1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-2", + "capacityDelta": "+1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-3", + "capacityDelta": "01", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-4", + "capacityDelta": "1e0", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-5", + "capacityDelta": "1.0", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-6", + "capacityDelta": " 1", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-7", + "capacityDelta": "1 ", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-8", + "capacityDelta": 1, + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "delta-9", + "capacityDelta": 0.0, + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + } + ], + "rejectedEvidence": [ + { + "name": "changed-cutoff-without-checkpoint", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null, + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5VHVwbGUiOnsidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiI1In0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiNCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiI1IiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMTEifX19LCJidW5kbGVWZXJzaW9uIjoiMSIsImNhbGxlcldvcmtsb2FkIjoic3BpZmZlOi8vZmlyZW11ZC9ucy9wcm9kL3NhL3dvcmxkLW1hbmFnZW1lbnQtc2VydmljZSIsImVudGl0bGVtZW50VmVyc2lvbiI6IjciLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDJUMDA6MDA6MDBaIiwiZXZhbHVhdGlvbklkZW50aXR5Ijoic2hhMjU2OmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmIiLCJnYW1lcGxheUF2YWlsYWJsZSI6dHJ1ZSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMyIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInNvdXJjZUV2ZW50RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzb3VyY2VFdmVudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIn1dLCJwcm92aXNpb25pbmdTdGF0dXMiOm51bGwsInF1b3RhcyI6eyJtYXhBY3RpdmVTZXNzaW9ucyI6IjEwMCIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiOTIyMzM3MjAzNjg1NDc3NTgwNyIsIm1heFN0b3JhZ2VCeXRlcyI6IjEwNDg1NzYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwic2NoZW1hIjoiYWNjb3VudC1hdXRoLWV2aWRlbmNlLWJ1bmRsZS92MSIsInNuYXBzaG90SWRlbnRpdHkiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInNvdXJjZUtpbmQiOiJQQUlEX0hPU1RJTkciLCJzdWJzY3JpcHRpb25TdGF0dXMiOiJhY3RpdmUiLCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjoiNSIsInRlbmFudEJpbGxpbmdTZXF1ZW5jZSI6IjExIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YXJpYW50IjoiVEVOQU5UX09QRVJBVElPTiJ9" + }, + { + "name": "noncanonical-evidence-whitespace", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null, + "canonicalAccountEvidenceBase64": "IHsiYWxsb3dOZXdHYW1lcGxheUJpbmRpbmdzIjp0cnVlLCJhbGxvd05ld0luc3RhbmNlU3RhcnRzIjp0cnVlLCJhbGxvd1B1YmxpY0pvaW4iOnRydWUsImF1dGhvcml0eUF2YWlsYWJpbGl0eSI6IkFWQUlMQUJMRSIsImF1dGhvcml0eVR1cGxlIjp7InRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjoiNSJ9LCJ0ZW5hbnRCaWxsaW5nQ3V0b2ZmIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6eyJvdXRib3hTZXF1ZW5jZSI6IjMiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjoiNSIsInRlbmFudEJpbGxpbmdTZXF1ZW5jZSI6IjExIn19fSwiYnVuZGxlVmVyc2lvbiI6IjEiLCJjYWxsZXJXb3JrbG9hZCI6InNwaWZmZTovL2ZpcmVtdWQvbnMvcHJvZC9zYS93b3JsZC1tYW5hZ2VtZW50LXNlcnZpY2UiLCJlbnRpdGxlbWVudFZlcnNpb24iOiI3IiwiZXZhbHVhdGVkQXQiOiIyMDI2LTExLTAyVDAwOjAwOjAwWiIsImV2YWx1YXRpb25JZGVudGl0eSI6InNoYTI1NjpiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwiZ2FtZXBsYXlBdmFpbGFibGUiOnRydWUsIm91dGJveENoZWNrcG9pbnRzIjpbeyJvdXRib3hTZXF1ZW5jZSI6IjMiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJzb3VyY2VFdmVudERpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwic291cmNlRXZlbnRJZCI6IjExMTExMTExLTExMTEtNDExMS04MTExLTExMTExMTExMTExMSJ9XSwicHJvdmlzaW9uaW5nU3RhdHVzIjpudWxsLCJxdW90YXMiOnsibWF4QWN0aXZlU2Vzc2lvbnMiOiIxMDAiLCJtYXhDb25jdXJyZW50R2FtZUluc3RhbmNlcyI6IjkyMjMzNzIwMzY4NTQ3NzU4MDciLCJtYXhTdG9yYWdlQnl0ZXMiOiIxMDQ4NTc2In0sInJlcXVlc3RJZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsInNjaGVtYSI6ImFjY291bnQtYXV0aC1ldmlkZW5jZS1idW5kbGUvdjEiLCJzbmFwc2hvdElkZW50aXR5Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzb3VyY2VLaW5kIjoiUEFJRF9IT1NUSU5HIiwic3Vic2NyaXB0aW9uU3RhdHVzIjoiYWN0aXZlIiwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjUiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxMSIsInRlbmFudElkIjoiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwidmFyaWFudCI6IlRFTkFOVF9PUEVSQVRJT04ifQ==" + }, + { + "name": "duplicate-evidence-member", + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null, + "canonicalAccountEvidenceBase64": "eyJidW5kbGVWZXJzaW9uIjoiMSIsImFsbG93TmV3R2FtZXBsYXlCaW5kaW5ncyI6dHJ1ZSwiYWxsb3dOZXdJbnN0YW5jZVN0YXJ0cyI6dHJ1ZSwiYWxsb3dQdWJsaWNKb2luIjp0cnVlLCJhdXRob3JpdHlBdmFpbGFiaWxpdHkiOiJBVkFJTEFCTEUiLCJhdXRob3JpdHlUdXBsZSI6eyJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6IjUifSwidGVuYW50QmlsbGluZ0N1dG9mZiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOnsib3V0Ym94U2VxdWVuY2UiOiIzIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjUiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxMSJ9fX0sImJ1bmRsZVZlcnNpb24iOiIxIiwiY2FsbGVyV29ya2xvYWQiOiJzcGlmZmU6Ly9maXJlbXVkL25zL3Byb2Qvc2Evd29ybGQtbWFuYWdlbWVudC1zZXJ2aWNlIiwiZW50aXRsZW1lbnRWZXJzaW9uIjoiNyIsImV2YWx1YXRlZEF0IjoiMjAyNi0xMS0wMlQwMDowMDowMFoiLCJldmFsdWF0aW9uSWRlbnRpdHkiOiJzaGEyNTY6YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYiIsImdhbWVwbGF5QXZhaWxhYmxlIjp0cnVlLCJvdXRib3hDaGVja3BvaW50cyI6W3sib3V0Ym94U2VxdWVuY2UiOiIzIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwic291cmNlRXZlbnREaWdlc3QiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInNvdXJjZUV2ZW50SWQiOiIxMTExMTExMS0xMTExLTQxMTEtODExMS0xMTExMTExMTExMTEifV0sInByb3Zpc2lvbmluZ1N0YXR1cyI6bnVsbCwicXVvdGFzIjp7Im1heEFjdGl2ZVNlc3Npb25zIjoiMTAwIiwibWF4Q29uY3VycmVudEdhbWVJbnN0YW5jZXMiOiI5MjIzMzcyMDM2ODU0Nzc1ODA3IiwibWF4U3RvcmFnZUJ5dGVzIjoiMTA0ODU3NiJ9LCJyZXF1ZXN0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJzY2hlbWEiOiJhY2NvdW50LWF1dGgtZXZpZGVuY2UtYnVuZGxlL3YxIiwic25hcHNob3RJZGVudGl0eSI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwic291cmNlS2luZCI6IlBBSURfSE9TVElORyIsInN1YnNjcmlwdGlvblN0YXR1cyI6ImFjdGl2ZSIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiI1IiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMTEiLCJ0ZW5hbnRJZCI6IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInZhcmlhbnQiOiJURU5BTlRfT1BFUkFUSU9OIn0=" + } + ], + "rejectedRequests": [ + { + "name": "delta-10", + "capacityDelta": null, + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + }, + { + "name": "changed-shape", + "requestedShape": [ + "1", + "9223372036854775807", + "0" + ], + "expected": "REJECT_BEFORE_COMMIT", + "acceptedDigest": null + } + ], + "rejectedUsage": [ + { + "name": "usage-addition-overflow", + "usage": "9223372036854775807", + "held": "0", + "capacityDelta": "1", + "expected": "CAPACITY_QUOTA_EXCEEDED", + "acceptedDigest": null + }, + { + "name": "held-addition-overflow", + "usage": "0", + "held": "9223372036854775807", + "capacityDelta": "1", + "expected": "CAPACITY_QUOTA_EXCEEDED", + "acceptedDigest": null + } + ], + "playerRequest": { + "tenantId": "22222222-2222-4222-8222-222222222222", + "requestId": "33333333-3333-4333-8333-333333333333", + "admissionId": "44444444-4444-4444-8444-444444444444", + "ownerService": "game-session-service", + "targetNamespace": "prod", + "ownerContext": { + "accountId": "11111111-1111-4111-8111-111111111111", + "tenantId": "22222222-2222-4222-8222-222222222222", + "playableStateNamespaceId": "66666666-6666-4666-8666-666666666666", + "gameInstanceId": "77777777-7777-4777-8777-777777777777", + "characterId": "88888888-8888-4888-8888-888888888888", + "sessionId": "99999999-9999-4999-8999-999999999999", + "realmId": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "requestId": "33333333-3333-4333-8333-333333333333", + "playableStateScope": "SHARED" + }, + "admissionAttemptId": "55555555-5555-4555-8555-555555555555", + "capacityRearmFence": "1", + "operation": "CAPACITY_CREATING", + "priorShape": [ + "0", + "0", + "0" + ], + "requestedShape": [ + "1", + "0", + "0" + ], + "canonicalAccountEvidenceBase64": "eyJhbGxvd05ld0dhbWVwbGF5QmluZGluZ3MiOnRydWUsImFsbG93TmV3SW5zdGFuY2VTdGFydHMiOnRydWUsImFsbG93UHVibGljSm9pbiI6dHJ1ZSwiYXV0aG9yaXR5QXZhaWxhYmlsaXR5IjoiQVZBSUxBQkxFIiwiYXV0aG9yaXR5U291cmNlRXZpZGVuY2UiOlt7ImNhbm9uaWNhbEV2ZW50SnNvbiI6IntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNFwiLFwiZXZlbnRJZFwiOlwiZWRiM2JkMzMtODZlMS0zYmZkLTllYjItZjY3ZmZkYzNjOTZiXCIsXCJldmVudFR5cGVcIjpcIlRFTkFOVF9BVVRIT1JJVFlfQ0hBTkdFRFwiLFwib3V0Ym94U2VxdWVuY2VcIjpcIjFcIixcIm91dGJveFN0cmVhbUtleVwiOlwiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJyZXF1ZXN0RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwicmVxdWVzdElkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInNjaGVtYVZlcnNpb25cIjpcImFjY291bnQtdGVuYW50LWF1dGhvcml0eS1ldmVudC92MVwiLFwic291cmNlRXZpZGVuY2VcIjp7XCJjYW5vbmljYWxUZW5hbnRJZFwiOlwiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyXCIsXCJjcmVhdGlvblJlcXVlc3RJZFwiOlwiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzXCIsXCJldmlkZW5jZURpZ2VzdFwiOlwic2hhMjU2OjcxNzQwZWZmNTcxNzI0ZDY3ZmJiMjVjMGY4NzQ1MjYyMzY1NzRmNzI0MjlhODg1OTI2ODljMWFjNDdlODAzY2VcIixcIm9wZXJhdGlvbklkXCI6XCIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzNcIixcInByb3ZlbmFuY2VLaW5kXCI6XCJORVdfR0FNRV9ST1dcIixcInJlcXVlc3REaWdlc3RcIjpcInNoYTI1NjpmMDZlNWU1MGJiZGE5OTE3YjNmZGFkOGUyNzczNzA2OTNmNDlhZmMzMzllZWM3Zjc1NDhiMWU1NDEyNTQ2NjkwXCIsXCJzY2hlbWFWZXJzaW9uXCI6MSxcInNvdXJjZUdhbWVSb3dJZFwiOlwiMTdcIixcInNvdXJjZUdhbWVUZW5hbnRLZXlcIjpcIndvcmxkXCIsXCJ0YXJnZXROYW1lc3BhY2VcIjpcInByb2RcIn0sXCJ0ZW5hbnRBdXRob3JpdHlHZW5lcmF0aW9uXCI6XCIyXCIsXCJ0ZW5hbnRBdXRob3JpdHlTb3VyY2VWZXJzaW9uXCI6XCIyXCIsXCJ0ZW5hbnRCaWxsaW5nUmVjZWlwdFwiOntcImV2ZW50RGlnZXN0XCI6XCJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYVwiLFwiZXZlbnRJZFwiOlwiNWFjMTU4MmItYTQwZC0zNTA1LWFiNDItZjc3NjY1N2I0YjYwXCIsXCJvdXRib3hTdHJlYW1LZXlcIjpcImFjY291bnQ6dGVuYW50LWVudGl0bGVtZW50OnYxOnRlbmFudC8yMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIixcInRlbmFudEJpbGxpbmdTZXF1ZW5jZVwiOlwiMVwifSxcInRlbmFudElkXCI6XCIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjJcIn0iLCJldmVudERpZ2VzdCI6InNoYTI1NjowZTg0Mjk5ODMzZDg1NzU0ZmE1ODNlNDE1MGZhN2Q5MTM3NDZiODNhZWVjMzRhMDU2YzRjY2I1NjZhMTUwYzI0IiwiZXZlbnRJZCI6ImVkYjNiZDMzLTg2ZTEtM2JmZC05ZWIyLWY2N2ZmZGMzYzk2YiIsIm91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9XSwiYXV0aG9yaXR5VHVwbGUiOnsiYWNjb3VudEF1dGhvcml0eUdlbmVyYXRpb24iOiIxIiwiaXNzdWVyQXV0aEdlbmVyYXRpb24iOiIxIiwibWVtYmVyc2hpcEF1dGhvcml0eUdlbmVyYXRpb24iOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjoiMSJ9LCJwcml2YXRlUmVhbG1HcmFudFZlcnNpb25zIjpbXSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiOiIyIn0sInRlbmFudEJpbGxpbmdDdXRvZmYiOnsiMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIjp7Im91dGJveFNlcXVlbmNlIjoiMSIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6dGVuYW50LzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiIsInRlbmFudEF1dGhvcml0eUdlbmVyYXRpb24iOiIyIiwidGVuYW50QmlsbGluZ1NlcXVlbmNlIjoiMSJ9fX0sImJ1bmRsZVZlcnNpb24iOiIyIiwiY2FsbGVyQWNjb3VudElkIjoiMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExIiwiY2FsbGVyV29ya2xvYWQiOiJzcGlmZmU6Ly9maXJlbXVkL25zL3Byb2Qvc2EvZ2FtZS1zZXNzaW9uLXNlcnZpY2UiLCJlbnRpdGxlbWVudFZlcnNpb24iOiIxIiwiZXZhbHVhdGVkQXQiOiIyMDI2LTExLTAyVDAwOjAwOjAwWiIsImV2YWx1YXRpb25JZGVudGl0eSI6InNoYTI1NjpkYWY2MTU0MjQwNWE1MmMwOTY5OTRiNWRiODk5NmRhNGJhOWJiNWFhOGI4ZjU2YjY4YjY4NWJjNTU4NTdjYjM4IiwiZ2FtZXBsYXlBZG1pc3Npb25BbGxvd2VkIjpmYWxzZSwiZ2FtZXBsYXlBdmFpbGFibGUiOnRydWUsImlzc3VhbmNlRmVuY2UiOiIxIiwiaXNzdWVyIjoiZmlyZW11ZC1hY2NvdW50LXNlcnZpY2UiLCJtZW1iZXJzaGlwQXV0aG9yaXR5R2VuZXJhdGlvbiI6IjEiLCJtZW1iZXJzaGlwRXhpc3RzIjpmYWxzZSwibWVtYmVyc2hpcExpZmVjeWNsZVN0YXRlIjoiTUlTU0lORyIsIm1lbWJlcnNoaXBWZXJzaW9uIjp7IjIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiI6IjEifSwib3V0Ym94Q2hlY2twb2ludHMiOlt7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6YWNjb3VudC8xMTExMTExMS0xMTExLTQxMTEtODExMS0xMTExMTExMTExMTEifSx7Im91dGJveFNlcXVlbmNlIjoiMCIsIm91dGJveFN0cmVhbUtleSI6ImFjY291bnQ6YXV0aC1hdXRob3JpdHk6djE6aXNzdWVyL2ZpcmVtdWQtYWNjb3VudC1zZXJ2aWNlIn0seyJvdXRib3hTZXF1ZW5jZSI6IjAiLCJvdXRib3hTdHJlYW1LZXkiOiJhY2NvdW50OmF1dGgtYXV0aG9yaXR5OnYxOm1lbWJlcnNoaXAvMTExMTExMTEtMTExMS00MTExLTgxMTEtMTExMTExMTExMTExLzIyMjIyMjIyLTIyMjItNDIyMi04MjIyLTIyMjIyMjIyMjIyMiJ9LHsib3V0Ym94U2VxdWVuY2UiOiIxIiwib3V0Ym94U3RyZWFtS2V5IjoiYWNjb3VudDphdXRoLWF1dGhvcml0eTp2MTp0ZW5hbnQvMjIyMjIyMjItMjIyMi00MjIyLTgyMjItMjIyMjIyMjIyMjIyIiwic291cmNlRXZlbnREaWdlc3QiOiJzaGEyNTY6MGU4NDI5OTgzM2Q4NTc1NGZhNTgzZTQxNTBmYTdkOTEzNzQ2YjgzYWVlYzM0YTA1NmM0Y2NiNTY2YTE1MGMyNCIsInNvdXJjZUV2ZW50SWQiOiJlZGIzYmQzMy04NmUxLTNiZmQtOWViMi1mNjdmZmRjM2M5NmIifV0sInByb3Zpc2lvbmluZ1N0YXR1cyI6bnVsbCwicXVvdGFzIjp7Im1heEFjdGl2ZVNlc3Npb25zIjoiMyIsIm1heENvbmN1cnJlbnRHYW1lSW5zdGFuY2VzIjoiMiIsIm1heFN0b3JhZ2VCeXRlcyI6IjQwOTYifSwicmVxdWVzdElkIjoiMzMzMzMzMzMtMzMzMy00MzMzLTgzMzMtMzMzMzMzMzMzMzMzIiwicm9sZXMiOltdLCJzY2hlbWEiOiJhY2NvdW50LWF1dGgtZXZpZGVuY2UtYnVuZGxlL3YxIiwic25hcHNob3RJZGVudGl0eSI6InNoYTI1NjphNmQ4ZjBjOTU3NTFjMDdkNzExOTlmZGE2ZjFjYjU4MzgyY2ZkODM0NWM2MTllYWIxM2E3MWE1M2MyMmU5YTVjIiwic291cmNlS2luZCI6Ik5PTl9QQUlEX0RFTU8iLCJzb3VyY2VSZWZlcmVuY2VzIjp7ImFkbWlzc2lvblBvaW50ZXJTbmFwc2hvdERpZ2VzdCI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb21taXRQcm9vZlNoYTI1NiI6ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJjYWxsZXJDb250ZXh0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJjYWxsZXJPcGVyYXRpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclJlZ2lzdHJ5UmVjb3JkU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImNhbGxlclRva2VuRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJjYWxsZXJUb2tlbkp0aSI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhbGxlclRva2VuU2hhMjU2IjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsImVudGl0bGVtZW50U291cmNlRGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJnYW1lU2Vzc2lvbk93bmVyUHJvb2ZEaWdlc3QiOiJzaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSIsInBhaWRSZWNlaXB0VmFsaWRVbnRpbCI6bnVsbCwicHVibGlzaGVkUG9saWN5U2V0RGlnZXN0Ijoic2hhMjU2OmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWEiLCJzY29wZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRDYXB0dXJlSWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJ3b3JsZExpZmVjeWNsZURpZ2VzdCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhIiwid29ybGRSb3dWZXJzaW9uIjoiMCJ9LCJzdWJzY3JpcHRpb25TdGF0dXMiOm51bGwsInRhcmdldCI6eyJhY3RpdmVXb3JsZEVwb2NoIjoiNSIsImNhbm9uaWNhbFZlcnNpb25JZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyIsImNhdGFsb2dSZXZpc2lvbiI6IjciLCJjaGFyYWN0ZXJDcmVhdGlvblBvbGljeSI6IlBSRVNFRURFRF9PTkxZIiwiY29ubmVjdFNjb3BlRXhwaXJlc0F0IjoiMjAyNi0xMS0wMlQwMDowMjowMFoiLCJldmFsdWF0ZWRBdCI6IjIwMjYtMTEtMDFUMjM6NTk6NDBaIiwiZ2FtZUluc3RhbmNlSWQiOiI3Nzc3Nzc3Ny03Nzc3LTQ3NzctODc3Ny03Nzc3Nzc3Nzc3NzciLCJwbGF5YWJsZVN0YXRlTmFtZXNwYWNlSWQiOiI2NjY2NjY2Ni02NjY2LTQ2NjYtODY2Ni02NjY2NjY2NjY2NjYiLCJwbGF5YWJsZVN0YXRlU2NvcGUiOiJTSEFSRUQiLCJwb2ludGVyVmVyc2lvbiI6IjMiLCJyZWFsbUlkIjoiYWFhYWFhYWEtYWFhYS00YWFhLThhYWEtYWFhYWFhYWFhYWFhIiwicmVhbG1TbHVnIjoicHJvZHVjdGlvbiIsInRhcmdldENsYXNzIjoiUFVCTElDX1BST0RVQ1RJT04iLCJ0YXJnZXROYW1lc3BhY2UiOiJwcm9kIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ0ZW5hbnRTbHVnIjoidGVuYW50Iiwid29ybGRTbHVnIjoid29ybGQifSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6IjIiLCJ0ZW5hbnRCaWxsaW5nU2VxdWVuY2UiOiIxIiwidGVuYW50SWQiOiIyMjIyMjIyMi0yMjIyLTQyMjItODIyMi0yMjIyMjIyMjIyMjIiLCJ2YWxpZFVudGlsIjoiMjAyNi0xMS0wMlQwMDowMTozMFoiLCJ2YXJpYW50IjoiUExBWUVSX0FETUlTU0lPTiIsInZlcmlmaWVkQ29ubmVjdFNjb3BlVG9rZW5IYXNoIjoic2hhMjU2OjIyZjhhNGExOTIzNTMzNGVmZDAzNThjOTM2M2MyZTkzYzc5OWJkNWQ4NDkzODkxODk5MmExM2E3MDRiMDUzNjIifQ==" + }, + "playerVector": { + "name": "distinct-player-admission-positive", + "capacityDelta": "1", + "commitAllowed": true, + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673131383a63617061636974792d61646d697373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a656374313138323a313a33383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d323232323232323232323232393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331313a61646d697373696f6e4964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d343434343434343434343434363a746172676574363a6f626a656374313634363a313a3331323a6f776e657253657276696365363a737472696e673132303a67616d652d73657373696f6e2d7365727669636531353a7461726765744e616d657370616365363a737472696e6731343a70726f6431323a6f776e6572436f6e74657874363a6f626a656374313533353a313a39393a6163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d313131313131313131313131383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323232343a706c617961626c6553746174654e616d6573706163654964363a737472696e673133363a36363636363636362d363636362d343636362d383636362d36363636363636363636363631343a67616d65496e7374616e63654964363a737472696e673133363a37373737373737372d373737372d343737372d383737372d37373737373737373737373731313a6368617261637465724964363a737472696e673133363a38383838383838382d383838382d343838382d383838382d383838383838383838383838393a73657373696f6e4964363a737472696e673133363a39393939393939392d393939392d343939392d383939392d393939393939393939393939373a7265616c6d4964363a737472696e673133363a61616161616161612d616161612d346161612d386161612d616161616161616161616161393a726571756573744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331383a706c617961626c65537461746553636f7065363a737472696e6731363a53484152454431353a657870656374656456657273696f6e363a6f626a656374313130353a313a3231383a61646d697373696f6e417474656d70744964363a737472696e673133363a35353535353535352d353535352d343535352d383535352d35353535353535353535353531383a6361706163697479526561726d46656e6365363a6e756d62657231313a31383a6d75746174696f6e363a6f626a65637431383533393a313a35393a6f7065726174696f6e363a737472696e673131373a43415041434954595f4352454154494e4731303a7072696f725368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3032333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031343a7265717565737465645368617065363a6f626a6563743139373a313a3331343a61637469766553657373696f6e73363a6e756d62657231313a3132333a636f6e63757272656e7447616d65496e7374616e636573363a6e756d62657231313a3031323a73746f726167654279746573363a6e756d62657231313a3031353a6163636f756e7445766964656e6365363a737472696e6731383138383a65794a68624778766430356c643064686257567762474635516d6c755a476c755a334d694f6e527964575573496d467362473933546d56335357357a64474675593256546447467964484d694f6e527964575573496d4673624739335548566962476c6a536d39706269493664484a315a53776959585630614739796158523551585a6861577868596d6c7361585235496a6f6951565a4253557842516b78464969776959585630614739796158523555323931636d4e6c52585a705a475675593255694f6c7437496d4e68626d397561574e68624556325a573530536e4e7662694936496e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e4677694c4677695a585a6c626e524a5a4677694f6c77695a5752694d324a6b4d7a4d744f445a6c4d53307a596d5a6b4c546c6c596a49745a6a59335a6d5a6b597a4e6a4f545a695843497358434a6c646d56756446523563475663496a7063496c5246546b464f564639425656524954314a4a56466c6651306842546b6446524677694c46776962335630596d3934553256786457567559325663496a7063496a466349697863496d393164474a7665464e30636d56686255746c655677694f6c776959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a795a5846315a584e3052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c467769636d56786457567a64456c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e4e6a6147567459565a6c636e4e7062323563496a7063496d466a59323931626e517464475675595735304c57463164476876636d6c306553316c646d5675644339324d5677694c46776963323931636d4e6c52585a705a47567559325663496a703758434a6a59573576626d6c6a595778555a573568626e524a5a4677694f6c77694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49795843497358434a6a636d566864476c76626c4a6c6358566c6333524a5a4677694f6c77694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a5843497358434a6c646d6c6b5a57356a5a5552705a32567a644677694f6c7769633268684d6a55324f6a63784e7a51775a575a6d4e5463784e7a49305a4459335a6d4a694d6a566a4d4759344e7a51314d6a59794d7a59314e7a526d4e7a49304d6a6c684f4467314f5449324f446c6a4d57466a4e44646c4f44417a5932566349697863496d39775a584a6864476c76626b6c6b584349365843497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4e6349697863496e427962335a6c626d46755932564c6157356b5843493658434a4f525664665230464e525639535431646349697863496e4a6c6358566c633352456157646c63335263496a7063496e4e6f595449314e6a706d4d445a6c4e5755314d474a695a4745354f544533596a4e6d5a47466b4f4755794e7a637a4e7a41324f544e6d4e446c685a6d4d7a4d7a6c6c5a574d335a6a63314e4468694d5755314e4445794e5451324e6a6b775843497358434a7a5932686c625746575a584a7a61573975584349364d537863496e4e7664584a6a5a556468625756536233644a5a4677694f6c77694d54646349697863496e4e7664584a6a5a556468625756555a573568626e524c5a586c63496a7063496e6476636d786b5843497358434a3059584a6e5a58524f5957316c6333426859325663496a7063496e427962325263496e307358434a305a573568626e52426458526f62334a7064486c485a57356c636d46306157397558434936584349795843497358434a305a573568626e52426458526f62334a7064486c5462335679593256575a584a7a6157397558434936584349795843497358434a305a573568626e5243615778736157356e556d566a5a576c77644677694f6e7463496d56325a57353052476c6e5a584e305843493658434a7a614745794e545936595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595677694c4677695a585a6c626e524a5a4677694f6c77694e57466a4d5455344d6d4974595451775a43307a4e5441314c5746694e4449745a6a63334e6a59314e324930596a59775843497358434a76645852696233685464484a6c5957314c5a586c63496a7063496d466a59323931626e513664475675595735304c57567564476c30624756745a5735304f6e59784f6e526c626d4675644338794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a6349697863496e526c626d467564454a7062477870626d64545a5846315a57356a5a5677694f6c77694d56776966537863496e526c626d467564456c6b58434936584349794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a4a63496e30694c434a6c646d5675644552705a32567a64434936496e4e6f595449314e6a6f775a5467304d6a6b354f444d7a5a4467314e7a55305a6d45314f444e6c4e4445314d475a684e3251354d544d334e445a694f444e685a57566a4d7a52684d445532597a526a593249314e6a5a684d545577597a4930496977695a585a6c626e524a5a434936496d566b596a4e695a444d7a4c5467325a5445744d324a6d5a4330355a5749794c5759324e325a6d5a474d7a597a6b3259694973496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a395853776959585630614739796158523556485677624755694f6e736959574e6a623356756445463164476876636d6c306555646c626d567959585270623234694f6949784969776961584e7a64575679515856306145646c626d567959585270623234694f6949784969776962575674596d5679633268706345463164476876636d6c306555646c626d567959585270623234694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a6f694d534a394c434a77636d6c325958526c556d566862473148636d467564465a6c636e4e706232357a496a7062585377696447567559573530515856306147397961585235523256755a584a6864476c7662694936657949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694f694979496e3073496e526c626d467564454a7062477870626d6444645852765a6d59694f6e73694d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a4979496a7037496d393164474a7665464e6c6358566c626d4e6c496a6f694d534973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453664475675595735304c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694973496e526c626d46756445463164476876636d6c306555646c626d567959585270623234694f694979496977696447567559573530516d6c7362476c755a314e6c6358566c626d4e6c496a6f694d534a3966583073496d4a31626d52735a565a6c636e4e70623234694f69497949697769593246736247567951574e6a6233567564456c6b496a6f694d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784969776959324673624756795632397961327876595751694f694a7a63476c6d5a6d55364c79396d61584a6c6258566b4c32357a4c33427962325176633245765a3246745a53317a5a584e7a615739754c584e6c636e5a70593255694c434a6c626e52706447786c6257567564465a6c636e4e70623234694f694978496977695a585a68624856686447566b515851694f6949794d4449324c5445784c544179564441774f6a41774f6a417757694973496d563259577831595852706232354a5a47567564476c3065534936496e4e6f595449314e6a706b595759324d5455304d6a51774e5745314d6d4d774f5459354f5452694e5752694f446b354e6d52684e474a684f574a694e5746684f4749345a6a5532596a5934596a59344e574a6a4e5455344e54646a596a4d34496977695a3246745a58427359586c425a47317063334e7062323542624778766432566b496a706d5957787a5a5377695a3246745a58427359586c42646d467062474669624755694f6e527964575573496d6c7a63335668626d4e6c526d5675593255694f6949784969776961584e7a64575679496a6f695a6d6c795a5731315a43316859324e76645735304c584e6c636e5a70593255694c434a745a5731695a584a7a61476c77515856306147397961585235523256755a584a6864476c7662694936496a45694c434a745a5731695a584a7a61476c77525868706333527a496a706d5957787a5a53776962575674596d567963326870634578705a6d566a65574e735a564e305958526c496a6f6954556c5455306c4f52794973496d316c62574a6c636e4e6f615842575a584a7a61573975496a7037496a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694936496a45696653776962335630596d39345132686c5932747762326c7564484d694f6c7437496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453659574e6a62335675644338784d5445784d5445784d5330784d5445784c5451784d5445744f4445784d5330784d5445784d5445784d5445784d54456966537837496d393164474a7665464e6c6358566c626d4e6c496a6f694d434973496d393164474a7665464e30636d56686255746c65534936496d466a59323931626e513659585630614331686458526f62334a7064486b36646a453661584e7a645756794c325a70636d56746457517459574e6a623356756443317a5a584a3261574e6c496e307365794a7664585269623368545a5846315a57356a5a534936496a41694c434a76645852696233685464484a6c5957314c5a586b694f694a6859324e76645735304f6d4631644767745958563061473979615852354f6e59784f6d316c62574a6c636e4e6f615841764d5445784d5445784d5445744d5445784d5330304d5445784c5467784d5445744d5445784d5445784d5445784d5445784c7a49794d6a49794d6a49794c5449794d6a49744e4449794d6930344d6a49794c5449794d6a49794d6a49794d6a49794d694a394c48736962335630596d39345532567864575675593255694f6949784969776962335630596d3934553352795a57467453325635496a6f6959574e6a62335675644470686458526f4c57463164476876636d6c30655470324d5470305a573568626e51764d6a49794d6a49794d6a49744d6a49794d6930304d6a49794c5467794d6a49744d6a49794d6a49794d6a49794d6a49794969776963323931636d4e6c52585a6c626e52456157646c633351694f694a7a614745794e5459364d4755344e4449354f54677a4d3251344e5463314e475a684e54677a5a5451784e54426d5954646b4f54457a4e7a5132596a677a5957566c597a4d30595441314e6d4d3059324e694e545932595445314d474d794e434973496e4e7664584a6a5a5556325a573530535751694f694a6c5a47497a596d517a4d7930344e6d55784c544e695a6d51744f5756694d69316d4e6a646d5a6d526a4d324d354e6d496966563073496e427962335a7063326c76626d6c755a314e305958523163794936626e567362437769635856766447467a496a7037496d31686545466a64476c325a564e6c63334e706232357a496a6f694d794973496d316865454e76626d4e31636e4a6c626e52485957316c5357357a644746755932567a496a6f694d694973496d316865464e3062334a685a3256436558526c63794936496a51774f54596966537769636d56786457567a64456c6b496a6f694d7a4d7a4d7a4d7a4d7a4d744d7a4d7a4d7930304d7a4d7a4c54677a4d7a4d744d7a4d7a4d7a4d7a4d7a4d7a4d7a4d7a49697769636d39735a584d694f6c74644c434a7a5932686c625745694f694a6859324e76645735304c574631644767745a585a705a47567559325574596e56755a47786c4c335978496977696332356863484e6f6233524a5a47567564476c3065534936496e4e6f595449314e6a70684e6d51345a6a426a4f5455334e54466a4d44646b4e7a45784f546c6d5a4745325a6a466a596a55344d7a677959325a6b4f444d304e574d324d546c6c595749784d3245334d5745314d324d794d6d55355954566a4969776963323931636d4e6c53326c755a434936496b3550546c395151556c4558305246545538694c434a7a62335679593256535a575a6c636d56755932567a496a7037496d466b62576c7a63326c76626c4276615735305a584a54626d467763326876644552705a32567a64434936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a446232317461585251636d39765a6c4e6f595449314e694936496d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6a595778735a584a44623235305a586830535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a6a595778735a584a5063475679595852706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c4a6c5a326c7a64484a35556d566a62334a6b553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d4e686247786c636c5276613256755258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a6a595778735a584a556232746c626b703061534936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e686247786c636c527661325675553268684d6a5532496a6f6959574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496d567564476c30624756745a57353055323931636d4e6c52476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a6e5957316c5532567a63326c76626b3933626d567955484a7662325a456157646c633351694f694a7a614745794e54593659574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859534973496e4268615752535a574e6c61584230566d467361575256626e527062434936626e5673624377696348566962476c7a6147566b5547397361574e355532563052476c6e5a584e30496a6f69633268684d6a55324f6d46685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595745694c434a7a593239775a5552705a32567a64434936496e4e6f595449314e6a70685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746684969776964323979624752445958423064584a6c535751694f69497a4d7a4d7a4d7a4d7a4d79307a4d7a4d7a4c54517a4d7a4d744f444d7a4d79307a4d7a4d7a4d7a4d7a4d7a4d7a4d7a4d694c434a3362334a735a4578705a6d566a65574e735a5552705a32567a64434936496e4e6f595449314e6a7068595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668595746685957466859574668496977696432397962475253623364575a584a7a61573975496a6f694d434a394c434a7a64574a7a59334a7063485270623235546447463064584d694f6d353162477773496e5268636d646c6443493665794a6859335270646d565862334a735a45567762324e6f496a6f694e534973496d4e68626d397561574e6862465a6c636e4e706232354a5a434936496a4d7a4d7a4d7a4d7a4d7a4c544d7a4d7a4d744e444d7a4d7930344d7a4d7a4c544d7a4d7a4d7a4d7a4d7a4d7a4d7a4d794973496d4e6864474673623264535a585a7063326c7662694936496a63694c434a6a6147467959574e305a584a44636d566864476c76626c427662476c6a65534936496c425352564e465255524652463950546b785a4969776959323975626d566a64464e6a6233426c5258687761584a6c63304630496a6f694d6a41794e6930784d5330774d6c51774d446f774d6a6f774d466f694c434a6c646d4673645746305a57524264434936496a49774d6a59744d5445744d4446554d6a4d364e546b364e444261496977695a3246745a556c7563335268626d4e6c535751694f6949334e7a63334e7a63334e7930334e7a63334c5451334e7a63744f4463334e7930334e7a63334e7a63334e7a63334e7a63694c434a776247463559574a735a564e305958526c546d46745a584e7759574e6c535751694f6949324e6a59324e6a59324e6930324e6a59324c5451324e6a59744f4459324e6930324e6a59324e6a59324e6a59324e6a59694c434a776247463559574a735a564e305958526c55324e76634755694f694a5453454653525551694c434a7762326c7564475679566d567963326c7662694936496a4d694c434a795a57467362556c6b496a6f695957466859574668595745745957466859533030595746684c546868595745745957466859574668595746685957466849697769636d5668624731546248566e496a6f6963484a765a48566a64476c7662694973496e5268636d646c64454e7359584e7a496a6f695546564354456c4458314253543052565131524a543034694c434a3059584a6e5a58524f5957316c63334268593255694f694a77636d396b496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a305a573568626e52546248566e496a6f6964475675595735304969776964323979624752546248566e496a6f696432397962475169665377696447567559573530515856306147397961585235523256755a584a6864476c7662694936496a49694c434a305a573568626e5243615778736157356e5532567864575675593255694f694978496977696447567559573530535751694f6949794d6a49794d6a49794d6930794d6a49794c5451794d6a49744f4449794d6930794d6a49794d6a49794d6a49794d6a49694c434a32595778705a46567564476c73496a6f694d6a41794e6930784d5330774d6c51774d446f774d546f7a4d466f694c434a3259584a7059573530496a6f6955457842575556535830464554556c5455306c5054694973496e5a6c636d6c6d6157566b51323975626d566a64464e6a6233426c564739725a57354959584e6f496a6f69633268684d6a55324f6a49795a6a68684e4745784f54497a4e544d7a4e47566d5a44417a4e54686a4f544d324d324d795a546b7a597a63354f574a6b4e5751344e446b7a4f446b784f446b354d6d45784d3245334d4452694d44557a4e6a496966513d3d31333a636170616369747944656c7461363a6e756d62657231313a3131313a6175646974526561736f6e363a737472696e673131383a63617061636974792d61646d697373696f6e", + "sha256": "a78250cc70a4da7ce2933e504d1ab4d773746ff4b5a21acd18510d24b412c735" + } +} diff --git a/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py new file mode 100644 index 0000000000..4adf3aa94a --- /dev/null +++ b/services/common-platform-core/src/testFixtures/resources/capacity/test_capacity_admission_vectors.py @@ -0,0 +1,252 @@ +"""Independent capacity-admission/1 corpus consumer. Encoding proof, not runtime authority.""" +import base64 +import copy +import hashlib +import json +import re +import sys +import unicodedata +import unittest +from pathlib import Path + +MAX = 9223372036854775807 +REPOSITORY = Path(__file__).resolve().parents[6] +sys.path.insert(0, str(REPOSITORY / "dev-tools")) + +from evidence_digest import canonical_json_bytes + + +def decimal(value): + if not isinstance(value, str) or not re.fullmatch(r"0|[1-9][0-9]{0,18}", value): + raise ValueError("canonical int64 decimal string required") + result = int(value) + if result > MAX: + raise ValueError("int64 overflow") + return result + + +def segment(value): + if len(value) > 393216: + raise ValueError("segment bound") + return str(len(value)).encode("ascii") + b":" + value + + +def value(kind, payload, present=True): + return segment(kind.encode("ascii")) + (b"1" if present else b"0") + segment(payload) + + +def string(text): + encoded = unicodedata.normalize("NFC", text).encode("utf-8", "strict") + if len(encoded) > 360448: + raise ValueError("string bound") + return value("string", encoded) + + +def number(text): + return value("number", str(decimal(text)).encode("ascii")) + + +def obj(fields): + return value("object", segment(str(len(fields)).encode("ascii")) + b"".join( + segment(key.encode("ascii")) + item for key, item in fields)) + + +def shape(values): + return obj(list(zip(("activeSessions", "concurrentGameInstances", "storageBytes"), + (number(v) for v in values)))) + + +def reject_duplicates(pairs): + result = {} + for key, item in pairs: + if key in result: + raise ValueError("duplicate member") + result[key] = item + return result + + +def reject_nonfinite(token): + raise ValueError("non-finite JSON constant") + + +def evidence(encoded, variant="TENANT_OPERATION"): + raw = base64.b64decode(encoded, validate=True) + if base64.b64encode(raw).decode("ascii") != encoded: + raise ValueError("canonical padded base64 required") + if not 0 < len(raw) <= 262144: + raise ValueError("evidence bound") + parsed = json.loads(raw.decode("utf-8", "strict"), object_pairs_hook=reject_duplicates, + parse_constant=reject_nonfinite) + try: + canonical = canonical_json_bytes(parsed) + except TypeError as error: + raise ValueError("canonical evidence values required") from error + if raw != canonical or parsed["schema"] != "account-auth-evidence-bundle/v1" or parsed["variant"] != variant: + raise ValueError("exact canonical variant required") + tenant = parsed["tenantId"] + cutoff = parsed["authorityTuple"]["tenantBillingCutoff"][tenant] + points = parsed["outboxCheckpoints"] + matching = [point for point in points if point["outboxStreamKey"] == cutoff["outboxStreamKey"]] + if (variant == "TENANT_OPERATION" and len(points) != 1) or len(matching) != 1 or any( + cutoff[k] != matching[0][k] for k in ("outboxStreamKey", "outboxSequence")): + raise ValueError("cutoff checkpoint mismatch") + return encoded + + +def preimage(request, candidate): + context = request["ownerContext"] + if request["ownerService"] == "game-session-service": + variant = "PLAYER_ADMISSION" + owner_fields = [(key, string(context[key])) for key in + ("accountId", "tenantId", "playableStateNamespaceId", "gameInstanceId", + "characterId", "sessionId", "realmId", "requestId", "playableStateScope")] + elif request["ownerService"] == "world-management-service": + variant = "TENANT_OPERATION" + owner_fields = [(key, string(context[key])) for key in + ("tenantId", "operationId", "lifecycleId", "gameInstanceId", "ownerId")] + owner_fields.append(("ownerFence", number(context["ownerFence"]))) + else: + raise ValueError("known owner service required") + fields = [ + ("actionFamilySchemaId", string("capacity-admission")), + ("actionFamilySchemaVersion", string("1")), + ("scope", obj([(key, string(request[key])) for key in ("tenantId", "requestId", "admissionId")])), + ("target", obj([("ownerService", string(request["ownerService"])), + ("targetNamespace", string(request["targetNamespace"])), + ("ownerContext", obj(owner_fields))])), + ("expectedVersion", obj([("admissionAttemptId", string(request["admissionAttemptId"])), + ("capacityRearmFence", number(request["capacityRearmFence"]))])), + ("mutation", obj([("operation", string(candidate.get("operation", request["operation"]))), + ("priorShape", shape(candidate.get("priorShape", request["priorShape"]))), + ("requestedShape", shape(candidate.get("requestedShape", request["requestedShape"]))), + ("accountEvidence", string(evidence(request["canonicalAccountEvidenceBase64"], variant))), + ("capacityDelta", value("absent", b"", False) if candidate["capacityDelta"] is None + else number(candidate["capacityDelta"]))])), + ("auditReason", string("capacity-admission"))] + result = segment(b"mutationDigest/v1") + b"".join(segment(key.encode("ascii")) + item for key, item in fields) + if len(result) > 524288: + raise ValueError("preimage bound") + return result + + +class CapacityAdmissionVectors(unittest.TestCase): + def test_evidence_uses_restricted_jcs_bytes(self): + # UTF-16 ordering places the supplementary key before U+E000, unlike code-point sorting. + value = {"\ue000": "bmp", "\U00010000": "supplementary"} + self.assertEqual(canonical_json_bytes(value), + '{"\U00010000":"supplementary","\ue000":"bmp"}'.encode("utf-8")) + + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + parsed = json.loads(base64.b64decode(corpus["request"]["canonicalAccountEvidenceBase64"])) + parsed["fractional"] = 1.0 + noncanonical_numeric = json.dumps(parsed, sort_keys=True, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + encoded = base64.b64encode(noncanonical_numeric).decode("ascii") + with self.assertRaisesRegex(ValueError, "canonical evidence values"): + evidence(encoded) + + parsed.pop("fractional") + parsed["\ue000"] = "bmp" + parsed["\U00010000"] = "supplementary" + codepoint_ordered = json.dumps(parsed, sort_keys=True, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + encoded = base64.b64encode(codepoint_ordered).decode("ascii") + with self.assertRaisesRegex(ValueError, "exact canonical variant"): + evidence(encoded) + + def test_shared_golden_preimages_and_digests(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + digests = [] + for candidate in corpus["vectors"]: + with self.subTest(candidate["name"]): + encoded = preimage(corpus["request"], candidate) + self.assertEqual(encoded.hex(), candidate["preimageHex"]) + digest = hashlib.sha256(encoded).hexdigest() + self.assertEqual(digest, candidate["sha256"]) + digests.append(digest) + self.assertNotEqual(digests[0], digests[1]) + + def test_player_golden_preimage_and_each_player_identity(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + request, candidate = corpus["playerRequest"], corpus["playerVector"] + encoded_evidence = request["canonicalAccountEvidenceBase64"] + decoded_evidence = json.loads( + base64.b64decode(evidence(encoded_evidence, "PLAYER_ADMISSION"))) + self.assertEqual(decoded_evidence["bundleVersion"], "2") + self.assertNotIn("verifiedConnectScopeId", decoded_evidence) + scope_hash = "sha256:" + hashlib.sha256(b"controlled-scope").hexdigest() + self.assertEqual(decoded_evidence["verifiedConnectScopeTokenHash"], scope_hash) + snapshot = copy.deepcopy(decoded_evidence) + for key in ("snapshotIdentity", "requestId", "evaluatedAt", "evaluationIdentity"): + snapshot.pop(key) + snapshot_identity = "sha256:" + hashlib.sha256( + canonical_json_bytes(snapshot)).hexdigest() + self.assertEqual(decoded_evidence["snapshotIdentity"], snapshot_identity) + evaluation = { + "snapshotIdentity": snapshot_identity, + "requestId": decoded_evidence["requestId"], + "callerWorkload": decoded_evidence["callerWorkload"], + "evaluatedAt": decoded_evidence["evaluatedAt"], + } + evaluation_identity = "sha256:" + hashlib.sha256( + canonical_json_bytes(evaluation)).hexdigest() + self.assertEqual(decoded_evidence["evaluationIdentity"], evaluation_identity) + context_ids = [item for key, item in request["ownerContext"].items() if key.endswith("Id")] + self.assertEqual(len(context_ids), len(set(context_ids))) + encoded = preimage(request, candidate) + self.assertEqual(encoded.hex(), candidate["preimageHex"]) + self.assertEqual(hashlib.sha256(encoded).hexdigest(), candidate["sha256"]) + for key in ("characterId", "sessionId"): + with self.subTest(key): + changed = copy.deepcopy(request) + changed["ownerContext"][key] = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb" + self.assertNotEqual(hashlib.sha256(preimage(changed, candidate)).hexdigest(), candidate["sha256"]) + swapped = copy.deepcopy(request) + context = swapped["ownerContext"] + context["characterId"], context["sessionId"] = context["sessionId"], context["characterId"] + self.assertNotEqual(hashlib.sha256(preimage(swapped, candidate)).hexdigest(), candidate["sha256"]) + + def test_rejects_nonzero_unused_base64_pad_bits(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + parsed = json.loads(base64.b64decode(corpus["request"]["canonicalAccountEvidenceBase64"])) + alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + for padding in (1, 2): + # Valid JSON evidence with each padding width isolates the base64 spelling check. + for width in range(3): + parsed["padBitTest"] = "x" * width + raw = json.dumps(parsed, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + canonical = base64.b64encode(raw).decode("ascii") + if canonical.endswith("=" * padding) and not canonical.endswith("=" * (padding + 1)): + break + self.assertEqual(evidence(canonical), canonical) + index = len(canonical) - padding - 1 + alternate = canonical[:index] + alphabet[alphabet.index(canonical[index]) + 1] + canonical[index + 1:] + self.assertEqual(base64.b64decode(alternate, validate=True), raw) + with self.subTest(padding=padding), self.assertRaisesRegex(ValueError, "canonical padded base64"): + evidence(alternate) + + def test_rejected_decimal_candidates(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + for candidate in corpus["rejected"]: + with self.subTest(candidate["name"]), self.assertRaises(ValueError): + decimal(candidate["capacityDelta"]) + + def test_rejected_evidence_candidates(self): + corpus = json.loads(Path(__file__).with_name("capacity-admission-v1-vectors.json").read_text()) + for candidate in corpus["rejectedEvidence"]: + with self.subTest(candidate["name"]), self.assertRaises(ValueError): + evidence(candidate["canonicalAccountEvidenceBase64"]) + parsed = json.loads(base64.b64decode(corpus["request"]["canonicalAccountEvidenceBase64"])) + for token, constant in (("NaN", float("nan")), ("Infinity", float("inf")), + ("-Infinity", float("-inf"))): + with self.subTest(token), self.assertRaisesRegex(ValueError, "non-finite JSON constant"): + parsed["nonFinite"] = constant + raw = json.dumps(parsed, sort_keys=True, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + evidence(base64.b64encode(raw).decode("ascii")) + # Shape/absence and usage expectations are separate from this encoding corpus: + # CapacityAdmissionDigestTest and AccountTenantCapacityOwnerTest invoke their real owners. + + +if __name__ == "__main__": + unittest.main() diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java new file mode 100644 index 0000000000..537c57c303 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -0,0 +1,298 @@ +package net.firedevops.firemud.common.account.capacity; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.StatusProto; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.account.v1.TenantCapacityAdmissionAttempt; +import net.firedevops.firemud.account.v1.TenantCapacityAdmissionCommitment; +import net.firedevops.firemud.account.v1.TenantCapacityPlayerContext; +import net.firedevops.firemud.account.v1.TenantCapacityShape; +import net.firedevops.firemud.account.v1.TenantCapacityWorldContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Operation; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.OwnerContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Shape; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.WorldContext; +import net.firedevops.firemud.shared.v1.ErrorDetail; + +/** Strict bounded content mapping. TLS identity and source authority are never codec inputs. */ +public final class TenantCapacityAdmissionGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 288 * 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = 4096; + public static final long CALL_DEADLINE_SECONDS = 5; + + private static final String FAILURE_MESSAGE = "Tenant capacity commitment did not complete"; + + private TenantCapacityAdmissionGrpcCodec() {} + + public enum Failure { + INVALID_ARGUMENT(Status.Code.INVALID_ARGUMENT), + AUTH_UNAVAILABLE(Status.Code.UNAUTHENTICATED), + PERMISSION_DENIED(Status.Code.PERMISSION_DENIED), + IDEMPOTENCY_CONFLICT(Status.Code.ALREADY_EXISTS), + CAPACITY_ADMISSION_STALE(Status.Code.UNAVAILABLE), + ENTITLEMENT_UNAVAILABLE(Status.Code.UNAVAILABLE), + TENANT_BILLING_BLOCKED(Status.Code.RESOURCE_EXHAUSTED), + CAPACITY_QUOTA_EXCEEDED(Status.Code.RESOURCE_EXHAUSTED); + + private final Status.Code code; + + Failure(Status.Code code) { + this.code = code; + } + + public StatusRuntimeException toStatusException() { + return toStatusException(code); + } + + public StatusRuntimeException toStatusException(Status.Code status) { + if (!matches(status)) throw invalid(); + return StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.value()) + .setMessage(FAILURE_MESSAGE) + .addDetails(Any.pack(detail())) + .build()); + } + + private ErrorDetail detail() { + return ErrorDetail.newBuilder().setCode(name()).setMessage(FAILURE_MESSAGE).build(); + } + + private boolean matches(Status.Code status) { + return status == code + || (this == ENTITLEMENT_UNAVAILABLE && status == Status.Code.FAILED_PRECONDITION); + } + } + + /** Preserve the transport outcome. Accept semantic details only in the closed owner format. */ + public static StatusRuntimeException validateFailure(StatusRuntimeException failure) { + try { + var status = StatusProto.fromThrowable(failure); + if (status == null || status.getDetailsCount() == 0) return failure; + if (status.getDetailsCount() == 1 && status.getSerializedSize() <= MAX_RESPONSE_WIRE_BYTES) { + var detail = status.getDetails(0).unpack(ErrorDetail.class); + var error = Failure.valueOf(detail.getCode()); + if (error.matches(failure.getStatus().getCode()) && error.detail().equals(detail)) + return failure; + } + } catch (InvalidProtocolBufferException | IllegalArgumentException invalidDetail) { + // A malformed detail supplies no owner decision or execution proof. + } + return failure.getStatus().asRuntimeException(); + } + + public static CommitTenantCapacityAdmissionRequest toRequest(Request value) { + value.requireStructurallyValid(); + var attempt = + TenantCapacityAdmissionAttempt.newBuilder() + .addTenantId(value.identity().tenantId().toString()) + .addRequestId(value.identity().requestId().toString()) + .addAdmissionId(value.identity().admissionId().toString()) + .addAdmissionAttemptId(value.admissionAttemptId().toString()) + .addCapacityRearmFence(value.capacityRearmFence()) + .addTargetNamespace(value.targetNamespace()) + .addOperation(value.operation().name()) + .addPriorShape(shape(value.priorShape())) + .addRequestedShape(shape(value.requestedShape())) + .addCanonicalAccountEvidence(ByteString.copyFrom(value.evidence().canonicalBytes())) + .addMutationDigest(value.mutationDigest()); + if (value.context() instanceof PlayerContext player) attempt.addPlayerContext(player(player)); + else attempt.addWorldContext(world((WorldContext) value.context())); + var wire = + CommitTenantCapacityAdmissionRequest.newBuilder() + .addAttempt(attempt) + .setCapacityDelta(value.capacityDelta()) + .build(); + clean(wire, MAX_REQUEST_WIRE_BYTES); + return wire; + } + + public static Request parseRequest(CommitTenantCapacityAdmissionRequest wire) { + clean(wire, MAX_REQUEST_WIRE_BYTES); + if (!wire.hasCapacityDelta() || wire.getCapacityDelta() < 0) throw invalid(); + var attempt = one(wire.getAttemptList()); + clean(attempt, MAX_REQUEST_WIRE_BYTES); + OwnerContext context; + if (attempt.getPlayerContextCount() == 1 && attempt.getWorldContextCount() == 0) + context = player(one(attempt.getPlayerContextList())); + else if (attempt.getWorldContextCount() == 1 && attempt.getPlayerContextCount() == 0) + context = world(one(attempt.getWorldContextList())); + else throw invalid(); + var request = + new Request( + new Identity( + uuid(one(attempt.getTenantIdList())), + uuid(one(attempt.getRequestIdList())), + uuid(one(attempt.getAdmissionIdList()))), + uuid(one(attempt.getAdmissionAttemptIdList())), + one(attempt.getCapacityRearmFenceList()), + one(attempt.getTargetNamespaceList()), + context, + Operation.valueOf(one(attempt.getOperationList())), + shape(one(attempt.getPriorShapeList())), + shape(one(attempt.getRequestedShapeList())), + Evidence.parse( + one(attempt.getCanonicalAccountEvidenceList()).toByteArray(), context.owner()), + wire.getCapacityDelta(), + one(attempt.getMutationDigestList())); + request.requireStructurallyValid(); + return request; + } + + public static CommitTenantCapacityAdmissionResponse toResponse(Request request, Result result) { + result.requireBinding(request); + var wire = + CommitTenantCapacityAdmissionResponse.newBuilder() + .addCommitment( + TenantCapacityAdmissionCommitment.newBuilder() + .addTenantId(result.identity().tenantId().toString()) + .addRequestId(result.identity().requestId().toString()) + .addAdmissionId(result.identity().admissionId().toString()) + .addAdmissionAttemptId(result.admissionAttemptId().toString()) + .addCapacityRearmFence(result.capacityRearmFence()) + .addMutationDigest(result.mutationDigest()) + .addReservationId(result.reservationId().toString()) + .addReservationFence(result.reservationFence()) + .addExpiresAt(result.expiresAt().toString()) + .addState(result.state().name()) + .addSnapshotIdentity(result.snapshotIdentity()) + .addEvaluationIdentity(result.evaluationIdentity())) + .build(); + clean(wire, MAX_RESPONSE_WIRE_BYTES); + return wire; + } + + public static Result requireResponse( + Request request, CommitTenantCapacityAdmissionResponse wire) { + clean(wire, MAX_RESPONSE_WIRE_BYTES); + var result = one(wire.getCommitmentList()); + clean(result, MAX_RESPONSE_WIRE_BYTES); + String expires = one(result.getExpiresAtList()); + Instant instant; + try { + instant = Instant.parse(expires); + } catch (java.time.format.DateTimeParseException malformed) { + throw invalid(); + } + if (!instant.toString().equals(expires)) throw invalid(); + var parsed = + new Result( + new Identity( + uuid(one(result.getTenantIdList())), + uuid(one(result.getRequestIdList())), + uuid(one(result.getAdmissionIdList()))), + uuid(one(result.getAdmissionAttemptIdList())), + one(result.getCapacityRearmFenceList()), + one(result.getMutationDigestList()), + uuid(one(result.getReservationIdList())), + one(result.getReservationFenceList()), + instant, + State.valueOf(one(result.getStateList())), + one(result.getSnapshotIdentityList()), + one(result.getEvaluationIdentityList())); + parsed.requireBinding(request); + return parsed; + } + + private static TenantCapacityShape shape(Shape value) { + return TenantCapacityShape.newBuilder() + .addActiveSessions(value.activeSessions()) + .addConcurrentGameInstances(value.concurrentGameInstances()) + .addStorageBytes(value.storageBytes()) + .build(); + } + + private static Shape shape(TenantCapacityShape wire) { + clean(wire, 128); + return new Shape( + one(wire.getActiveSessionsList()), + one(wire.getConcurrentGameInstancesList()), + one(wire.getStorageBytesList())); + } + + private static TenantCapacityPlayerContext player(PlayerContext player) { + return TenantCapacityPlayerContext.newBuilder() + .addAccountId(player.accountId().toString()) + .addTenantId(player.tenantId().toString()) + .addPlayableStateNamespaceId(player.playableStateNamespaceId().toString()) + .addGameInstanceId(player.gameInstanceId().toString()) + .addCharacterId(player.characterId().toString()) + .addSessionId(player.sessionId().toString()) + .addRealmId(player.realmId().toString()) + .addRequestId(player.requestId().toString()) + .addPlayableStateScope(player.playableStateScope()) + .build(); + } + + private static PlayerContext player(TenantCapacityPlayerContext wire) { + clean(wire, 1024); + return new PlayerContext( + uuid(one(wire.getAccountIdList())), + uuid(one(wire.getTenantIdList())), + uuid(one(wire.getPlayableStateNamespaceIdList())), + uuid(one(wire.getGameInstanceIdList())), + uuid(one(wire.getCharacterIdList())), + uuid(one(wire.getSessionIdList())), + uuid(one(wire.getRealmIdList())), + uuid(one(wire.getRequestIdList())), + one(wire.getPlayableStateScopeList())); + } + + private static TenantCapacityWorldContext world(WorldContext value) { + return TenantCapacityWorldContext.newBuilder() + .addTenantId(value.tenantId().toString()) + .addOperationId(value.operationId().toString()) + .addLifecycleId(value.lifecycleId().toString()) + .addGameInstanceId(value.gameInstanceId().toString()) + .addOwnerId(value.ownerId().toString()) + .addOwnerFence(value.ownerFence()) + .build(); + } + + private static WorldContext world(TenantCapacityWorldContext wire) { + clean(wire, 1024); + return new WorldContext( + uuid(one(wire.getTenantIdList())), + uuid(one(wire.getOperationIdList())), + uuid(one(wire.getLifecycleIdList())), + uuid(one(wire.getGameInstanceIdList())), + uuid(one(wire.getOwnerIdList())), + one(wire.getOwnerFenceList())); + } + + private static UUID uuid(String raw) { + UUID parsed = UUID.fromString(raw); + if (!parsed.toString().equals(raw)) throw invalid(); + return TenantCapacityAdmission.uuid(parsed); + } + + private static T one(List values) { + if (values.size() != 1) throw invalid(); + return values.getFirst(); + } + + private static void clean(Message message, int maximum) { + if (message == null + || message.getSerializedSize() > maximum + || !message.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact bounded capacity protobuf required"); + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java new file mode 100644 index 0000000000..bea9dda822 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -0,0 +1,205 @@ +package net.firedevops.firemud.common.account.capacity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.Any; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class TenantCapacityAdmissionGrpcCodecTest { + @Test + void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { + for (var failure : Failure.values()) { + var canonical = failure.toStatusException(); + assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(canonical)).isSameAs(canonical); + } + var deadline = Status.DEADLINE_EXCEEDED.asRuntimeException(); + assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(deadline)).isSameAs(deadline); + var claimedFence = + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(Status.Code.UNAVAILABLE.value()) + .addDetails(Any.pack(ErrorDetail.newBuilder().setCode("FENCE_REJECTED").build())) + .build()); + var verified = TenantCapacityAdmissionGrpcCodec.validateFailure(claimedFence); + assertThat(verified.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(StatusProto.fromThrowable(verified).getDetailsList()).isEmpty(); + } + + @Test + void exactBothAlternativesRoundTripWithCompleteBundleAndReservationBinding() { + for (Request request : + List.of( + CapacityAdmissionTestFixture.playerRequest(), + CapacityAdmissionTestFixture.worldRequest(17L))) { + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + assertThat(wire.hasCapacityDelta()).isTrue(); + assertThat(TenantCapacityAdmissionGrpcCodec.parseRequest(wire)).isEqualTo(request); + Result result = result(request); + assertThat( + TenantCapacityAdmissionGrpcCodec.requireResponse( + request, TenantCapacityAdmissionGrpcCodec.toResponse(request, result))) + .isEqualTo(result); + } + } + + @Test + void nonCreatingEvidenceRoundTripsWithoutChangingAnyCanonicalBytes() { + Request request = CapacityAdmissionTestFixture.playerRequest(false); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + var parsed = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + assertThat(wire.getAttempt(0).getCanonicalAccountEvidence(0).toByteArray()) + .containsExactly(request.evidence().canonicalBytes()); + assertThat(parsed).isEqualTo(request); + assertThat(parsed.evidence().canonicalBytes()) + .containsExactly(request.evidence().canonicalBytes()); + assertThat(parsed.evidence().permitsCreation()).isFalse(); + assertThat(TenantCapacityAdmissionGrpcCodec.toRequest(parsed).toByteArray()) + .containsExactly(wire.toByteArray()); + parsed.requireStructurallyValid(); + assertThatThrownBy(parsed::requireCommittable).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void absentNegativeDuplicateUnknownAndMixedCallerContextFailBeforeCommit() { + Request request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(999, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var world = + TenantCapacityAdmissionGrpcCodec.toRequest(CapacityAdmissionTestFixture.worldRequest(17L)); + for (var bad : + List.of( + wire.toBuilder().clearCapacityDelta().build(), + wire.toBuilder().setCapacityDelta(-1).build(), + wire.toBuilder().addAttempt(wire.getAttempt(0)).build(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setAttempt( + 0, + wire.getAttempt(0).toBuilder() + .addWorldContext(world.getAttempt(0).getWorldContext(0))) + .build(), + wire.toBuilder() + .setAttempt(0, wire.getAttempt(0).toBuilder().addCapacityRearmFence(1)) + .build(), + wire.toBuilder() + .setAttempt( + 0, + wire.getAttempt(0).toBuilder() + .setPlayerContext( + 0, + wire.getAttempt(0).getPlayerContext(0).toBuilder() + .addSessionId( + wire.getAttempt(0).getPlayerContext(0).getSessionId(0)))) + .build(), + wire.toBuilder() + .setAttempt( + 0, + wire.getAttempt(0).toBuilder() + .setPlayerContext( + 0, + wire.getAttempt(0).getPlayerContext(0).toBuilder() + .setUnknownFields(unknown))) + .build())) { + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.parseRequest(bad)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void presentZeroSurvivesOnlyExplicitNonExpandingClassification() { + Request base = CapacityAdmissionTestFixture.worldRequest(0L); + Request zero = + new Request( + base.identity(), + base.admissionAttemptId(), + base.capacityRearmFence(), + base.targetNamespace(), + base.context(), + TenantCapacityAdmission.Operation.NON_EXPANDING_RECOVERY, + new TenantCapacityAdmission.Shape(0, 1, 0), + new TenantCapacityAdmission.Shape(0, 1, 0), + base.evidence(), + 0L, + null) + .withDigest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(zero); + assertThat(wire.hasCapacityDelta()).isTrue(); + assertThat(TenantCapacityAdmissionGrpcCodec.parseRequest(wire).capacityDelta()).isZero(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRequest(base)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void responseCannotSubstituteAttemptDigestFenceOrEvidenceIdentity() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); + for (var bad : + List.of( + wire.toBuilder().addCommitment(wire.getCommitment(0)).build(), + wire.toBuilder() + .setCommitment(0, wire.getCommitment(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(), + wire.toBuilder() + .setCommitment( + 0, wire.getCommitment(0).toBuilder().setMutationDigest(0, "b".repeat(64))) + .build(), + wire.toBuilder() + .setCommitment( + 0, + wire.getCommitment(0).toBuilder() + .setEvaluationIdentity(0, "sha256:" + "b".repeat(64))) + .build(), + wire.toBuilder() + .setCommitment( + 0, + wire.getCommitment(0).toBuilder() + .setExpiresAt(0, request.evidence().expiresAt().plusSeconds(1).toString())) + .build())) { + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(request, bad)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void malformedAndOutOfRangeResponseExpiryUseTheInvalidResponseException() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); + for (String expires : + List.of("not-an-instant", "2026-99-02T00:00:00Z", "+1000000001-01-01T00:00:00Z")) { + var malformed = + wire.toBuilder() + .setCommitment(0, wire.getCommitment(0).toBuilder().setExpiresAt(0, expires)) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(request, malformed)) + .isExactlyInstanceOf(IllegalArgumentException.class); + } + } + + private static Result result(Request request) { + return new Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.fromString("b2222222-2222-4222-8222-222222222222"), + 1, + CapacityAdmissionTestFixture.NOW.plusSeconds(15), + State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + } +} diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 359dea0f2b..e7cbb9b5b3 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -1,17 +1,21 @@ package net.firedevops.firemud.test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.List; import java.util.Set; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeRequest; @@ -43,6 +47,9 @@ class AccountRuntimeStubServerCompatibilityTest { "RequestEmailVerification", "VerifyEmail", "VerifyEmailLoginOtp"); + // Private runtime mutations require their actual bounded mTLS owner, never fake authority. + private static final Set UNIMPLEMENTED_RUNTIME_METHODS = + Set.of("CommitTenantCapacityAdmission"); @Test void accountServiceMethodSetIsFullyCategorized() { @@ -53,15 +60,40 @@ void accountServiceMethodSetIsFullyCategorized() { assertThat(actualMethods) .containsExactlyInAnyOrderElementsOf( - java.util.stream.Stream.concat( + java.util.stream.Stream.of( AccountRuntimeStubServer.implementedRuntimeMethodNames().stream(), - NON_RUNTIME_METHODS.stream()) + NON_RUNTIME_METHODS.stream(), + UNIMPLEMENTED_RUNTIME_METHODS.stream()) + .flatMap(java.util.function.Function.identity()) .collect(java.util.stream.Collectors.toSet())); assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) .contains("IssueDirectTextConnectScope", "JoinPublicProductionMembership"); } + @Test + void privateCapacityMutationRemainsUnimplementedOnSharedFakeRuntimeServer() throws Exception { + assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) + .doesNotContain("CommitTenantCapacityAdmission"); + try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); + try { + var stub = AccountServiceGrpc.newBlockingStub(channel); + assertThatThrownBy( + () -> + stub.commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest.getDefaultInstance())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNIMPLEMENTED)); + } finally { + channel.shutdownNow(); + } + } + } + @Test void joinMembershipVersionsRemainUnsignedOnTheirExistingFieldNumbers() { Descriptor descriptor = From e92bf11c7e8346c50f3966e82f7681dfe0d29b45 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:51:07 +1300 Subject: [PATCH 51/52] Bound Account capacity contention retries and type retention failure --- .../player-access-and-session.md | 2 + ...ccountPlayerAdmissionEntitlementOwner.java | 11 +++- .../service/AccountTenantCapacityOwner.java | 48 ++++++++++++++--- ...ntPlayerAdmissionEntitlementOwnerTest.java | 14 +++++ .../AccountTenantCapacityOwnerTest.java | 51 ++++++++++++++++--- .../capacity/CapacityAdmissionDigestTest.java | 34 +++++++++++++ 6 files changed, 145 insertions(+), 15 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index c0a6812d65..87dd792aa8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,6 +32,8 @@ The [shared capacity-admission/v1 schema](../../../services/common-platform-core 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. +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 requires 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 and activation holds. ### Controlled player-admission transport composition diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index c8b384f56e..e918d69b5e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -28,6 +28,8 @@ import net.firedevops.firemud.accountservice.repository.AccountSubscriptionIntentRepository.FenceRejectedException; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; @@ -35,6 +37,7 @@ import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; @@ -644,8 +647,12 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( time); // Retain only inside this actual evaluator's final source transaction. A supplied bundle // cannot register itself as capacity authority, and commit failure returns no evidence. - new net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository(dsl) - .retainPlayerEvaluation(evidence); + try { + new AccountTenantCapacityRepository(dsl).retainPlayerEvaluation(evidence); + } catch (CapacityException retentionFailure) { + if (retentionFailure.code() == Failure.ENTITLEMENT_UNAVAILABLE) throw unavailable(); + throw retentionFailure; + } return evidence; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 87cb05708a..b889ad2d71 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -8,6 +8,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Context; +import io.grpc.Deadline; import java.sql.Connection; import java.sql.SQLException; import java.time.Clock; @@ -15,6 +16,8 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; @@ -49,6 +52,10 @@ value = "EI_EXPOSE_REP2", justification = "Private Account owner collaborators.") public final class AccountTenantCapacityOwner { + private static final int TRANSACTION_TIMEOUT_SECONDS = 5; + private static final int MAX_SERIALIZATION_ATTEMPTS = 4; + private static final long INITIAL_RETRY_DELAY_MILLIS = 5; + private final DSLContext dsl; private final AccountRepository accounts; private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships; @@ -81,7 +88,7 @@ public AccountTenantCapacityOwner( transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - transaction.setTimeout(5); + transaction.setTimeout(TRANSACTION_TIMEOUT_SECONDS); } public Result commit(Request request, String authenticatedCaller) { @@ -275,14 +282,41 @@ static void requireClaim(Record row, UUID owner, long fence, Instant now) { } private Result commitWithFreshSnapshot(Supplier action) { + Context caller = Context.current(); + Deadline localDeadline = Deadline.after(TRANSACTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + Deadline incoming = caller.getDeadline(); + Deadline retryDeadline = incoming == null ? localDeadline : localDeadline.minimum(incoming); + if (caller.isCancelled() || retryDeadline.isExpired()) throw unavailable(); + for (int attempt = 1; ; attempt++) { + try { + return inTransaction( + () -> { + if (caller.isCancelled() || retryDeadline.isExpired()) throw unavailable(); + return action.get(); + }); + } catch (RuntimeException failure) { + // A PostgreSQL serialization failure rolls back the whole transaction. Retry outside + // that transaction so a concurrent original can become exact replay or conflict. + if (attempt >= MAX_SERIALIZATION_ATTEMPTS + || !serializationFailure(failure) + || !waitForFreshSnapshot(caller, retryDeadline, attempt)) throw failure; + } + } + } + + private static boolean waitForFreshSnapshot(Context caller, Deadline deadline, int attempt) { + long minimumDelay = INITIAL_RETRY_DELAY_MILLIS << (attempt - 1); + long delay = ThreadLocalRandom.current().nextLong(minimumDelay, 2 * minimumDelay); + if (caller.isCancelled() || deadline.timeRemaining(TimeUnit.MILLISECONDS) <= delay) { + return false; + } try { - return inTransaction(action); - } catch (RuntimeException failure) { - // PostgreSQL has rolled back this serialization failure. The whole next transaction needs - // a new snapshot so a concurrent first attempt can become exact replay or conflict. - if (!serializationFailure(failure) || Context.current().isCancelled()) throw failure; - return inTransaction(action); + TimeUnit.MILLISECONDS.sleep(delay); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return false; } + return !caller.isCancelled() && !deadline.isExpired(); } private static boolean serializationFailure(RuntimeException failure) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index 28f9af32c8..703e8bf61e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -180,6 +180,18 @@ void capacityRetentionFailureRollsBackSourceCaptureWithoutReturningEvidence() th assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); } + @Test + void missingCapacityRetentionReadbackRollsBackAsSourceUnavailable() throws Exception { + Fixture f = new Fixture(true); + f.missingCapacityRetentionReadback = true; + assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) + .isInstanceOf(AccountPlayerAdmissionEntitlementOwner.SourceUnavailableException.class) + .hasMessage("ENTITLEMENT_UNAVAILABLE: current player source evidence is unavailable") + .hasNoCause(); + assertThat(f.retainedCapacity).isEmpty(); + assertThat(f.transactions.events).containsExactly("begin", "commit", "begin", "rollback"); + } + @Test void existingMembershipCarriesItsIndependentVersionAndPositiveCheckpoint() throws Exception { Fixture f = new Fixture(true); @@ -959,6 +971,7 @@ private static final class Fixture { private final RecordingTransactions transactions = new RecordingTransactions(); private final Map retainedCapacity = new LinkedHashMap<>(); private boolean refuseCapacityRetention; + private boolean missingCapacityRetentionReadback; private final java.util.concurrent.atomic.AtomicReference time = new java.util.concurrent.atomic.AtomicReference<>(NOW); private final FreshTenantCreationEvidence source = source(); @@ -1056,6 +1069,7 @@ private Fixture(boolean exists, String stateScope) throws Exception { if (refuseCapacityRetention) throw new DataAccessException("Controlled capacity retention refusal"); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + if (missingCapacityRetentionReadback) return 0; Object[] values = (Object[]) invocation.getRawArguments()[1]; String id = (String) values[0]; if (retainedCapacity.containsKey(id)) return 0; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 58751d1b71..175f517db5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -12,6 +12,7 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import io.grpc.Context; import java.sql.Connection; import java.sql.SQLException; import java.time.Clock; @@ -130,22 +131,60 @@ void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() } @Test - void serializationFailureRetriesOnceAndReplaysInAFreshTransaction() throws Exception { + void repeatedSerializationFailuresRetryAndReplayInAFreshTransaction() throws Exception { var f = new Fixture(true); - var aborted = - new org.jooq.exception.DataAccessException( - "concurrent reservation", new SQLException("serialization failure", "40001")); + var aborted = serializationFailure(); when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) - .thenThrow(aborted) + .thenThrow(aborted, aborted) .thenReturn(Optional.of(new Account())); assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload()).reservationId()) .isEqualTo(f.reservation); - verify(f.accounts, times(2)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verify(f.accounts, times(3)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); verifyNoInteractions(f.memberships, f.issuances, f.scopes); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void repeatedSerializationFailuresStopAtTheAttemptLimit() throws Exception { + var f = new Fixture(true); + var aborted = serializationFailure(); + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenThrow(aborted); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isSameAs(aborted); + verify(f.accounts, times(4)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void cancelledCallDoesNotRetryAnAbortedTransaction() throws Exception { + var f = new Fixture(true); + var aborted = serializationFailure(); + try (var caller = Context.current().withCancellation()) { + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenAnswer( + invocation -> { + caller.cancel(null); + throw aborted; + }); + + caller.run( + () -> + assertThatThrownBy( + () -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isSameAs(aborted)); + } + verify(f.accounts).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + private static org.jooq.exception.DataAccessException serializationFailure() { + return new org.jooq.exception.DataAccessException( + "concurrent reservation", new SQLException("serialization failure", "40001")); + } + @Test void changedAttemptOrPayloadOrFenceConflictsBeforeAnyCurrentSourceOrUsageMutation() throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index 64cb4d0d06..db3c2e513b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -275,6 +275,40 @@ void nonCreatingEvidenceIsValidContentButCannotAuthorizeExecution() { } } + @Test + void boundReleasedAndQuarantinedResultsCannotAuthorizeOriginalExecution() { + Request request = CapacityAdmissionTestFixture.playerRequest(); + for (var state : + List.of( + TenantCapacityAdmission.State.RELEASED, + TenantCapacityAdmission.State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION)) { + var reservation = + new TenantCapacityAdmission.Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + UUID.fromString("b1111111-1111-4111-8111-111111111111"), + 1, + request.evidence().expiresAt(), + state, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + reservation.requireBinding(request); + assertThatThrownBy( + () -> + new OriginalNewCapacityExecution( + request, + reservation, + request.identity().admissionId(), + "sha256:" + "a".repeat(64), + "owner-1", + 1)) + .as(state.name()) + .isInstanceOf(IllegalArgumentException.class); + } + } + private static Request playerMutation(Request base, Long delta, Shape requested, String digest) { return new Request( base.identity(), From 2616596afa0a38ad3126313a50865f91babb4efc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:28:40 +1300 Subject: [PATCH 52/52] Keep capacity replay lock-free and qualify every execution operation --- .../AccountTenantCapacityRepository.java | 17 +++++++---- .../service/AccountTenantCapacityOwner.java | 8 +++-- .../AccountTenantCapacityOwnerTest.java | 30 ++++++++++++++++--- .../capacity/TenantCapacityAdmission.java | 2 +- .../capacity/CapacityAdmissionDigestTest.java | 21 +++++++++++++ 5 files changed, 65 insertions(+), 13 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java index 275bc5920a..9fdb6c982d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -28,6 +28,8 @@ value = "EI_EXPOSE_REP2", justification = "Private owner transaction collaborator.") public final class AccountTenantCapacityRepository { + private static final String FIND_RESERVATION = + "SELECT * FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?"; private final DSLContext dsl; public AccountTenantCapacityRepository(DSLContext dsl) { @@ -81,12 +83,17 @@ public void requireRetained(Evidence evidence) { } public Record find(Identity id) { + return find(id, FIND_RESERVATION + " FOR UPDATE"); + } + + /** Exact replay reads the transaction snapshot without taking a mutation lock. */ + public Record findForReplay(Identity id) { + return find(id, FIND_RESERVATION); + } + + private Record find(Identity id, String query) { transaction(); - return dsl.fetchOne( - "SELECT * FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? FOR UPDATE", - id.tenantId(), - id.requestId(), - id.admissionId()); + return dsl.fetchOne(query, id.tenantId(), id.requestId(), id.admissionId()); } public Record usage(Request request) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index b889ad2d71..2a00b3420c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -94,12 +94,14 @@ public AccountTenantCapacityOwner( public Result commit(Request request, String authenticatedCaller) { requireCaller(request, authenticatedCaller); request.requireStructurallyValid(); + if (!(request.context() instanceof PlayerContext)) throw unavailable(); return commitWithFreshSnapshot( () -> { - lockPlayerAccount(request); - Record existing = capacity.find(request.identity()); - // Replay/conflict is resolved before current-source reads and any usage write. + // Exact replay/conflict can linearize at the snapshot read without taking a mutation + // lock. + Record existing = capacity.findForReplay(request.identity()); if (existing != null) return capacity.exact(request, existing); + lockPlayerAccount(request); if (request.capacityRearmFence() != 1) throw conflict(); current(request); requireSupportedShape(request); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 175f517db5..0b811bf47e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.startsWith; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -20,6 +21,7 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; @@ -126,21 +128,29 @@ void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() var result = f.owner.commit(f.request, f.request.evidence().callerWorkload()); assertThat(result.reservationId()).isEqualTo(f.reservation); assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload())).isEqualTo(result); - verifyNoInteractions(f.memberships, f.issuances, f.scopes); + verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } @Test void repeatedSerializationFailuresRetryAndReplayInAFreshTransaction() throws Exception { var f = new Fixture(true); + f.existing = false; var aborted = serializationFailure(); + var abortedAttempts = new AtomicInteger(); when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) - .thenThrow(aborted, aborted) - .thenReturn(Optional.of(new Account())); + .thenAnswer( + invocation -> { + if (abortedAttempts.incrementAndGet() == 2) f.existing = true; + throw aborted; + }); assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload()).reservationId()) .isEqualTo(f.reservation); - verify(f.accounts, times(3)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verify(f.accounts, times(2)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verify(f.dsl, times(3)) + .fetchOne( + startsWith("SELECT * FROM account_tenant_capacity_reservations "), any(Object[].class)); verifyNoInteractions(f.memberships, f.issuances, f.scopes); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } @@ -148,6 +158,7 @@ void repeatedSerializationFailuresRetryAndReplayInAFreshTransaction() throws Exc @Test void repeatedSerializationFailuresStopAtTheAttemptLimit() throws Exception { var f = new Fixture(true); + f.existing = false; var aborted = serializationFailure(); when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) .thenThrow(aborted); @@ -161,6 +172,7 @@ void repeatedSerializationFailuresStopAtTheAttemptLimit() throws Exception { @Test void cancelledCallDoesNotRetryAnAbortedTransaction() throws Exception { var f = new Fixture(true); + f.existing = false; var aborted = serializationFailure(); try (var caller = Context.current().withCancellation()) { when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) @@ -290,6 +302,16 @@ void authenticatedGameSessionCannotSelectWorldOwnerBeforeAccountWork() throws Ex verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); } + @Test + void authenticatedWorldRequestCannotReplayWhileWorldCapacityRemainsHeld() throws Exception { + var f = new Fixture(false, CapacityAdmissionTestFixture.worldRequest(1L)); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.ENTITLEMENT_UNAVAILABLE)); + verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes); + } + @Test void wrongTargetNamespaceOrMissingRequestIsInvalidBeforeAccountWork() throws Exception { var f = new Fixture(false, CapacityAdmissionTestFixture.playerRequest(), "staging"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java index 5da6d9b77a..3376286d64 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmission.java @@ -295,7 +295,7 @@ public Request withDigest() { /** Strong guard for rearm and selected-owner execution; content alone grants no authority. */ public void requireCommittable() { requireStructurallyValid(); - if (operation == Operation.CAPACITY_CREATING && !evidence.permitsCreation()) throw invalid(); + if (!evidence.permitsCreation()) throw invalid(); } /** Account resolves exact replay/conflict and current policy after this content check. */ diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index db3c2e513b..a8f6b0e863 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -275,6 +275,27 @@ void nonCreatingEvidenceIsValidContentButCannotAuthorizeExecution() { } } + @Test + void nonExpandingRecoveryStillRequiresCreationEligibleEvidence() { + Request denied = CapacityAdmissionTestFixture.playerRequest(false); + Request recovery = + new Request( + denied.identity(), + denied.admissionAttemptId(), + denied.capacityRearmFence(), + denied.targetNamespace(), + denied.context(), + Operation.NON_EXPANDING_RECOVERY, + denied.priorShape(), + denied.priorShape(), + denied.evidence(), + 0L, + null) + .withDigest(); + recovery.requireStructurallyValid(); + assertThatThrownBy(recovery::requireCommittable).isInstanceOf(IllegalArgumentException.class); + } + @Test void boundReleasedAndQuarantinedResultsCannotAuthorizeOriginalExecution() { Request request = CapacityAdmissionTestFixture.playerRequest();