diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md
index b131b6fa6b..c8576ba8df 100644
--- a/design/architecture/microservices/account-service/api-contracts.md
+++ b/design/architecture/microservices/account-service/api-contracts.md
@@ -316,6 +316,8 @@ The unregistered `AccountOriginalNewCapacityExecutionReadClient` is the concrete
Only actual immutable final-session/receipt proof maps to `COMMITTED`; only irreversible original-attempt closure maps to `NOT_EXECUTED_AFTER_AUTHORIZATION`. Missing, changed, interrupted or ambiguous evidence stays `INDETERMINATE` through the existing worker, preserving the hold and bounded quarantine policy. Account remains sole capacity transition authority. The read does not register the worker or release from expiry. Serving retirement after positive outcome retention and negative replay from retained SQL CLOSED proof plus its exact persistent Redis tombstone are supported. Retention-before-cleanup ordering in the pre-retention crash window, genuine never-admitted cleanup of the acknowledged PROVISIONAL boundary and runtime teardown/used-capacity retirement are unqualified. The [Game Session read contract](../game-session-service/api-contracts.md#original-new-capacity-execution-read) records the exact owner and transport consequences.
+A separately selected historical read uses the same authenticated Game Session transport and original attempt/reservation selector. Account validates the closed historical receipt and retains it with a distinct proof version. The capacity recovery worker may finalize the original still-held reservation and move its units from held to used exactly once under the existing locked claim. Missing or changed evidence remains indeterminate under the original observation budget. Quarantined reservations retain their existing remediation requirement. Admission, credential confirmation, cleanup, release, rearm and worker registration retain their separate authority boundaries.
+
### Account reader for the original NEW final admission
The credential owner uses an `AccountOriginalNewFinalAdmissionReadClient` callback after issuing the bound credential and before persisting Account's final confirmation. Its concrete `AccountOriginalNewFinalAdmissionGrpcReadClient` is a manually composed, same-namespace mTLS client to Game Session. It sends the immutable original anchors and digests through the closed final-read selector; it never sends the LOGIN JWT or opaque rebind-handle bytes. The callback accepts only an exact, authenticated `COMPLETE` schema-2 readback with matching anchors and valid admission/continuity times, after which Account may activate and confirm the same original issuance. The callback is not wired into the default Account runtime. Without it, final confirmation fails closed; this client does not create an endpoint, admission decision, or public PLAY/LOOK path. The Game Session read contract is described in [Game Session API Contracts](../game-session-service/api-contracts.md#grpc-apis).
diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md
index 9f2863b989..39995f8fe7 100644
--- a/design/architecture/microservices/account-service/runtime-and-data.md
+++ b/design/architecture/microservices/account-service/runtime-and-data.md
@@ -336,14 +336,14 @@ The numeric runtime entitlement endpoint follows the [Account API refusal bounda
Account owns capacity evaluations, reservations, attempt history, recovery evidence, usage and their protected conservation aggregate 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). Evaluation expiry ends admission freshness; it is not an erasure grant. No universal duration, caller-supplied approval flag or tenant setting can replace the finite environment schedule and its privacy/finance approval.
-- Evaluations are purpose-bound authorization evidence. An expired evaluation can become a cleanup candidate only after its declared evidence horizon and every supported retry, replay, restore and investigation horizon end, with no hold or retained reference. References include prior evaluations retained inside immutable rearmed-attempt payloads, not only the current reservation foreign key. Until exact historical reference qualification exists, any retained reservation for the same tenant and owner conservatively blocks that scope's evaluations. Unreferenced non-admitting baselines still require the same policy and hold qualification.
+- Evaluations are purpose-bound authorization evidence. An expired evaluation can become a cleanup candidate only after its declared evidence horizon and every supported retry, replay, restore and investigation horizon end, with no hold or retained reference. References include prior evaluations retained inside immutable rearmed-attempt payloads, not only the current reservation foreign key. A retained reservation conservatively blocks evaluations in the same tenant and owner scope whenever historical reference qualification is incomplete. Unreferenced non-admitting baselines still require the same policy and hold qualification.
- Reservations retain live or recoverable work and the stable outer retry identity. Pending, ambiguous and quarantined work is never age-expired. Finalized or released state alone does not end the supported replay/restore window, prove teardown, or authorize removal of a reservation or its evidence.
- Attempt history and recovery evidence are recovery/reconciliation lineage. All related attempts and owner observations must be terminal, reconciliation complete, and supported restore/replay unable to resurrect a dependency before bounded compaction or erasure is eligible. Compact identities, digests and outcomes must survive every applicable retry/deduplication window; an archive does not replace an online guard.
- Usage and conservation are live resource-accounting state, not expiring event history. Retiring used capacity requires the once-only authoritative teardown transition; absence of an evaluation or an old timestamp cannot decrease either counter. The conservation aggregate adds no deletion or terminal-retirement authority.
Every category's environment entry must name its exact finite maximum duration, purpose, authorized Account roles, subject/tenant export treatment, terminal erasure or minimization action, backup/replica handling and legal holds. Cleanup is owner-local, uses a bounded batch and safe watermark, and fails closed when a required policy, hold, reference or restore input is absent or contradictory. No cross-schema reads, unqualified partition drops or arbitrary age-only deletion are permitted. Restore must retain the applicable evidence and erasure reconciliation before traffic opens.
-Read-only evaluation inspection uses a bounded oldest window and requires the exact environment schedule, current hold snapshot and safe watermark before reporting candidates. The [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the receiving owner, proof and remaining lifecycle work.
+The prepared read-only evaluation inspection reports an oldest bounded window, blocker counts and evidence-byte totals within that window, physical relation size and an explicitly approximate catalog row count. An internal assessment accepts an exact versioned evaluation schedule, current hold snapshot and safe watermark. Its candidate counts cover only unheld and unreferenced sample rows beyond expiry and every applicable horizon. Reference qualification uses the current reservation foreign key and a bounded, complete chain of exact retained rearm attempts. It verifies canonical attempt bytes against their owner, identity, attempt, fence and digest. Missing, malformed or over-budget history retains the scope-wide blocker. Without those inputs the default observation holds candidates. Cleanup, scheduling and receiving registration remain disabled. The [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records executed proof and remaining family-wide lifecycle obligations.
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).
diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md
index b64a9ad431..b89dad038c 100644
--- a/design/architecture/microservices/game-session-service/api-contracts.md
+++ b/design/architecture/microservices/game-session-service/api-contracts.md
@@ -14,6 +14,8 @@ After independent actual-CAS readback and immutable positive outcome retention,
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.
+`ReadHistoricalOriginalNewCapacityFinal` uses the same unregistered Account-only workload boundary and exact original attempt and reservation selector. It returns a distinct positive historical receipt only when one immutable V1065.2 observation binds the exact canonical execution, candidate, final session, and acquiring fence intent with its retained inventory revision, cohort and barrier target. The method reads the retained witness under the existing operation budget. Missing, ambiguous or mismatched proof leaves the original hold indeterminate. The receipt authorizes only Account's accounting settlement of the exact original hold. Admission, cleanup, release, rearm and successor authority remain subject to their own currentness checks.
+
## 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/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md
index f2176ac94b..1c247aabfc 100644
--- a/design/architecture/microservices/game-session-service/runtime-and-data.md
+++ b/design/architecture/microservices/game-session-service/runtime-and-data.md
@@ -14,6 +14,8 @@ A committed transition whose historical receipt lacks the V1063 execution digest
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. PostgreSQL serializes receipt binding with execution status and refuses a negative close for any execution referenced by a retained final receipt. 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 prepared [V1066 logout intent](../../../../services/game-session-service/src/main/resources/db/migration/V1066__original_new_admitted_logout_intent.sql) binds one logout identity to the exact active original NEW generation and its retained FINAL. Its tenant-slot script compares the original committed session and current generation before replacing the serving value with a persistent logout marker and removing the exact local indexes. The bounded recovery owner rereads the retained intent, FINAL and tenant assignment before it observes the exact marker and settled local indexes through Redis `EVALSHA_RO`. The manually composed reader requires the exact admitted-logout script descriptor and verifies the loaded script digest. A valid successor pointer is preserved. A live session, absent marker or contradictory index is insufficient. Protected dispatch, transcript and region settlement, the authenticated terminal receipt and Account usage retirement remain dependent on the admitted teardown owner.
+
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. The resource worker retains both its applicable operation permits while an abandoned connect physically runs and while its returned connection undergoes one asynchronous close attempt. The caller still returns at the deadline. A failed or cancelled Redis close leaves disposal unproved and retains the operation permit. The gauge `original_new_capacity_redis_close_failure_retained_operations` counts affected operations. Investigate the provider failure before a controlled restart, which restores local admission capacity without resolving any retained execution or Account outcome. 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-bound FINAL changes the exact schema-2 COMPLETE payload by requiring `capacityExecutionDigest`. Before registering the receiver against previously populated Coordination Redis, qualify the script's `REQUIRES_CLUSTER_RESET` cutover through the [Coordination reset and recovery gates](../../system-architecture-redis-reset-and-recovery.md#coordination-reset-model). An older COMPLETE payload cannot qualify as a capacity-bound FINAL receipt. Preserve its Account hold and any required durable recovery evidence through the reset qualification.
@@ -42,6 +44,8 @@ V1065 retains the transfer control and per-original receipt families, their immu
V1065.1 retains exact pre-Account origin custody and its bounded observation budget as a separate owner record. The owner records the origin before attempting Account commitment. The call that inserts the SQL origin owns its first physical initialization. The ordinary admission composition refuses an attempt with a retained origin before Account commitment and rechecks under the region lock before authorizing or replaying execution. A later OPEN retry or transfer requires the existing exact persistent marker. Only the exact retained Account decision and independent physical custody can advance the original recovery operation. Transfer retains original origin bytes, physical fencing evidence, and the actual successor in the same installation transaction. Completed-transfer confirmation preserves the captured state and fence receipt and independently verifies current physical custody. If the same successor has since claimed an origin captured as OPEN, confirmation binds the durable successor claim and its current marker to that same completed transfer. Owner movement preserves the original budget and cannot turn missing evidence into a terminal result. The origin and transfer-item relations are retained control state in the next runtime-family catalog epoch. The receiving composition remains unregistered.
+V1066.1 preserves a live origin observation for its issuing custody until the original deadline. An overlapping observation under that custody is refused before consuming another ordinal. A verified successor can take a fresh bounded observation under its newer fence. A callback must match the retained issuing fence, ordinal, deadline and current custody. Earlier permits with no retained issuing fence expire without inventing ownership. A closure-only execution can retain the original selected owner after a completed OPEN-origin transfer when the installed runtime and verified transfer establish current custody. Fresh dispatch continues to require the exact current selected owner. Closure custody alone leaves the Account hold in place.
+
V1065.2 allows the account fence owner to observe the exact physical FINAL before acquiring its SQL fence intent. The owner records an immutable historical receipt only when the same acquisition revalidates the prior no-active fence, inventory revision, and exact original attempt, candidate and frozen cohort. The sequence of the owner's operations establishes ordering without comparing Redis and SQL clocks. Missing, expired or displaced evidence leaves ordering indeterminate and the protective fence can still be established. The receipt neither promotes frozen inventory nor authorizes admission, release, rearm or successor installation.
## Runtime Model
@@ -122,7 +126,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, V1065.0.2, V1065.0.3, V1065.0.4, V1065.0.5, V1065.0.6, V1065.0.7, V1065.0.8, V1065.0.9, V1065.0.10, V1065.1 and V1065.2 installation markers and the actual installed definitions. It excludes only those eighteen 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`. V1065.0.4 serializes final receipts, execution closure, freeze insertion and transfer child enrollment, and seals epoch `13`. V1065.0.5 classifies retained capacity evidence budgets and exact attempt charges before sealing epoch `14`. V1065.0.6 seals epoch `15` after adding exact denial settlement and bounded history. V1065.0.7 classifies the tenant transfer-history budget before sealing epoch `16`. V1065.1 classifies retained pre-Account origin custody and transfer evidence before sealing epoch `17`. V1065.2 retains the Account-fence FINAL observation and seals epoch `18`. 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, V1065.0.3, V1065.0.4, V1065.0.5, V1065.0.6, V1065.0.7, V1065.0.8, V1065.0.9, V1065.0.10, V1065.1, V1065.2, V1066 and V1066.1 installation markers and the actual installed definitions. It excludes only those twenty 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`. V1065.0.4 serializes final receipts, execution closure, freeze insertion and transfer child enrollment, and seals epoch `13`. V1065.0.5 classifies retained capacity evidence budgets and exact attempt charges before sealing epoch `14`. V1065.0.6 seals epoch `15` after adding exact denial settlement and bounded history. V1065.0.7 classifies the tenant transfer-history budget before sealing epoch `16`. V1065.1 adds original capacity origin and transfer custody and seals epoch `17`. V1065.2 adds the retained Account-fence FINAL observation and seals epoch `18`. V1066 adds the retained admitted-logout intent and seals epoch `19`. V1066.1 binds origin observation permits to their issuing custody and guards transferred closure-only construction before sealing epoch `20`. 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/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md
index 950822ba5d..4da81b127d 100644
--- a/design/architecture/system-architecture-authz-route-matrix.md
+++ b/design/architecture/system-architecture-authz-route-matrix.md
@@ -266,6 +266,7 @@ For every first public-production text entry, the target command sequence is `LO
| 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 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). |
+| Game Session Service | `ReadHistoricalOriginalNewCapacityFinal` | `internal_workload` | **Unregistered.** Exact same-namespace Account mTLS workload and original capacity selector. Returns one matching immutable historical FINAL receipt for the original Account hold. |
| 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 0b3793cc91..16ae5dad6b 100644
--- a/design/architecture/system-architecture-authz-route-matrix.yaml
+++ b/design/architecture/system-architecture-authz-route-matrix.yaml
@@ -3233,6 +3233,33 @@ routes:
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; 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: game-session-service
+ route: ReadHistoricalOriginalNewCapacityFinal
+ transport: grpc
+ scope: tenant
+ route_status: target_not_currently_routable
+ classification: internal_workload
+ auth_path: exact_mtls_workload
+ issued_token_state: none
+ accepted_token_profiles: []
+ token_type: none
+ token_issuer: none
+ token_audience: none
+ method_policy: exact_declared_route
+ allowed_callers:
+ any_of: [account-service]
+ mtls_callers:
+ any_of: ["spiffe://firemud/ns/{namespace}/sa/account-service"]
+ tenant_billing_authority_generation_applies: false
+ membership_authority_generation_applies: false
+ end_user_token_required: false
+ caller_context: exact_original_capacity_attempt_and_reservation
+ response_profile: exact_historical_original_final_receipt
+ required_live_checks: [original_attempt_payload_and_digest, reservation_identity_and_fence, original_selected_owner_identity_and_fence]
+ implementation_status:
+ known_drift:
+ - unregistered_bounded_Account_only_historical_read_and_client_prepared
+ - absent_ambiguous_or_mismatched_witness_leaves_original_hold_indeterminate
- 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 6d455957cd..a530c08702 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -66,12 +66,22 @@ 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 separate pre-dispatch recovery receiving slice adds the [Account origin decision](../../architecture/microservices/account-service/runtime-and-data.md) and [Game Session origin custody](../../architecture/microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing) migrations. All eight focused composed cases passed on the earlier isolated source and controlled PostgreSQL/Redis fixture schema in [run 43160841396](https://github.com/benhook1013/FireMUD/actions/runs/43160841396). The receiving source moves that storage into Flyway, seals the new Game Session catalog epoch and removes the fixture schema installation. Local jOOQ generation, affected production and integration-source compilation, 32 focused unit tests, Java formatting and documentation checks pass. The remaining forward-migration and physical composition cases require fresh execution on the receiving source. Nine focused native cases passed on the receiving source for the exact completed transfer and original admission paths. They cover an Account abort after successor installation, refusal of an ordinary replay with retained origin custody, and unchanged successful historical no-origin and exact origin-bound replays. Runtime registration and activation remain held. Historical positive receipt recovery after Account fence intent is tracked separately.
+The separate pre-dispatch recovery receiving slice adds the [Account origin decision](../../architecture/microservices/account-service/runtime-and-data.md) and [Game Session origin custody](../../architecture/microservices/game-session-service/runtime-and-data.md#normal-handoff-future-execution-fencing) migrations. All eight focused composed cases passed on the earlier isolated source and controlled PostgreSQL/Redis fixture schema in [run 43160841396](https://github.com/benhook1013/FireMUD/actions/runs/43160841396). The receiving source moves that storage into Flyway, seals the new Game Session catalog epoch and removes the fixture schema installation. Local jOOQ generation, affected production and integration-source compilation, 32 focused unit tests, Java formatting and documentation checks pass. The remaining forward-migration and physical composition cases require fresh execution on the receiving source. Nine focused native cases passed on the receiving source for the exact completed transfer and original admission paths. They cover an Account abort after successor installation, refusal of an ordinary replay with retained origin custody, and unchanged successful historical no-origin and exact origin-bound replays. Runtime registration and activation remain held.
+
+A separate Account receiving slice uses the [historical FINAL receipt](../../architecture/microservices/game-session-service/api-contracts.md#original-new-capacity-execution-read) to settle the exact still-reserved original through the existing recovery claim. Game Session reads the immutable same-acquisition observation and frozen cohort. Account binds the authenticated receipt to the original request and moves one held unit to used capacity, with exact replay. The frozen binding and Account admission state stay held. A missing or mismatched observation follows the existing bounded indeterminate path. Four focused local PostgreSQL and Redis cases passed, including the Account-to-Game Session mTLS composition after loss of the original admission SQL commit, one-time settlement and replay, preserved ordinary recovery, and refusal of a FINAL delayed until after intent. Seven scoped codec and workload-guard unit cases passed. The controlled trust and source fixtures do not qualify deployed custody. Runtime registration, authority remediation for quarantined holds, cleanup, and activation remain separate.
+
+The downstream normal-handoff inventory qualification slice adds physical PostgreSQL and Redis calibration for two independently prepared capacity origins in one region, both alone and alongside a captured execution that commits during the freeze. The three-execution fixture measures a complete handoff and verifies that loss of the last retained marker leaves the predecessor and transfer receipts intact. The signer and its response delay are controlled. These cases qualify the exercised inventory shapes and fail-closed readback.
+
+The inventory limit remains open. Qualify the largest supported mixed cohort with the actual signer and protected storage boundary, measure complete current verification within the five-second handoff budget, and prove the owner rejects additional admissions beyond that limit while retaining the original identities and evidence. The passive origin receiving composition remains unregistered, and activation depends on this qualification.
The [Account recovery owner](../../architecture/microservices/account-service/runtime-and-data.md) prepares bounded read, exact late positive finalization and durable quarantine. Controlled proof covers late and ambiguous results, saturation and an active owner refusing a transfer before freeze. The handoff retains a single deadline across source selection and installation revalidation. The combined selected Java units passed 135 cases and the shared Python literal corpus passed four. The physical blocked-selection, pre-install revalidation, recovery and quarantine cases were unrun at that checkpoint. Audited Account remediation and deployed source, Redis and transport custody remain activation prerequisites.
At receiving source `037770fe`, the [staged Game Session physical job](https://github.com/benhook1013/FireMUD/actions/runs/43201656649/job/131126337971) passed three exact cases without failures, errors or skips. The verified artifact covers handoff of an already committed original, a real SQL authorization followed by process stop before Redis send, and the 65-original bounded census. This evidence belongs to that source and preserves the separate runtime and teardown holds.
+The first admitted-logout slice retains a hash-only SQL intent for the actual original FINAL and prepares the tenant-slot fence for that exact generation. At source `8bfb090a`, [physical proof 43208527855](https://github.com/benhook1013/FireMUD/actions/runs/43208527855) passed four exact PostgreSQL and Redis cases. They cover intent replay after controlled serving removal, refusal of stale, missing or unauthorized inputs, idempotent Redis logout preserving a successor, and catalog epoch installation. Protected dispatch, transcript and region settlement, the authenticated terminal receipt and the Account decrement remain open.
+
+The `d3aacdf4` source passed five focused local PostgreSQL and Redis cases with no failures or skips. Its read-only recovery case refuses an unchanged live session, an absent marker and a malformed successor pointer. It recovers an exact persistent fence under a Redis identity without write permissions. The four original intent, fence, replay and catalog cases also passed on this carried source.
+
Finalized usage retirement remains unimplemented. The admitted-session teardown owner, [Game Session terminal proof](../../architecture/microservices/game-session-service/runtime-and-data.md#finalized-capacity-usage-retirement), protected receipt transport and [Account conservation proof](../../architecture/microservices/account-service/runtime-and-data.md#finalized-capacity-usage-retirement) remain open. Runtime activation stays held.
The default-registration no-creation proof at base `c8dab91d050082d7c989900b4b2d44d7a812f275`, with [AccountRuntimeEntitlementNoWriteIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java) source SHA-256 `2ee2702944980bc486cae6f9cd74e626085454c4485b5b01987149bc9d199396`, passes five fresh cases without failures, errors or skips. It boots the complete Account application/main policy scan with real Account facade, discovered gRPC service and global certificate interceptor, physical PostgreSQL/Redis and a REQUIRE-mTLS listener; only unrelated Entity/Game Session/Logging Admin clients and mail are mocked. Certificate-authenticated same-namespace Game Session and World numeric requests and exact retries return the protobuf `ENTITLEMENT_UNAVAILABLE` error with no entitlement payload. Wrong-service/cross-namespace certificates and spoofed peer metadata are denied, and no-client-certificate calls fail TLS. The prepared PLAYER_ADMISSION/capacity owner, receiver, repository and recovery beans remain absent. Independent autocommit reads of the same application datasource compare counts and exact JSON/`xmin` images for all five V1040 capacity families after each refusal: their initially empty cohorts remain empty. This proves no durable creation for those requests only; preservation of populated evaluations, usage, reservations, attempt history and recovery evidence is unproved. The combined affected run also passes the separately retained private invoice witness method after a null-safety/canonical-format correction; that dirty witness is a compiled local input, is excluded from this checkpoint, and is not capacity-family preservation proof. Published receiving CI must qualify its own source independently. Retention/erasure, production custody, cleanup and launch/registration holds remain unchanged.
diff --git a/protos/game-session/v1/original_new_capacity_execution_read.proto b/protos/game-session/v1/original_new_capacity_execution_read.proto
index 1ab8247c73..007d0cb1ae 100644
--- a/protos/game-session/v1/original_new_capacity_execution_read.proto
+++ b/protos/game-session/v1/original_new_capacity_execution_read.proto
@@ -9,6 +9,8 @@ import "account/v1/tenant_capacity_admission.proto";
service OriginalNewCapacityExecutionReadService {
rpc ReadOriginalNewCapacityExecution(ReadOriginalNewCapacityExecutionRequest)
returns (ReadOriginalNewCapacityExecutionResponse);
+ rpc ReadHistoricalOriginalNewCapacityFinal(ReadOriginalNewCapacityExecutionRequest)
+ returns (ReadHistoricalOriginalNewCapacityFinalResponse);
}
message ReadOriginalNewCapacityExecutionRequest {
repeated account.v1.CommitTenantCapacityAdmissionRequest attempt = 1;
@@ -28,3 +30,20 @@ message ReadOriginalNewCapacityExecutionResponse {
repeated string current_owner_id = 11;
repeated int64 current_owner_fence = 12;
}
+
+// Historical positive evidence only. Carries no current owner or admission authority.
+message ReadHistoricalOriginalNewCapacityFinalResponse {
+ repeated ReadOriginalNewCapacityExecutionRequest selector = 1;
+ repeated string fence_operation_id = 2;
+ repeated string transition_id = 3;
+ repeated string candidate_digest = 4;
+ repeated string selected_owner_id = 5;
+ repeated int64 selected_owner_fence = 6;
+ repeated bytes canonical_execution = 7;
+ repeated string final_session_sha256 = 8;
+ repeated int64 admission_at_ms = 9;
+ repeated int64 continuity_expires_at_ms = 10;
+ repeated string inventory_snapshot_revision = 11;
+ repeated string cohort_digest = 12;
+ repeated string barrier_target_digest = 13;
+}
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 d377317b1f..c196eb788f 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
@@ -28,7 +28,8 @@ public final class AccountOriginalNewCapacityExecutionReadClient
extends AbstractReloadingBlockingGrpcClient<
OriginalNewCapacityExecutionReadServiceGrpc
.OriginalNewCapacityExecutionReadServiceBlockingStub>
- implements AccountTenantCapacityRecoveryWorker.ExecutionReadClient {
+ implements AccountTenantCapacityRecoveryWorker.ExecutionReadClient,
+ AccountTenantCapacityRecoveryWorker.HistoricalFinalReadClient {
private static final long MAX_READ_MILLIS = 5000;
private final String namespace;
private final String peer;
@@ -64,17 +65,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
- || SessionContext.hasAuthenticatedCallerContext()
- || SessionContext.isInternalService()
- || SessionContext.getServiceName() != null
- || SessionContext.getServiceInstanceId() != null) throw unavailable();
- 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);
+ Deadline rpcDeadline = authorizedDeadline(request, deadline);
var selector = new OriginalNewCapacityExecutionReadGrpcCodec.Selector(request, reservation);
var wire = OriginalNewCapacityExecutionReadGrpcCodec.toRequest(selector);
var response =
@@ -118,6 +109,46 @@ public AccountTenantCapacityRecoveryWorker.Observation readExact(
return observation;
}
+ @Override
+ public AccountTenantCapacityRecoveryWorker.HistoricalObservation readHistoricalFinal(
+ TenantCapacityAdmission.Request request,
+ TenantCapacityAdmission.Result reservation,
+ Instant deadline) {
+ Deadline rpcDeadline = authorizedDeadline(request, deadline);
+ var selector = new OriginalNewCapacityExecutionReadGrpcCodec.Selector(request, reservation);
+ var wire = OriginalNewCapacityExecutionReadGrpcCodec.toRequest(selector);
+ var response =
+ withPublishedInitializedStub(
+ "Historical FINAL read unavailable",
+ stub -> {
+ if (rpcDeadline.isExpired()) throw unavailable();
+ return stub.withDeadline(rpcDeadline)
+ .withMaxOutboundMessageSize(
+ OriginalNewCapacityExecutionReadGrpcCodec.MAX_REQUEST_BYTES)
+ .withMaxInboundMessageSize(
+ OriginalNewCapacityExecutionReadGrpcCodec.MAX_RESPONSE_BYTES)
+ .readHistoricalOriginalNewCapacityFinal(wire);
+ });
+ var receipt =
+ OriginalNewCapacityExecutionReadGrpcCodec.fromHistoricalResponse(selector, response);
+ if (rpcDeadline.isExpired() || !clock.instant().isBefore(deadline)) throw unavailable();
+ return new AccountTenantCapacityRecoveryWorker.HistoricalObservation(peer, receipt);
+ }
+
+ private Deadline authorizedDeadline(TenantCapacityAdmission.Request request, 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
+ || SessionContext.hasAuthenticatedCallerContext()
+ || SessionContext.isInternalService()
+ || SessionContext.getServiceName() != null
+ || SessionContext.getServiceInstanceId() != null) throw unavailable();
+ long millis = Math.min(MAX_READ_MILLIS, Duration.between(clock.instant(), deadline).toMillis());
+ if (millis <= 0) throw unavailable();
+ return maximum.offset(millis - MAX_READ_MILLIS, TimeUnit.MILLISECONDS);
+ }
+
@Override
protected String configuredTarget(ServiceEndpointsProperties endpoints) {
return endpoints.getGameSessionService();
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwner.java
new file mode 100644
index 0000000000..b3cb49bc02
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwner.java
@@ -0,0 +1,539 @@
+package net.firedevops.firemud.accountservice.service;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.time.Instant;
+import java.time.OffsetDateTime;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalLong;
+import java.util.Set;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jspecify.annotations.Nullable;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Unregistered read-only Account-local retention inspection, with no scheduler or endpoint.
+ *
+ *
Evaluation expiry ends admission freshness, not retention. Every retained reservation scope
+ * remains protected, including terminal reservations and earlier rearmed evaluations whose only
+ * historical reference is inside immutable attempt payloads. Expired evaluations outside those
+ * scopes still require the approved environment schedule, replay/restore compatibility and current
+ * governance/hold authority. None of those authorities is implemented by this component. There is
+ * no cleanup operation or policy-approval API here. Existing database UPDATE/DELETE/TRUNCATE guards
+ * remain unchanged and reject physical cleanup.
+ */
+@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Private Account owner collaborator.")
+public final class AccountCapacityEvaluationRetentionInspectionOwner {
+ public static final int MAX_SAMPLE_ROWS = 1000;
+ // At most 8 scopes × 16 reservations × 9 indexed history-key rows are inspected. At most 32
+ // payloads are fetched (16 MiB under the V1040 row-size constraint); sentinels fail closed.
+ private static final int MAX_REFERENCE_SCOPES = 8;
+ private static final int MAX_RESERVATIONS_PER_SCOPE = 16;
+ private static final int MAX_HISTORY_ROWS_PER_SCOPE = 8;
+ private static final int MAX_HISTORY_ROWS_PER_OBSERVATION = 32;
+ private static final int MAX_RETAINED_PAYLOAD_BYTES = 524288;
+
+ public enum Blocker {
+ LIVE_EVALUATION,
+ RETAINED_RESERVATION_SCOPE,
+ POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE,
+ HELD,
+ ABOVE_SAFE_WATERMARK,
+ RETENTION_WINDOW_OPEN
+ }
+
+ /**
+ * Sample counts/bytes are lower bounds, never whole-table cardinality or deletion eligibility.
+ */
+ public record SampleWindow(int rows, long evidenceBytes, Optional oldestEvaluatedAt) {
+ public SampleWindow {
+ Objects.requireNonNull(oldestEvaluatedAt);
+ }
+
+ private SampleWindow include(Instant evaluated, long bytes) {
+ return new SampleWindow(
+ rows + 1,
+ Math.addExact(evidenceBytes, bytes),
+ oldestEvaluatedAt.or(() -> Optional.of(evaluated)));
+ }
+ }
+
+ /**
+ * Physical relation bytes include indexes and TOAST; the catalog row estimate may be unavailable
+ * or stale. Only the oldest bounded sample is inspected. The default observation does not read
+ * evidence payload bytes; a current policy-qualified assessment decodes only bounded attempt
+ * envelopes. Neither identities nor payloads are exposed. Candidate counts authorize no mutation.
+ */
+ public record Observation(
+ Instant observedAt,
+ long totalRelationBytes,
+ OptionalLong estimatedTableRows,
+ int sampledRows,
+ boolean sampleTruncated,
+ @Nullable Blocker governanceBlocker,
+ Map blockers,
+ Optional scheduleVersion,
+ SampleWindow candidates) {
+ public Observation {
+ Objects.requireNonNull(observedAt);
+ Objects.requireNonNull(estimatedTableRows);
+ blockers = Map.copyOf(blockers);
+ Objects.requireNonNull(scheduleVersion);
+ Objects.requireNonNull(candidates);
+ }
+ }
+
+ private final DSLContext dsl;
+ private final TransactionTemplate reads;
+
+ private record Scope(UUID tenantId, String ownerService) {}
+
+ private record ReservationKey(
+ Scope scope,
+ UUID requestId,
+ UUID admissionId,
+ long currentRearmFence,
+ String callerWorkload) {}
+
+ private record HistoryKey(
+ ReservationKey reservation, UUID attemptId, long rearmFence, String mutationDigest) {}
+
+ private record SampledEvaluation(
+ String evaluationIdentity,
+ Scope scope,
+ Instant evaluatedAt,
+ Instant expiresAt,
+ long evidenceBytes,
+ boolean directlyReferenced,
+ boolean scopeReferenced) {}
+
+ private record HistoryQualification(Set references, Set unqualifiedScopes) {}
+
+ public AccountCapacityEvaluationRetentionInspectionOwner(
+ DSLContext dsl, PlatformTransactionManager transactions) {
+ this.dsl = Objects.requireNonNull(dsl);
+ reads = new TransactionTemplate(Objects.requireNonNull(transactions));
+ reads.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+ reads.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
+ reads.setReadOnly(true);
+ reads.setTimeout(5);
+ }
+
+ /** One bounded consistent observation, not a sweep or a claim that the sample is erasable. */
+ public Observation observe(int sampleRows) {
+ return observe(sampleRows, null, null);
+ }
+
+ Observation observe(
+ int sampleRows,
+ AccountCapacityEvaluationRetentionPolicy.@Nullable Schedule schedule,
+ AccountCapacityEvaluationRetentionPolicy.@Nullable Safety safety) {
+ requireBound(sampleRows);
+ return Objects.requireNonNull(
+ reads.execute(status -> readObservation(sampleRows, schedule, safety)));
+ }
+
+ private Observation readObservation(
+ int sampleRows,
+ AccountCapacityEvaluationRetentionPolicy.@Nullable Schedule schedule,
+ AccountCapacityEvaluationRetentionPolicy.@Nullable Safety safety) {
+ Record table =
+ Objects.requireNonNull(
+ dsl.fetchOne(
+ "SELECT transaction_timestamp() AS observed_at, "
+ + "pg_total_relation_size(relation.oid) AS relation_bytes, "
+ + "relation.reltuples::bigint AS estimated_rows "
+ + "FROM pg_class relation WHERE relation.oid = "
+ + "'account_tenant_capacity_evaluations'::regclass"));
+ Instant observedAt =
+ Objects.requireNonNull(table.get("observed_at", OffsetDateTime.class)).toInstant();
+ long relationBytes = Objects.requireNonNull(table.get("relation_bytes", Long.class));
+ long estimate = Objects.requireNonNull(table.get("estimated_rows", Long.class));
+ boolean policyCurrent =
+ AccountCapacityEvaluationRetentionPolicy.current(schedule, safety, observedAt);
+ // The initial sample is one bounded query; identity fields remain private to this inspection.
+ var rows =
+ dsl.fetch(
+ "WITH sample AS MATERIALIZED ("
+ + "SELECT evaluation_identity, tenant_uuid, owner_service, evaluated_at, expires_at, "
+ + "octet_length(canonical_evidence)::bigint AS evidence_bytes "
+ + "FROM account_tenant_capacity_evaluations "
+ + "ORDER BY evaluated_at, evaluation_identity LIMIT ?) "
+ + "SELECT sample.evaluation_identity, sample.tenant_uuid, sample.owner_service, "
+ + "sample.evaluated_at, sample.expires_at, sample.evidence_bytes, "
+ + "EXISTS (SELECT 1 FROM account_tenant_capacity_reservations reservation "
+ + "WHERE reservation.tenant_uuid = sample.tenant_uuid "
+ + "AND reservation.owner_service = sample.owner_service) AS scope_referenced, "
+ + (policyCurrent
+ ? "EXISTS (SELECT 1 FROM account_tenant_capacity_reservations reservation "
+ + "WHERE reservation.tenant_uuid = sample.tenant_uuid "
+ + "AND reservation.owner_service = sample.owner_service "
+ + "AND reservation.evaluation_identity = sample.evaluation_identity) AS directly_referenced "
+ : "FALSE AS directly_referenced ")
+ + "FROM sample ORDER BY sample.evaluated_at, sample.evaluation_identity",
+ sampleRows + 1);
+
+ int count = Math.min(rows.size(), sampleRows);
+ List sampled = new ArrayList<>(count);
+ for (int index = 0; index < count; index++) {
+ Record row = rows.get(index);
+ sampled.add(
+ new SampledEvaluation(
+ row.get("evaluation_identity", String.class),
+ new Scope(row.get("tenant_uuid", UUID.class), row.get("owner_service", String.class)),
+ Objects.requireNonNull(row.get("evaluated_at", OffsetDateTime.class)).toInstant(),
+ Objects.requireNonNull(row.get("expires_at", OffsetDateTime.class)).toInstant(),
+ Objects.requireNonNull(row.get("evidence_bytes", Long.class)),
+ Boolean.TRUE.equals(row.get("directly_referenced", Boolean.class)),
+ Boolean.TRUE.equals(row.get("scope_referenced", Boolean.class))));
+ }
+ HistoryQualification history =
+ policyCurrent ? qualifyHistory(sampled) : new HistoryQualification(Set.of(), Set.of());
+
+ var empty = new SampleWindow(0, 0, Optional.empty());
+ Map windows = new EnumMap<>(Blocker.class);
+ for (Blocker blocker : Blocker.values()) {
+ windows.put(blocker, empty);
+ }
+ SampleWindow candidates = empty;
+ for (int index = 0; index < count; index++) {
+ SampledEvaluation row = sampled.get(index);
+ Boolean referenced;
+ if (!policyCurrent) {
+ // Without current policy and hold inputs, retain the original cheap scope-wide block.
+ referenced = row.scopeReferenced();
+ } else if (row.directlyReferenced()
+ || history.references().contains(row.evaluationIdentity())) {
+ referenced = true;
+ } else if (history.unqualifiedScopes().contains(row.scope())) {
+ // An incomplete or over-limit history scan cannot prove the scope is unreferenced.
+ referenced = true;
+ } else {
+ referenced = false;
+ }
+ var classification =
+ AccountCapacityEvaluationRetentionPolicy.classify(
+ schedule,
+ safety,
+ observedAt,
+ row.evaluationIdentity(),
+ row.evaluatedAt(),
+ row.expiresAt(),
+ referenced);
+ if (classification == AccountCapacityEvaluationRetentionPolicy.Classification.CANDIDATE) {
+ candidates = candidates.include(row.evaluatedAt(), row.evidenceBytes());
+ } else {
+ Blocker blocker = Blocker.valueOf(classification.name());
+ windows.put(
+ blocker,
+ Objects.requireNonNull(windows.get(blocker))
+ .include(row.evaluatedAt(), row.evidenceBytes()));
+ }
+ }
+ Optional version =
+ schedule != null
+ && AccountCapacityEvaluationRetentionPolicy.current(schedule, safety, observedAt)
+ ? Optional.of(schedule.version())
+ : Optional.empty();
+ return new Observation(
+ observedAt,
+ relationBytes,
+ estimate < 0 ? OptionalLong.empty() : OptionalLong.of(estimate),
+ count,
+ rows.size() > sampleRows,
+ version.isPresent() ? null : Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE,
+ windows,
+ version,
+ candidates);
+ }
+
+ private HistoryQualification qualifyHistory(List sampled) {
+ Set requiredScopes = new HashSet<>();
+ for (SampledEvaluation row : sampled) {
+ if (row.scopeReferenced() && !row.directlyReferenced()) requiredScopes.add(row.scope());
+ }
+ if (requiredScopes.isEmpty()) return new HistoryQualification(Set.of(), Set.of());
+
+ List orderedScopes =
+ requiredScopes.stream()
+ .sorted(
+ (left, right) -> {
+ int tenantOrder = left.tenantId().compareTo(right.tenantId());
+ return tenantOrder != 0
+ ? tenantOrder
+ : left.ownerService().compareTo(right.ownerService());
+ })
+ .toList();
+ Set unqualified = new HashSet<>();
+ if (orderedScopes.size() > MAX_REFERENCE_SCOPES) {
+ unqualified.addAll(orderedScopes.subList(MAX_REFERENCE_SCOPES, orderedScopes.size()));
+ orderedScopes = orderedScopes.subList(0, MAX_REFERENCE_SCOPES);
+ }
+
+ // Cap scope enumeration before looking at attempt payloads. The extra row detects overflow.
+ List scopeBindings = new ArrayList<>();
+ for (Scope scope : orderedScopes) {
+ scopeBindings.add(scope.tenantId());
+ scopeBindings.add(scope.ownerService());
+ }
+ String scopeValues = valuesClause(orderedScopes.size(), 2, "uuid", "text");
+ var reservationRows =
+ dsl.fetch(
+ "WITH scopes(tenant_uuid, owner_service) AS (VALUES "
+ + scopeValues
+ + ") SELECT scopes.tenant_uuid, scopes.owner_service, reservation.request_id, "
+ + "reservation.admission_id, reservation.capacity_rearm_fence, reservation.caller_workload "
+ + "FROM scopes CROSS JOIN LATERAL ("
+ + "SELECT request_id, admission_id, capacity_rearm_fence, caller_workload "
+ + "FROM account_tenant_capacity_reservations "
+ + "WHERE tenant_uuid = scopes.tenant_uuid AND owner_service = scopes.owner_service "
+ + "LIMIT "
+ + (MAX_RESERVATIONS_PER_SCOPE + 1)
+ + ") reservation",
+ scopeBindings.toArray());
+ Map> reservations = new HashMap<>();
+ for (Record row : reservationRows) {
+ Scope scope =
+ new Scope(row.get("tenant_uuid", UUID.class), row.get("owner_service", String.class));
+ reservations
+ .computeIfAbsent(scope, ignored -> new ArrayList<>())
+ .add(
+ new ReservationKey(
+ scope,
+ row.get("request_id", UUID.class),
+ row.get("admission_id", UUID.class),
+ Objects.requireNonNull(row.get("capacity_rearm_fence", Long.class)),
+ row.get("caller_workload", String.class)));
+ }
+ for (Scope scope : orderedScopes) {
+ List scopeReservations = reservations.getOrDefault(scope, List.of());
+ if (scopeReservations.size() > MAX_RESERVATIONS_PER_SCOPE) {
+ unqualified.add(scope);
+ reservations.remove(scope);
+ }
+ }
+ List qualifiedReservations =
+ reservations.values().stream().flatMap(List::stream).toList();
+ if (qualifiedReservations.isEmpty())
+ return new HistoryQualification(Set.of(), Set.copyOf(unqualified));
+
+ List reservationBindings = new ArrayList<>();
+ for (ReservationKey reservation : qualifiedReservations) {
+ reservationBindings.add(reservation.scope().tenantId());
+ reservationBindings.add(reservation.scope().ownerService());
+ reservationBindings.add(reservation.requestId());
+ reservationBindings.add(reservation.admissionId());
+ reservationBindings.add(reservation.callerWorkload());
+ }
+ String reservationValues =
+ valuesClause(qualifiedReservations.size(), 5, "uuid", "text", "uuid", "uuid", "text");
+ var historyKeys =
+ dsl.fetch(
+ "WITH reservations(tenant_uuid, owner_service, request_id, admission_id, caller_workload) AS (VALUES "
+ + reservationValues
+ + "), scopes AS (SELECT DISTINCT tenant_uuid, owner_service FROM reservations) "
+ + "SELECT histories.tenant_uuid, histories.owner_service, histories.request_id, "
+ + "histories.admission_id, histories.caller_workload, histories.admission_attempt_id, histories.capacity_rearm_fence, "
+ + "histories.mutation_digest, histories.payload_bytes FROM scopes CROSS JOIN LATERAL ("
+ + "SELECT bounded_history.tenant_uuid, bounded_history.owner_service, bounded_history.request_id, "
+ + "bounded_history.admission_id, bounded_history.caller_workload, bounded_history.admission_attempt_id, "
+ + "bounded_history.capacity_rearm_fence, bounded_history.mutation_digest, "
+ + "bounded_history.payload_bytes FROM (SELECT * FROM reservations "
+ + "WHERE tenant_uuid = scopes.tenant_uuid AND owner_service = scopes.owner_service) reservations "
+ + "CROSS JOIN LATERAL ("
+ + "SELECT history.tenant_uuid, reservations.owner_service, history.request_id, "
+ + "history.admission_id, reservations.caller_workload, history.admission_attempt_id, history.capacity_rearm_fence, "
+ + "history.mutation_digest, octet_length(history.canonical_payload)::bigint AS payload_bytes "
+ + "FROM account_tenant_capacity_attempt_history history "
+ + "WHERE history.tenant_uuid = reservations.tenant_uuid "
+ + "AND history.request_id = reservations.request_id "
+ + "AND history.admission_id = reservations.admission_id "
+ + "ORDER BY history.admission_attempt_id LIMIT "
+ + (MAX_HISTORY_ROWS_PER_SCOPE + 1)
+ + ") bounded_history "
+ + "ORDER BY bounded_history.request_id, bounded_history.admission_id, "
+ + "bounded_history.admission_attempt_id LIMIT "
+ + (MAX_HISTORY_ROWS_PER_SCOPE + 1)
+ + ") histories ORDER BY histories.tenant_uuid, histories.owner_service, histories.request_id, "
+ + "histories.admission_id, histories.admission_attempt_id LIMIT "
+ + (MAX_HISTORY_ROWS_PER_OBSERVATION + 1),
+ reservationBindings.toArray());
+ if (historyKeys.size() > MAX_HISTORY_ROWS_PER_OBSERVATION) {
+ // The observation-wide byte/row budget was exceeded; none of the unscanned history is
+ // inferred.
+ unqualified.addAll(reservations.keySet());
+ return new HistoryQualification(Set.of(), Set.copyOf(unqualified));
+ }
+
+ Map> keysByScope = new HashMap<>();
+ for (Record row : historyKeys) {
+ Scope scope =
+ new Scope(row.get("tenant_uuid", UUID.class), row.get("owner_service", String.class));
+ if (Objects.requireNonNull(row.get("payload_bytes", Long.class))
+ > MAX_RETAINED_PAYLOAD_BYTES) {
+ unqualified.add(scope);
+ continue;
+ }
+ UUID requestId = row.get("request_id", UUID.class);
+ UUID admissionId = row.get("admission_id", UUID.class);
+ String callerWorkload = row.get("caller_workload", String.class);
+ ReservationKey reservation =
+ qualifiedReservations.stream()
+ .filter(
+ candidate ->
+ candidate.scope().equals(scope)
+ && candidate.requestId().equals(requestId)
+ && candidate.admissionId().equals(admissionId)
+ && candidate.callerWorkload().equals(callerWorkload))
+ .findFirst()
+ .orElse(null);
+ if (reservation == null) {
+ unqualified.add(scope);
+ continue;
+ }
+ keysByScope
+ .computeIfAbsent(scope, ignored -> new ArrayList<>())
+ .add(
+ new HistoryKey(
+ reservation,
+ row.get("admission_attempt_id", UUID.class),
+ Objects.requireNonNull(row.get("capacity_rearm_fence", Long.class)),
+ Objects.requireNonNull(row.get("mutation_digest", String.class)).trim()));
+ }
+ for (Map.Entry> entry : keysByScope.entrySet()) {
+ if (entry.getValue().size() > MAX_HISTORY_ROWS_PER_SCOPE) unqualified.add(entry.getKey());
+ }
+ for (ReservationKey reservation : qualifiedReservations) {
+ if (unqualified.contains(reservation.scope())) continue;
+ List attemptKeys =
+ keysByScope.getOrDefault(reservation.scope(), List.of()).stream()
+ .filter(key -> key.reservation().equals(reservation))
+ .toList();
+ long expectedHistoryRows = reservation.currentRearmFence() - 1;
+ if (expectedHistoryRows < 0
+ || expectedHistoryRows != attemptKeys.size()
+ || expectedHistoryRows > MAX_HISTORY_ROWS_PER_SCOPE) {
+ unqualified.add(reservation.scope());
+ continue;
+ }
+ Set fences = new HashSet<>();
+ for (HistoryKey key : attemptKeys) fences.add(key.rearmFence());
+ for (long expectedFence = 1; expectedFence <= expectedHistoryRows; expectedFence++) {
+ if (!fences.contains(expectedFence)) {
+ unqualified.add(reservation.scope());
+ break;
+ }
+ }
+ }
+
+ List keysToRead =
+ keysByScope.entrySet().stream()
+ .filter(entry -> !unqualified.contains(entry.getKey()))
+ .flatMap(entry -> entry.getValue().stream())
+ .toList();
+ if (keysToRead.isEmpty()) return new HistoryQualification(Set.of(), Set.copyOf(unqualified));
+ List historyBindings = new ArrayList<>();
+ for (HistoryKey key : keysToRead) {
+ historyBindings.add(key.reservation().scope().tenantId());
+ historyBindings.add(key.reservation().requestId());
+ historyBindings.add(key.reservation().admissionId());
+ historyBindings.add(key.attemptId());
+ }
+ String historyValues = valuesClause(keysToRead.size(), 4, "uuid", "uuid", "uuid", "uuid");
+ var payloadRows =
+ dsl.fetch(
+ "WITH selected(tenant_uuid, request_id, admission_id, admission_attempt_id) AS (VALUES "
+ + historyValues
+ + ") SELECT history.tenant_uuid, history.request_id, history.admission_id, "
+ + "history.admission_attempt_id, history.capacity_rearm_fence, history.mutation_digest, "
+ + "history.canonical_payload FROM selected JOIN account_tenant_capacity_attempt_history history "
+ + "USING (tenant_uuid, request_id, admission_id, admission_attempt_id)",
+ historyBindings.toArray());
+ if (payloadRows.size() != keysToRead.size()) {
+ unqualified.addAll(keysByScope.keySet());
+ return new HistoryQualification(Set.of(), Set.copyOf(unqualified));
+ }
+
+ Map> referencesByScope = new HashMap<>();
+ Set malformed = new HashSet<>();
+ for (Record row : payloadRows) {
+ UUID tenantId = row.get("tenant_uuid", UUID.class);
+ UUID requestId = row.get("request_id", UUID.class);
+ UUID admissionId = row.get("admission_id", UUID.class);
+ UUID attemptId = row.get("admission_attempt_id", UUID.class);
+ HistoryKey expected =
+ keysToRead.stream()
+ .filter(
+ key ->
+ key.reservation().scope().tenantId().equals(tenantId)
+ && key.reservation().requestId().equals(requestId)
+ && key.reservation().admissionId().equals(admissionId)
+ && key.attemptId().equals(attemptId))
+ .findFirst()
+ .orElse(null);
+ Scope scope = expected == null ? null : expected.reservation().scope();
+ if (scope == null || requestId == null || admissionId == null || attemptId == null) {
+ if (scope != null) malformed.add(scope);
+ else unqualified.addAll(keysByScope.keySet());
+ continue;
+ }
+ ReservationKey reservation = expected.reservation();
+ try {
+ long fence = Objects.requireNonNull(row.get("capacity_rearm_fence", Long.class));
+ String digest = Objects.requireNonNull(row.get("mutation_digest", String.class)).trim();
+ byte[] payload = Objects.requireNonNull(row.get("canonical_payload", byte[].class));
+ if (fence != expected.rearmFence()
+ || !digest.equals(expected.mutationDigest())
+ || payload.length > MAX_RETAINED_PAYLOAD_BYTES) throw new IllegalArgumentException();
+ var request = CapacityAdmissionDigest.decodeCommittable(payload, digest);
+ if (!request.identity().tenantId().equals(scope.tenantId())
+ || !request.identity().requestId().equals(requestId)
+ || !request.identity().admissionId().equals(admissionId)
+ || !request.admissionAttemptId().equals(attemptId)
+ || request.capacityRearmFence() != fence
+ || !request.context().owner().service().equals(reservation.scope().ownerService())
+ || !request.evidence().callerWorkload().equals(reservation.callerWorkload()))
+ throw new IllegalArgumentException();
+ referencesByScope
+ .computeIfAbsent(scope, ignored -> new HashSet<>())
+ .add(request.evidence().evaluationIdentity());
+ } catch (RuntimeException invalid) {
+ malformed.add(scope);
+ }
+ }
+ unqualified.addAll(malformed);
+ Set references = new HashSet<>();
+ for (Map.Entry> entry : referencesByScope.entrySet()) {
+ if (!unqualified.contains(entry.getKey())) references.addAll(entry.getValue());
+ }
+ return new HistoryQualification(Set.copyOf(references), Set.copyOf(unqualified));
+ }
+
+ private static String valuesClause(int rows, int columns, String... casts) {
+ if (rows < 1 || columns != casts.length)
+ throw new IllegalArgumentException("Invalid SQL values shape");
+ String row =
+ "("
+ + String.join(", ", java.util.Arrays.stream(casts).map(cast -> "?::" + cast).toList())
+ + ")";
+ return String.join(", ", java.util.Collections.nCopies(rows, row));
+ }
+
+ private static void requireBound(int rows) {
+ if (rows < 1 || rows > MAX_SAMPLE_ROWS) {
+ throw new IllegalArgumentException(
+ "Capacity retention sample must be between 1 and 1000 rows");
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicy.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicy.java
new file mode 100644
index 0000000000..809cb2e8f5
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicy.java
@@ -0,0 +1,128 @@
+package net.firedevops.firemud.accountservice.service;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import org.jspecify.annotations.Nullable;
+
+/** Classifies an observed evaluation using explicit policy inputs. Grants no cleanup authority. */
+final class AccountCapacityEvaluationRetentionPolicy {
+ private AccountCapacityEvaluationRetentionPolicy() {}
+
+ enum Classification {
+ CANDIDATE,
+ LIVE_EVALUATION,
+ RETAINED_RESERVATION_SCOPE,
+ POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE,
+ HELD,
+ ABOVE_SAFE_WATERMARK,
+ RETENTION_WINDOW_OPEN
+ }
+
+ enum Hold {
+ CLEAR,
+ HELD
+ }
+
+ /** The declared durations are relative to evaluation time. Maximum caps the dependencies. */
+ record Schedule(
+ String version,
+ Duration maximum,
+ Duration evidence,
+ Duration retry,
+ Duration replay,
+ Duration restore,
+ Duration investigation) {
+ Schedule {
+ requireVersion(version);
+ requirePositive(maximum);
+ for (Duration horizon : List.of(evidence, retry, replay, restore, investigation)) {
+ requirePositive(horizon);
+ if (horizon.compareTo(maximum) > 0)
+ throw new IllegalArgumentException("Retention horizon exceeds the schedule maximum");
+ }
+ }
+
+ private Duration requiredHorizon() {
+ return Collections.max(List.of(evidence, retry, replay, restore, investigation));
+ }
+ }
+
+ /** One bounded hold observation. Its safe watermark is inclusive in evaluation-time order. */
+ record Safety(
+ String scheduleVersion,
+ Instant observedAt,
+ Instant validUntil,
+ Instant safeWatermark,
+ Map holds) {
+ Safety {
+ requireVersion(scheduleVersion);
+ Objects.requireNonNull(observedAt);
+ Objects.requireNonNull(validUntil);
+ Objects.requireNonNull(safeWatermark);
+ if (!observedAt.isBefore(validUntil) || safeWatermark.isAfter(observedAt))
+ throw new IllegalArgumentException("Invalid capacity retention observation window");
+ if (Objects.requireNonNull(holds).size()
+ > AccountCapacityEvaluationRetentionInspectionOwner.MAX_SAMPLE_ROWS)
+ throw new IllegalArgumentException(
+ "Capacity retention hold observations exceed the sample bound");
+ holds = Map.copyOf(holds);
+ }
+ }
+
+ static boolean current(
+ @Nullable Schedule schedule, @Nullable Safety safety, @Nullable Instant observedAt) {
+ return schedule != null
+ && safety != null
+ && observedAt != null
+ && schedule.version().equals(safety.scheduleVersion())
+ && !observedAt.isBefore(safety.observedAt())
+ && observedAt.isBefore(safety.validUntil());
+ }
+
+ static Classification classify(
+ @Nullable Schedule schedule,
+ @Nullable Safety safety,
+ @Nullable Instant observedAt,
+ @Nullable String evaluationIdentity,
+ @Nullable Instant evaluatedAt,
+ @Nullable Instant expiresAt,
+ @Nullable Boolean scopeReferenced) {
+ if (Boolean.TRUE.equals(scopeReferenced)) return Classification.RETAINED_RESERVATION_SCOPE;
+ if (scopeReferenced == null
+ || observedAt == null
+ || evaluationIdentity == null
+ || evaluationIdentity.isBlank()
+ || evaluatedAt == null
+ || expiresAt == null
+ || !evaluatedAt.isBefore(expiresAt)
+ || evaluatedAt.isAfter(observedAt))
+ return Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE;
+ if (observedAt.isBefore(expiresAt)) return Classification.LIVE_EVALUATION;
+ if (schedule == null
+ || safety == null
+ || !current(schedule, safety, observedAt)
+ || Duration.between(evaluatedAt, expiresAt).compareTo(schedule.maximum()) > 0)
+ return Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE;
+ Hold hold = safety.holds().get(evaluationIdentity);
+ if (hold == null) return Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE;
+ if (hold == Hold.HELD) return Classification.HELD;
+ if (evaluatedAt.isAfter(safety.safeWatermark())) return Classification.ABOVE_SAFE_WATERMARK;
+ if (Duration.between(evaluatedAt, observedAt).compareTo(schedule.requiredHorizon()) < 0)
+ return Classification.RETENTION_WINDOW_OPEN;
+ return Classification.CANDIDATE;
+ }
+
+ private static void requireVersion(String version) {
+ if (Objects.requireNonNull(version).isBlank())
+ throw new IllegalArgumentException("Capacity retention schedule version is required");
+ }
+
+ private static void requirePositive(Duration duration) {
+ if (Objects.requireNonNull(duration).isZero() || duration.isNegative())
+ throw new IllegalArgumentException("Capacity retention horizons must be positive");
+ }
+}
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 118816e746..d11b0dbac7 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
@@ -6,6 +6,7 @@
import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
@@ -20,6 +21,7 @@
import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository;
import net.firedevops.firemud.common.account.capacity.AccountCapacityOriginContinuation;
import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest;
+import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecutionReadGrpcCodec;
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;
@@ -57,6 +59,16 @@ public interface ExecutionReadClient {
Observation readExact(Request request, Result reservation, Instant deadline);
}
+ /** Exact authenticated historical read, separate from the current execution source. */
+ public interface HistoricalFinalReadClient {
+ HistoricalObservation readHistoricalFinal(
+ Request request, Result reservation, Instant deadline);
+ }
+
+ public record HistoricalObservation(
+ String authenticatedOwnerWorkload,
+ OriginalNewCapacityExecutionReadGrpcCodec.HistoricalFinalReadback receipt) {}
+
public record Observation(
String authenticatedOwnerWorkload,
Result reservation,
@@ -105,16 +117,27 @@ public String toString() {
private final DSLContext dsl;
private final AccountTenantCapacityRepository capacity;
private final ExecutionReadClient source;
+ private final HistoricalFinalReadClient historicalSource;
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, dsl, source, null, clock);
+ }
+
+ public AccountTenantCapacityRecoveryWorker(
+ AccountTenantCapacityOwner owner,
+ DSLContext dsl,
+ ExecutionReadClient source,
+ HistoricalFinalReadClient historicalSource,
+ Clock clock) {
this.owner = Objects.requireNonNull(owner);
this.dsl = Objects.requireNonNull(dsl);
this.capacity = new AccountTenantCapacityRepository(dsl);
this.source = Objects.requireNonNull(source);
+ this.historicalSource = historicalSource;
this.clock = Objects.requireNonNull(clock);
}
@@ -123,10 +146,25 @@ public Result reconcile(Request request, NoCommitAction noCommitAction) {
Objects.requireNonNull(noCommitAction);
request.requireCommittable();
return withExclusiveOperation(
- request.identity(), () -> reconcileClaim(request, noCommitAction));
+ request.identity(),
+ () -> reconcileClaim(request, noCommitAction, this::readCurrentEvidence));
}
- private Result reconcileClaim(Request request, NoCommitAction noCommitAction) {
+ /** Settles only an exact positive historical receipt for an existing held reservation. */
+ public Result reconcileHistoricalFinal(Request request) {
+ request.requireCommittable();
+ if (historicalSource == null
+ || request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION) {
+ throw unavailable();
+ }
+ return withExclusiveOperation(
+ request.identity(),
+ () ->
+ reconcileClaim(request, NoCommitAction.RETAIN_FOR_REARM, this::readHistoricalEvidence));
+ }
+
+ private Result reconcileClaim(
+ Request request, NoCommitAction noCommitAction, EvidenceReader reader) {
Claim claim = claim(request);
if (claim.reservation().state() != State.RESERVED) return claim.reservation();
if (claim.noCommitProof() != null) {
@@ -157,8 +195,7 @@ private Result reconcileClaim(Request request, NoCommitAction noCommitAction) {
request, Objects.requireNonNull(capacity.find(request.identity())));
});
}
- Observation candidate = null;
- byte[] candidateProof = null;
+ RecoveryEvidence candidate = null;
if (claim.attempts() < AccountCapacityOriginContinuation.MAX_OBSERVATIONS) {
Instant started = clock.instant();
boolean positiveOnly = !started.isBefore(claim.reconcileDeadline());
@@ -166,21 +203,18 @@ private Result reconcileClaim(Request request, NoCommitAction noCommitAction) {
if (!positiveOnly && claim.reconcileDeadline().isBefore(deadline))
deadline = claim.reconcileDeadline();
try {
- candidate = source.readExact(request, claim.reservation(), deadline);
+ candidate = reader.read(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;
+ final RecoveryEvidence observed = candidate;
+ final byte[] exactProof = observed == null ? null : observed.proof();
return owner.inTransaction(
() -> {
Record row = capacity.find(request.identity());
@@ -371,32 +405,55 @@ private static void requireExactSource(Request request, Result expected, Observa
throw unavailable();
}
+ private RecoveryEvidence readCurrentEvidence(
+ Request request, Result reservation, Instant deadline) {
+ var observation = source.readExact(request, reservation, deadline);
+ requireExactSource(request, reservation, observation);
+ return new RecoveryEvidence(observation.disposition(), proof(request, observation));
+ }
+
+ private RecoveryEvidence readHistoricalEvidence(
+ Request request, Result reservation, Instant deadline) {
+ var observation = historicalSource.readHistoricalFinal(request, reservation, deadline);
+ String expectedOwner =
+ TenantCapacityAdmission.expectedWorkload(
+ request.targetNamespace(), request.context().owner());
+ if (observation == null || !expectedOwner.equals(observation.authenticatedOwnerWorkload())) {
+ throw unavailable();
+ }
+ var selector = new OriginalNewCapacityExecutionReadGrpcCodec.Selector(request, reservation);
+ byte[] receipt =
+ OriginalNewCapacityExecutionReadGrpcCodec.toHistoricalResponse(
+ selector, observation.receipt())
+ .toByteArray();
+ return new RecoveryEvidence(
+ Disposition.COMMITTED,
+ framedProof(
+ "account-capacity-historical-final/v1".getBytes(StandardCharsets.US_ASCII),
+ expectedOwner.getBytes(StandardCharsets.US_ASCII),
+ receipt));
+ }
+
private static byte[] proof(Request request, Observation observed) {
// Fixed content binding includes the entire attempt and exact owner readback, not a boolean.
+ return framedProof(
+ "account-capacity-owner-readback/v1".getBytes(StandardCharsets.US_ASCII),
+ CapacityAdmissionDigest.preimage(request),
+ observed.reservation().reservationId().toString().getBytes(StandardCharsets.US_ASCII),
+ Long.toString(observed.reservation().reservationFence())
+ .getBytes(StandardCharsets.US_ASCII),
+ observed.authenticatedOwnerWorkload().getBytes(StandardCharsets.US_ASCII),
+ observed.disposition().name().getBytes(StandardCharsets.US_ASCII),
+ observed.proofId().toString().getBytes(StandardCharsets.US_ASCII),
+ Long.toString(observed.currentOwnerFence()).getBytes(StandardCharsets.US_ASCII),
+ observed.authoritativeStateDigest().getBytes(StandardCharsets.US_ASCII),
+ observed.canonicalOwnerReadback());
+ }
+
+ private static byte[] framedProof(byte[]... fields) {
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));
+ for (byte[] bytes : fields) {
+ output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII));
output.write(':');
output.writeBytes(bytes);
}
@@ -413,6 +470,22 @@ private static String sha256(byte[] bytes) {
}
}
+ @FunctionalInterface
+ private interface EvidenceReader {
+ RecoveryEvidence read(Request request, Result reservation, Instant deadline);
+ }
+
+ private record RecoveryEvidence(Disposition disposition, byte[] proof) {
+ private RecoveryEvidence {
+ proof = proof.clone();
+ }
+
+ @Override
+ public byte[] proof() {
+ return proof.clone();
+ }
+ }
+
private record Claim(
Result reservation,
long fence,
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java
new file mode 100644
index 0000000000..3ecd7bf5e4
--- /dev/null
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java
@@ -0,0 +1,849 @@
+package 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.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture;
+import java.sql.SQLException;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.LinkedHashMap;
+import java.util.List;
+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.AccountCapacityOriginDecisionRepository;
+import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository;
+import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding;
+import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository;
+import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity;
+import net.firedevops.firemud.accountservice.repository.AccountRepository;
+import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository;
+import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionInspectionOwner.Blocker;
+import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence;
+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.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
+import org.flywaydb.core.Flyway;
+import org.jooq.DSLContext;
+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;
+
+/**
+ * Disposable PostgreSQL proof of bounded read-only inspection and unchanged immutable guards. This
+ * suite establishes no policy approval or deletion authority.
+ */
+class AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest {
+ private static final AccountPostgresIntegrationFixture POSTGRES =
+ new AccountPostgresIntegrationFixture();
+
+ @BeforeAll
+ static void start() {
+ POSTGRES.start();
+ }
+
+ @AfterAll
+ static void stop() {
+ POSTGRES.stop();
+ }
+
+ @Test
+ void freshAndPopulatedForwardMigrationPreserveRowsAndGuardsWhileBoundingObservations() {
+ verifyForwardMigration(false);
+ verifyForwardMigration(true);
+ }
+
+ @Test
+ void policyQualifiedInspectionFindsRearmedOldEvaluationAndLeavesUnrelatedRowCandidate()
+ throws InterruptedException {
+ String schema = "capacity_retention_history_" + UUID.randomUUID().toString().replace("-", "");
+ new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema);
+ var data = POSTGRES.dataSource(schema);
+ try {
+ configure(data, schema).load().migrate();
+ var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES);
+ var transactions = new DataSourceTransactionManager(data);
+ var write = new TransactionTemplate(transactions);
+ FreshTenantCreationEvidence tenant = bootstrapFreshTenant(dsl, write);
+
+ Instant priorAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
+ var prior =
+ playerRequest(
+ tenant.canonicalTenantId(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ priorAt,
+ priorAt.plusSeconds(10));
+ var unrelated =
+ playerRequest(
+ tenant.canonicalTenantId(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ UUID.randomUUID(),
+ priorAt.minus(Duration.ofDays(10)),
+ priorAt.minus(Duration.ofDays(10)).plusSeconds(90));
+ UUID reservationId = UUID.randomUUID();
+ UUID recoveryOwner = UUID.randomUUID();
+ String readbackDigest = "b".repeat(64);
+ write.executeWithoutResult(
+ status -> {
+ insertEvaluation(dsl, prior, priorAt, priorAt.plusSeconds(10));
+ insertEvaluation(
+ dsl,
+ unrelated,
+ unrelated.evidence().evaluatedAt(),
+ unrelated.evidence().expiresAt());
+ new AccountCapacityOriginDecisionRepository(dsl).accept(prior);
+ 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, state, execution_status, "
+ + "reconcile_deadline) VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, "
+ + "?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING', ?::timestamptz)",
+ prior.identity().tenantId(),
+ prior.identity().requestId(),
+ prior.identity().admissionId(),
+ reservationId,
+ prior.evidence().callerWorkload(),
+ prior.admissionAttemptId(),
+ prior.mutationDigest(),
+ CapacityAdmissionDigest.preimage(prior),
+ prior.evidence().evaluationIdentity(),
+ prior.evidence().expiresAt().toString(),
+ prior.evidence().expiresAt().plusSeconds(60).toString());
+ dsl.execute(
+ "UPDATE account_tenant_capacity_usage SET held_units = 1, usage_revision = 2 "
+ + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'",
+ tenant.canonicalTenantId());
+ });
+
+ waitUntil(prior.evidence().expiresAt().plusMillis(100));
+ Instant nextAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
+ var nextSeed =
+ playerRequest(
+ tenant.canonicalTenantId(),
+ prior.identity().requestId(),
+ prior.identity().admissionId(),
+ UUID.randomUUID(),
+ nextAt,
+ nextAt.plusSeconds(60));
+ var next =
+ new TenantCapacityAdmission.Request(
+ prior.identity(),
+ nextSeed.admissionAttemptId(),
+ 2,
+ prior.targetNamespace(),
+ prior.context(),
+ prior.operation(),
+ prior.priorShape(),
+ prior.requestedShape(),
+ nextSeed.evidence(),
+ prior.capacityDelta(),
+ null)
+ .withDigest();
+ byte[] ownerReadback =
+ "controlled-terminal-no-commit".getBytes(java.nio.charset.StandardCharsets.US_ASCII);
+ write.executeWithoutResult(
+ status -> {
+ insertEvaluation(dsl, next, next.evidence().evaluatedAt(), next.evidence().expiresAt());
+ dsl.execute(
+ "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, "
+ + "recovery_claim_fence = 1, recovery_claim_expires_at = clock_timestamp() + INTERVAL '1 day', "
+ + "execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION', owner_readback = ?, "
+ + "owner_readback_digest = ? WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?",
+ recoveryOwner,
+ ownerReadback,
+ readbackDigest,
+ prior.identity().tenantId(),
+ prior.identity().requestId(),
+ prior.identity().admissionId());
+ });
+ var capacityOwner = capacityOwner(dsl, transactions, next);
+ var rearmed = capacityOwner.rearm(prior, next, recoveryOwner, 1L);
+ assertThat(rearmed.evaluationIdentity()).isEqualTo(next.evidence().evaluationIdentity());
+
+ List beforeObservation = rowImages(dsl);
+ var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, transactions);
+ Instant policyObservedAt = Instant.now().minusSeconds(1);
+ var schedule =
+ new AccountCapacityEvaluationRetentionPolicy.Schedule(
+ "physical-fixture/v1",
+ Duration.ofDays(30),
+ Duration.ofDays(2),
+ Duration.ofDays(3),
+ Duration.ofDays(4),
+ Duration.ofDays(5),
+ Duration.ofDays(6));
+ var safety =
+ new AccountCapacityEvaluationRetentionPolicy.Safety(
+ "physical-fixture/v1",
+ policyObservedAt,
+ policyObservedAt.plus(Duration.ofHours(1)),
+ policyObservedAt.minus(Duration.ofDays(1)),
+ Map.of(
+ prior.evidence().evaluationIdentity(),
+ AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR,
+ next.evidence().evaluationIdentity(),
+ AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR,
+ unrelated.evidence().evaluationIdentity(),
+ AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR));
+
+ var observation = owner.observe(10, schedule, safety);
+
+ assertThat(observation.sampledRows()).isEqualTo(3);
+ assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows())
+ .isEqualTo(2);
+ assertThat(observation.candidates().rows()).isEqualTo(1);
+ assertThat(rowImages(dsl)).isEqualTo(beforeObservation);
+ } finally {
+ new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE");
+ }
+ }
+
+ @Test
+ void populatedMixedCohortKeepsExactImagesAcrossBoundedPolicyAndUnqualifiedReads() {
+ String schema = "capacity_retention_mixed_" + UUID.randomUUID().toString().replace("-", "");
+ new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema);
+ var data = POSTGRES.dataSource(schema);
+ try {
+ configure(data, schema).target("1043").load().migrate();
+ var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES);
+ var transactions = new DataSourceTransactionManager(data);
+ var write = new TransactionTemplate(transactions);
+ populate(dsl, write);
+ UUID tenant =
+ dsl.fetchSingle("SELECT tenant_uuid FROM account_tenant_capacity_reservations")
+ .get(0, UUID.class);
+ Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS);
+ // Controlled historical storage, not production hold authority or cleanup eligibility.
+ // The existing game-session history/direct references share this tenant but not the
+ // world-management owner scope of these unrelated evaluations.
+ write.executeWithoutResult(
+ status -> {
+ for (var row :
+ List.of(
+ new Object[] {
+ digest('4'), now.minus(Duration.ofDays(10)), now.minus(Duration.ofDays(9)), 4
+ },
+ new Object[] {
+ digest('5'), now.minus(Duration.ofDays(9)), now.minus(Duration.ofDays(8)), 5
+ },
+ new Object[] {
+ digest('6'), now.minus(Duration.ofDays(8)), now.minus(Duration.ofDays(7)), 6
+ },
+ new Object[] {
+ digest('7'),
+ now.minus(Duration.ofHours(12)),
+ now.minus(Duration.ofHours(6)),
+ 7
+ },
+ new Object[] {
+ digest('8'), now.minus(Duration.ofHours(1)), now.plus(Duration.ofHours(1)), 8
+ })) {
+ 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 (?, ?, ?, 'test-workload', 'world-management-service', ?, ?::timestamptz, ?::timestamptz)",
+ row[0],
+ digest('d'),
+ tenant,
+ new byte[(int) row[3]],
+ row[1].toString(),
+ row[2].toString());
+ }
+ });
+ var beforeMigration = rowImages(dsl);
+ var guards = guardImages(dsl);
+ configure(data, schema).load().migrate();
+ assertThat(rowImages(dsl)).isEqualTo(beforeMigration);
+ assertThat(guardImages(dsl)).isEqualTo(guards);
+ var conservation =
+ dsl.fetch(
+ "SELECT to_jsonb(c)::text AS row, xmin::text AS xmin "
+ + "FROM account_tenant_capacity_conservation c ORDER BY tenant_uuid, owner_service")
+ .intoMaps();
+ var flyway =
+ dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps();
+ var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, transactions);
+ // Same controlled schedule as the existing physical qualification, not a new policy choice.
+ var schedule =
+ new AccountCapacityEvaluationRetentionPolicy.Schedule(
+ "physical-fixture/v1",
+ Duration.ofDays(30),
+ Duration.ofDays(2),
+ Duration.ofDays(3),
+ Duration.ofDays(4),
+ Duration.ofDays(5),
+ Duration.ofDays(6));
+ var safety =
+ new AccountCapacityEvaluationRetentionPolicy.Safety(
+ "physical-fixture/v1",
+ now.minusSeconds(1),
+ now.plus(Duration.ofHours(1)),
+ now.minus(Duration.ofDays(1)),
+ Map.of(
+ digest('a'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR,
+ digest('b'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR,
+ digest('c'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR,
+ digest('4'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR,
+ digest('5'), AccountCapacityEvaluationRetentionPolicy.Hold.HELD,
+ digest('7'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR,
+ digest('8'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR));
+ for (int repeat = 0; repeat < 2; repeat++) {
+ var bounded = owner.observe(3, schedule, safety);
+ assertThat(bounded.sampledRows()).isEqualTo(3);
+ assertThat(bounded.sampleTruncated()).isTrue();
+ assertThat(bounded.candidates().rows()).isOne();
+ assertThat(bounded.candidates().evidenceBytes()).isEqualTo(4);
+ assertThat(bounded.blockers().get(Blocker.HELD).rows()).isOne();
+ assertThat(bounded.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows())
+ .isOne();
+ var all = owner.observe(10, schedule, safety);
+ assertThat(all.sampledRows()).isEqualTo(8);
+ assertThat(all.sampleTruncated()).isFalse();
+ assertThat(all.governanceBlocker()).isNull();
+ assertThat(all.candidates().rows()).isOne();
+ assertThat(all.candidates().evidenceBytes()).isEqualTo(4);
+ assertThat(all.candidates().oldestEvaluatedAt()).contains(now.minus(Duration.ofDays(10)));
+ assertThat(all.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isEqualTo(2);
+ assertThat(all.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).evidenceBytes())
+ .isEqualTo(262145);
+ assertThat(all.blockers().get(Blocker.HELD).rows()).isOne();
+ assertThat(all.blockers().get(Blocker.HELD).evidenceBytes()).isEqualTo(5);
+ assertThat(all.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows())
+ .isOne();
+ assertThat(all.blockers().get(Blocker.ABOVE_SAFE_WATERMARK).rows()).isOne();
+ assertThat(all.blockers().get(Blocker.RETENTION_WINDOW_OPEN).rows()).isOne();
+ assertThat(all.blockers().get(Blocker.LIVE_EVALUATION).rows()).isOne();
+ var unqualified = owner.observe(10);
+ assertThat(unqualified.candidates().rows()).isZero();
+ assertThat(unqualified.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows())
+ .isEqualTo(2);
+ assertThat(unqualified.blockers().get(Blocker.LIVE_EVALUATION).rows()).isOne();
+ assertThat(unqualified.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows())
+ .isEqualTo(5);
+ assertThat(rowImages(dsl)).isEqualTo(beforeMigration);
+ assertThat(guardImages(dsl)).isEqualTo(guards);
+ assertThat(
+ dsl.fetch(
+ "SELECT to_jsonb(c)::text AS row, xmin::text AS xmin "
+ + "FROM account_tenant_capacity_conservation c ORDER BY tenant_uuid, owner_service")
+ .intoMaps())
+ .isEqualTo(conservation);
+ assertThat(
+ dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps())
+ .isEqualTo(flyway);
+ }
+ } finally {
+ new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE");
+ }
+ }
+
+ private static void verifyForwardMigration(boolean populated) {
+ String schema = "capacity_retention_" + UUID.randomUUID().toString().replace("-", "");
+ new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema);
+ var data = POSTGRES.dataSource(schema);
+ try {
+ configure(data, schema).target("1043").load().migrate();
+ var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES);
+ var transactions = new DataSourceTransactionManager(data);
+ var write = new TransactionTemplate(transactions);
+ if (populated) populate(dsl, write);
+ var beforeRows = rowImages(dsl);
+ if (populated) {
+ assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isOne();
+ assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_attempt_history"))).isOne();
+ assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_recovery_evidence"))).isOne();
+ }
+ var beforeGuards = guardImages(dsl);
+ var beforeFlyway =
+ dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps();
+ String originalMigration =
+ dsl.fetchSingle("SELECT checksum::text FROM flyway_schema_history WHERE version = '1040'")
+ .get(0, String.class);
+
+ configure(data, schema).load().migrate();
+
+ assertThat(rowImages(dsl)).isEqualTo(beforeRows);
+ assertThat(guardImages(dsl)).isEqualTo(beforeGuards);
+ assertThat(
+ dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank")
+ .intoMaps()
+ .subList(0, beforeFlyway.size()))
+ .isEqualTo(beforeFlyway);
+ var conservation =
+ dsl.fetch(
+ "SELECT to_jsonb(c)::text AS row, xmin::text AS xmin "
+ + "FROM account_tenant_capacity_conservation c ORDER BY tenant_uuid, owner_service")
+ .intoMaps();
+ assertThat(conservation).hasSize(populated ? 2 : 0);
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT checksum::text FROM flyway_schema_history WHERE version = '1040'")
+ .get(0, String.class))
+ .isEqualTo(originalMigration);
+ assertThat(configure(data, schema).load().validateWithResult().validationSuccessful).isTrue();
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT pg_get_indexdef('account_capacity_evaluation_oldest_retention_idx'::regclass)")
+ .get(0, String.class))
+ .contains("evaluated_at, evaluation_identity");
+ assertThat(
+ dsl.fetchSingle(
+ "SELECT pg_get_indexdef('account_capacity_reservation_retention_scope_idx'::regclass)")
+ .get(0, String.class))
+ .contains("tenant_uuid, owner_service");
+ var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, transactions);
+ var observed = owner.observe(2);
+ assertThat(observed.totalRelationBytes()).isPositive();
+ assertThat(observed.sampledRows()).isEqualTo(populated ? 2 : 0);
+ assertThat(observed.sampleTruncated()).isEqualTo(populated);
+ assertThat(observed.governanceBlocker())
+ .isEqualTo(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE);
+ if (populated) {
+ // The oldest evaluation has no current FK, but its reservation scope/history is retained.
+ assertThat(observed.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isEqualTo(1);
+ assertThat(observed.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).evidenceBytes())
+ .isEqualTo(262144);
+ assertThat(observed.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows())
+ .isEqualTo(1);
+ assertThat(observed.blockers().get(Blocker.LIVE_EVALUATION).rows()).isZero();
+ var all = owner.observe(1000);
+ assertThat(all.sampledRows()).isEqualTo(3);
+ assertThat(all.sampleTruncated()).isFalse();
+ assertThat(all.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isEqualTo(2);
+ for (String sql :
+ List.of(
+ "UPDATE account_tenant_capacity_evaluations SET canonical_evidence = decode('01', 'hex')",
+ "DELETE FROM account_tenant_capacity_evaluations WHERE evaluation_identity = '"
+ + digest('c')
+ + "'",
+ "TRUNCATE account_tenant_capacity_evaluations CASCADE",
+ "DELETE FROM account_tenant_capacity_reservations",
+ "UPDATE account_tenant_capacity_attempt_history SET canonical_payload = decode('01', 'hex')",
+ "DELETE FROM account_tenant_capacity_attempt_history",
+ "TRUNCATE account_tenant_capacity_attempt_history",
+ "UPDATE account_tenant_capacity_recovery_evidence SET outcome = 'INDETERMINATE'",
+ "DELETE FROM account_tenant_capacity_recovery_evidence",
+ "TRUNCATE account_tenant_capacity_recovery_evidence")) {
+ assertThatThrownBy(() -> write.executeWithoutResult(status -> dsl.execute(sql)))
+ .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514"));
+ }
+ }
+ assertThat(rowImages(dsl)).isEqualTo(beforeRows);
+ assertThat(guardImages(dsl)).isEqualTo(beforeGuards);
+ assertThat(
+ dsl.fetch(
+ "SELECT to_jsonb(c)::text AS row, xmin::text AS xmin "
+ + "FROM account_tenant_capacity_conservation c ORDER BY tenant_uuid, owner_service")
+ .intoMaps())
+ .isEqualTo(conservation);
+ } finally {
+ new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE");
+ }
+ }
+
+ private static org.flywaydb.core.api.configuration.FluentConfiguration configure(
+ javax.sql.DataSource data, String schema) {
+ return Flyway.configure()
+ .dataSource(data)
+ .schemas(schema)
+ .defaultSchema(schema)
+ .placeholders(Map.of("serviceSchema", schema))
+ .locations("classpath:db/migration");
+ }
+
+ private static List rowImages(DSLContext dsl) {
+ return dsl.fetch(
+ "SELECT family || ':' || image AS image FROM ("
+ + "SELECT 'evaluation' AS family, (to_jsonb(e) || jsonb_build_object('xmin', e.xmin::text))::text AS image "
+ + "FROM account_tenant_capacity_evaluations e UNION ALL "
+ + "SELECT 'history', (to_jsonb(h) || jsonb_build_object('xmin', h.xmin::text))::text "
+ + "FROM account_tenant_capacity_attempt_history h UNION ALL "
+ + "SELECT 'recovery', (to_jsonb(r) || jsonb_build_object('xmin', r.xmin::text))::text "
+ + "FROM account_tenant_capacity_recovery_evidence r UNION ALL "
+ + "SELECT 'reservation', (to_jsonb(r) || jsonb_build_object('xmin', r.xmin::text))::text "
+ + "FROM account_tenant_capacity_reservations r UNION ALL "
+ + "SELECT 'usage', (to_jsonb(u) || jsonb_build_object('xmin', u.xmin::text))::text "
+ + "FROM account_tenant_capacity_usage u) retained ORDER BY family, image")
+ .getValues("image", String.class);
+ }
+
+ private static List guardImages(DSLContext dsl) {
+ return dsl.fetch(
+ "SELECT pg_get_triggerdef(oid) AS definition FROM pg_trigger WHERE NOT tgisinternal "
+ + "AND tgrelid IN ('account_tenant_capacity_evaluations'::regclass, "
+ + "'account_tenant_capacity_attempt_history'::regclass, "
+ + "'account_tenant_capacity_recovery_evidence'::regclass) ORDER BY tgrelid, tgname")
+ .getValues("definition", String.class);
+ }
+
+ private static void populate(DSLContext dsl, TransactionTemplate write) {
+ var tenant = source();
+ UUID bootstrap = UUID.randomUUID();
+ UUID request = UUID.randomUUID();
+ UUID admission = UUID.randomUUID();
+ write.executeWithoutResult(
+ status -> {
+ UUID account =
+ dsl.fetchSingle(
+ "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, 'test-password') RETURNING account_uuid",
+ "retention-" + UUID.randomUUID(),
+ "retention-" + UUID.randomUUID() + "@example.test")
+ .get(0, UUID.class);
+ new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant);
+ dsl.execute(
+ "INSERT INTO account_tenant_creation_bootstrap_operations "
+ + "(request_id, schema_version, initiating_account_uuid, tenant_uuid, creation_request_id, "
+ + "creation_operation_id, account_authorization_operation_id, account_authorization_digest, "
+ + "creator_evidence_digest, creator_evidence_payload, source_snapshot_payload, source_snapshot_digest, "
+ + "request_payload, request_digest, baseline_membership_version, baseline_membership_authority_generation, "
+ + "baseline_event_sequence, status) "
+ + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0, 'IN_PROGRESS')",
+ bootstrap,
+ account,
+ tenant.canonicalTenantId(),
+ tenant.creationRequestId(),
+ tenant.operationId(),
+ bootstrap,
+ digest('d'),
+ tenant.evidenceDigest(),
+ new byte[] {1},
+ new byte[] {2},
+ digest('e'),
+ new byte[] {3},
+ digest('f'));
+ dsl.execute(
+ "UPDATE account_tenant_creation_bootstrap_operations SET membership_id = 1, membership_version = 2, "
+ + "membership_authority_generation = 1, membership_lifecycle_state = 'ACTIVE', gameplay_admission_allowed = FALSE, "
+ + "membership_roles_payload = convert_to('[\"tenantAdmin\"]', 'UTF8'), event_stream_key = ?, "
+ + "event_request_id = ?, event_sequence = 1, event_id = ?, event_digest = ?, caller_bound_authority_invalidated = FALSE, "
+ + "event_payload = ?, audit_event_id = ?, audit_event_type = 'ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED', "
+ + "audit_occurred_at = CURRENT_TIMESTAMP, audit_payload_digest = ?, audit_payload = ?, result_payload = ?, "
+ + "result_digest = ?, status = 'COMMITTED' WHERE request_id = ?",
+ "account:auth-authority:v1:membership/" + account + "/" + tenant.canonicalTenantId(),
+ bootstrap.toString(),
+ "retention-bootstrap-" + bootstrap,
+ digest('1'),
+ new byte[] {4},
+ UUID.randomUUID(),
+ digest('2'),
+ new byte[] {5},
+ new byte[] {6},
+ digest('3'),
+ bootstrap);
+ for (var evaluation :
+ List.of(
+ new Object[] {digest('a'), "game-session-service", 3, -2, new byte[262144]},
+ new Object[] {digest('c'), "world-management-service", 2, -1, new byte[] {1}},
+ new Object[] {digest('b'), "game-session-service", 1, 1, new byte[] {2}})) {
+ 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 (?, ?, ?, 'test-workload', ?, ?, CURRENT_TIMESTAMP - ? * INTERVAL '1 day', "
+ + "CURRENT_TIMESTAMP + ? * INTERVAL '1 day')",
+ evaluation[0],
+ digest('d'),
+ tenant.canonicalTenantId(),
+ evaluation[1],
+ evaluation[4],
+ evaluation[2],
+ evaluation[3]);
+ }
+ UUID attempt = UUID.randomUUID();
+ String mutationDigest = "e".repeat(64);
+ byte[] capacityPayload = {7};
+ dsl.execute(
+ "INSERT INTO account_capacity_origin_decisions "
+ + "(tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, "
+ + "mutation_digest, canonical_payload, decision, decision_id) "
+ + "VALUES (?, ?, ?, 1, ?, ?, ?, 'ACCEPTED', ?)",
+ tenant.canonicalTenantId(),
+ request,
+ admission,
+ attempt,
+ mutationDigest,
+ capacityPayload,
+ UUID.randomUUID());
+ 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, state, execution_status, reconcile_deadline) "
+ + "VALUES (?, ?, ?, ?, 'game-session-service', 'test-workload', ?, 1, 1, ?, ?, ?, 0, "
+ + "CURRENT_TIMESTAMP + INTERVAL '1 day', 'RESERVED', 'OWNER_EXECUTION_PENDING', CURRENT_TIMESTAMP + INTERVAL '2 days')",
+ tenant.canonicalTenantId(),
+ request,
+ admission,
+ UUID.randomUUID(),
+ attempt,
+ mutationDigest,
+ capacityPayload,
+ digest('b'));
+ 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 (?, ?, ?, ?, 1, ?, convert_to(?, 'UTF8'), ?)",
+ tenant.canonicalTenantId(),
+ request,
+ admission,
+ UUID.randomUUID(),
+ "f".repeat(64),
+ digest('a'),
+ new byte[] {8});
+ // Controlled SQL lineage for inspection, not a genuine execution-source observation.
+ // Establish the ordinary fenced claim before retaining its unavailable-source evidence.
+ dsl.execute(
+ "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, "
+ + "recovery_claim_fence = 1, recovery_claim_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 day' "
+ + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?",
+ UUID.randomUUID(),
+ tenant.canonicalTenantId(),
+ request,
+ admission);
+ 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) "
+ + "SELECT tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, "
+ + "recovery_policy_version, 1, CURRENT_TIMESTAMP, 'SOURCE_UNAVAILABLE' "
+ + "FROM account_tenant_capacity_reservations "
+ + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?",
+ tenant.canonicalTenantId(),
+ request,
+ admission);
+ dsl.execute(
+ "UPDATE account_tenant_capacity_reservations SET recovery_attempt_count = 1 "
+ + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?",
+ tenant.canonicalTenantId(),
+ request,
+ admission);
+ });
+ }
+
+ private static FreshTenantCreationEvidence bootstrapFreshTenant(
+ DSLContext dsl, TransactionTemplate write) {
+ FreshTenantCreationEvidence tenant = source();
+ UUID bootstrap = UUID.randomUUID();
+ write.executeWithoutResult(
+ status -> {
+ UUID account =
+ dsl.fetchSingle(
+ "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, 'test-password') RETURNING account_uuid",
+ "lineage-" + UUID.randomUUID(),
+ "lineage-" + UUID.randomUUID() + "@example.test")
+ .get(0, UUID.class);
+ new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant);
+ dsl.execute(
+ "INSERT INTO account_tenant_creation_bootstrap_operations "
+ + "(request_id, schema_version, initiating_account_uuid, tenant_uuid, creation_request_id, "
+ + "creation_operation_id, account_authorization_operation_id, account_authorization_digest, "
+ + "creator_evidence_digest, creator_evidence_payload, source_snapshot_payload, source_snapshot_digest, "
+ + "request_payload, request_digest, baseline_membership_version, baseline_membership_authority_generation, "
+ + "baseline_event_sequence, status) "
+ + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0, 'IN_PROGRESS')",
+ bootstrap,
+ account,
+ tenant.canonicalTenantId(),
+ tenant.creationRequestId(),
+ tenant.operationId(),
+ bootstrap,
+ digest('d'),
+ tenant.evidenceDigest(),
+ new byte[] {1},
+ new byte[] {2},
+ digest('e'),
+ new byte[] {3},
+ digest('f'));
+ dsl.execute(
+ "UPDATE account_tenant_creation_bootstrap_operations SET membership_id = 1, membership_version = 2, "
+ + "membership_authority_generation = 1, membership_lifecycle_state = 'ACTIVE', gameplay_admission_allowed = FALSE, "
+ + "membership_roles_payload = convert_to('[\"tenantAdmin\"]', 'UTF8'), event_stream_key = ?, "
+ + "event_request_id = ?, event_sequence = 1, event_id = ?, event_digest = ?, event_payload = ?, "
+ + "audit_event_id = ?, audit_event_type = 'ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED', "
+ + "audit_occurred_at = CURRENT_TIMESTAMP, audit_payload_digest = ?, audit_payload = ?, result_payload = ?, "
+ + "result_digest = ?, status = 'COMMITTED' WHERE request_id = ?",
+ "account:auth-authority:v1:membership/" + account + "/" + tenant.canonicalTenantId(),
+ bootstrap.toString(),
+ "lineage-bootstrap-" + bootstrap,
+ digest('1'),
+ new byte[] {4},
+ UUID.randomUUID(),
+ digest('2'),
+ new byte[] {5},
+ new byte[] {6},
+ digest('3'),
+ bootstrap);
+ });
+ return tenant;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static AccountTenantCapacityOwner capacityOwner(
+ DSLContext dsl,
+ DataSourceTransactionManager transactions,
+ TenantCapacityAdmission.Request request) {
+ var player = (TenantCapacityAdmission.PlayerContext) request.context();
+ var parsed =
+ RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(
+ request.evidence().canonicalBytes());
+ AccountRepository accounts = mock(AccountRepository.class);
+ when(accounts.findByAccountUuidForUpdate(player.accountId()))
+ .thenReturn(Optional.of(new Account()));
+ AccountCanonicalRuntimeMembershipSnapshotRepository memberships =
+ mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class);
+ when(memberships.readCurrent(player.accountId(), player.tenantId()))
+ .thenReturn(parsed.membershipSource());
+
+ Map evidenceFields = request.evidence().fields();
+ Map sourceReferences =
+ (Map) evidenceFields.get("sourceReferences");
+ Map target = (Map) evidenceFields.get("target");
+ UUID tokenJti = UUID.fromString((String) sourceReferences.get("callerTokenJti"));
+ UUID callerContextId = UUID.fromString((String) sourceReferences.get("callerContextId"));
+ UUID operationId = UUID.fromString((String) sourceReferences.get("callerOperationId"));
+ long now = Instant.now().getEpochSecond();
+ var issuanceIdentity =
+ new AccountGameplayDelegationPendingIdentity(
+ operationId,
+ request.identity().requestId(),
+ player.accountId(),
+ request.evidence().callerWorkload(),
+ callerContextId,
+ new AccountGameplayCredentialRequestBinding(1, "fixture", "f".repeat(64)),
+ "e".repeat(64),
+ tokenJti,
+ now - 10,
+ now - 10,
+ now + 3600);
+ var issuance =
+ mock(AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData.class);
+ when(issuance.identity()).thenReturn(issuanceIdentity);
+ when(issuance.tokenSha256()).thenReturn((String) sourceReferences.get("callerTokenSha256"));
+ when(issuance.canonicalRegistryRecordSha256())
+ .thenReturn((String) sourceReferences.get("callerRegistryRecordSha256"));
+ when(issuance.commitProofSha256())
+ .thenReturn((String) sourceReferences.get("callerCommitProofSha256"));
+ AccountGameplayDelegationIssuanceRepository issuances =
+ mock(AccountGameplayDelegationIssuanceRepository.class);
+ when(issuances.readCurrentCommittedCandidateByJti(tokenJti)).thenReturn(Optional.of(issuance));
+
+ var scope = mock(AccountConnectScopeRepository.CanonicalConnectScopeEvidence.class);
+ when(scope.accountUuid()).thenReturn(player.accountId());
+ when(scope.tenantUuid()).thenReturn(player.tenantId());
+ when(scope.scopeDigest()).thenReturn((String) sourceReferences.get("scopeDigest"));
+ when(scope.gameInstanceUuid()).thenReturn(player.gameInstanceId());
+ when(scope.playableStateNamespaceUuid()).thenReturn(player.playableStateNamespaceId());
+ when(scope.realmId()).thenReturn(player.realmId());
+ when(scope.playableStateScope()).thenReturn(player.playableStateScope());
+ when(scope.connectScopeExpiresAt()).thenReturn((String) target.get("connectScopeExpiresAt"));
+ AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class);
+ when(scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash()))
+ .thenReturn(Optional.of(scope));
+
+ return new AccountTenantCapacityOwner(
+ dsl, accounts, memberships, issuances, scopes, transactions, Clock.systemUTC(), "prod");
+ }
+
+ @SuppressWarnings("unchecked")
+ private static TenantCapacityAdmission.Request playerRequest(
+ UUID tenantId,
+ UUID requestId,
+ UUID admissionId,
+ UUID attemptId,
+ Instant at,
+ Instant scopeExpiry) {
+ var template = CapacityAdmissionTestFixture.playerRequest();
+ var original = (TenantCapacityAdmission.PlayerContext) template.context();
+ var player =
+ new TenantCapacityAdmission.PlayerContext(
+ original.accountId(),
+ tenantId,
+ original.playableStateNamespaceId(),
+ original.gameInstanceId(),
+ original.characterId(),
+ original.sessionId(),
+ original.realmId(),
+ requestId,
+ original.playableStateScope());
+ var target =
+ new LinkedHashMap(
+ (Map) template.evidence().fields().get("target"));
+ target.put("tenantId", tenantId.toString());
+ target.put("evaluatedAt", at.toString());
+ target.put("connectScopeExpiresAt", scopeExpiry.toString());
+ return CapacityAdmissionTestFixture.playerRequestFor(
+ player, admissionId, attemptId, "prod", target, at);
+ }
+
+ private static void insertEvaluation(
+ DSLContext dsl,
+ TenantCapacityAdmission.Request request,
+ Instant evaluatedAt,
+ Instant expiresAt) {
+ 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)",
+ request.evidence().evaluationIdentity(),
+ request.evidence().snapshotIdentity(),
+ request.identity().tenantId(),
+ request.evidence().callerWorkload(),
+ request.context().owner().service(),
+ request.evidence().canonicalBytes(),
+ evaluatedAt.toString(),
+ expiresAt.toString());
+ }
+
+ private static void waitUntil(Instant deadline) throws InterruptedException {
+ long remainingMillis = Duration.between(Instant.now(), deadline).toMillis();
+ if (remainingMillis > 0) Thread.sleep(remainingMillis);
+ }
+
+ private static FreshTenantCreationEvidence source() {
+ UUID request = UUID.randomUUID(), operation = UUID.randomUUID(), tenant = UUID.randomUUID();
+ String slug = "retention-" + UUID.randomUUID().toString().substring(0, 8);
+ String digest =
+ GameTenantCreationDigest.requestDigest("prod", request, slug, "Retention", 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"));
+ }
+
+ private static String digest(char digit) {
+ return "sha256:" + String.valueOf(digit).repeat(64);
+ }
+
+ private static String sqlState(Throwable failure) {
+ for (Throwable cause = failure; cause != null; cause = cause.getCause()) {
+ if (cause instanceof SQLException sql) return sql.getSQLState();
+ }
+ return null;
+ }
+}
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 d400e5ff28..14995bdb60 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
@@ -46,7 +46,9 @@
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.AccountCapacityOriginContinuation.Permit;
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.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure;
import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
@@ -275,7 +277,7 @@ void actualExpiredOriginPolicyRetainsBudgetAndRejectsFurtherObservation() throws
((java.time.OffsetDateTime) image.get("recovery_deadline"))
.toInstant()
.plusNanos(1000),
- java.time.ZoneOffset.UTC);
+ ZoneOffset.UTC);
assertThatThrownBy(() -> session.beginOriginObservation(expired))
.isInstanceOf(StatusRuntimeException.class);
var unknown = session.capacityOwner.resolveOrigin(session.capacityRequest, GS, false);
@@ -367,7 +369,11 @@ void actualUnknownOriginCallbackConsumesDurableBudgetWithoutInventingReservation
session.dsl.fetchCount(
org.jooq.impl.DSL.table("account_tenant_capacity_reservations")))
.isZero();
- var next = session.beginOriginObservation(CLOCK);
+ var beforeRetry = session.gs.originBudgetImage();
+ assertThatThrownBy(() -> session.beginOriginObservation(CLOCK))
+ .isInstanceOf(StatusRuntimeException.class);
+ assertThat(session.gs.originBudgetImage()).isEqualTo(beforeRetry);
+ var next = session.beginOriginObservation(Clock.fixed(permit.deadline(), ZoneOffset.UTC));
assertThat(next.ordinal()).isEqualTo(2);
}
}
@@ -381,6 +387,10 @@ void actualNoAcceptOriginCallbackRetiresOnlyExactCustodyAndExcludesDelayedCommit
var permit = session.beginOriginObservation(CLOCK);
var denied = session.capacityOwner.resolveOrigin(session.capacityRequest, GS, true);
assertThat(denied.status().name()).isEqualTo("NO_ACCEPT_RETAINED");
+ var beforeOverlap = session.gs.originBudgetImage();
+ assertThatThrownBy(() -> session.beginOriginObservation(CLOCK))
+ .isInstanceOf(StatusRuntimeException.class);
+ assertThat(session.gs.originBudgetImage()).isEqualTo(beforeOverlap);
session.deliverOriginResolution(denied, permit, CLOCK);
assertThat(session.gs.originPhysicalImage())
.containsEntry("state", "DENIED")
@@ -417,6 +427,7 @@ void actualOriginHandoffPreservesBudgetAndRefusesStillLiveOldCustodyCallback() t
"recovery_max_observations",
"recovery_observations",
"last_observation_deadline",
+ "last_observation_custody_fence",
"reservation_policy_applied"))
assertThat(moved.get(field)).isEqualTo(before.get(field));
assertThat((Long) moved.get("custody_owner_fence"))
@@ -425,15 +436,125 @@ void actualOriginHandoffPreservesBudgetAndRefusesStillLiveOldCustodyCallback() t
var physical = session.gs.originPhysicalImage();
assertThatThrownBy(() -> session.deliverOriginResolution(denied, permit, CLOCK))
.isInstanceOf(StatusRuntimeException.class);
+ var rebound =
+ new Permit(
+ permit.requestDigest(),
+ permit.originDigest(),
+ (String) moved.get("custody_owner_id"),
+ (Long) moved.get("custody_owner_fence"),
+ permit.ordinal(),
+ permit.deadline());
+ assertThatThrownBy(() -> session.deliverOriginResolution(denied, rebound, CLOCK))
+ .isInstanceOf(StatusRuntimeException.class);
assertThat(session.gs.originBudgetImage()).isEqualTo(moved);
assertThat(session.gs.originPhysicalImage()).isEqualTo(physical);
var successor = session.beginOriginObservation(CLOCK);
assertThat(successor.ordinal()).isEqualTo(2);
+ assertThat(successor.custodyFence()).isGreaterThan(permit.custodyFence());
+ assertThat(session.gs.originBudgetImage())
+ .containsEntry("last_observation_custody_fence", successor.custodyFence());
session.deliverOriginResolution(denied, successor, CLOCK);
assertThat(session.gs.originPhysicalImage()).containsEntry("state", "DENIED");
}
}
+ @Test
+ void actualTransferredOpenOriginClosesTheOriginalRetainedReservation() throws Exception {
+ try (Session session = session()) {
+ session.enableOriginReceiving();
+ var request = session.capacityRequest;
+ session.gs.prepareReceivingOrigin(request);
+ var reservation = session.capacityClient.commit(request, CLOCK.millis() + 5000);
+ assertThat(reservation.state()).isEqualTo(TenantCapacityAdmission.State.RESERVED);
+ var original = session.beginOriginObservation(CLOCK);
+ var resolution = session.capacityOwner.resolveOrigin(request, GS, false);
+ assertThat(resolution.reservation()).isEqualTo(reservation);
+ String accountBefore = session.capacityImage();
+ byte[] candidate = session.gs.physicalSession();
+ var execution =
+ new OriginalNewCapacityExecution(
+ request,
+ reservation,
+ session.gs.decisionId(),
+ "sha256:" + OriginalNewCapacityExecution.sha256(candidate),
+ original.custodyOwner(),
+ original.custodyFence());
+
+ session.gs.handoffReceivingOrigin();
+ var moved = session.gs.originBudgetImage();
+ assertThat(moved)
+ .containsEntry("state", "OPEN")
+ .containsEntry("recovery_observations", 1)
+ .containsEntry("last_observation_custody_fence", original.custodyFence());
+ assertThat(CLOCK.instant()).isBefore(original.deadline());
+ assertThatThrownBy(() -> session.deliverOriginResolution(resolution, original, CLOCK))
+ .isInstanceOf(StatusRuntimeException.class);
+ assertThat(session.gs.originBudgetImage()).isEqualTo(moved);
+ assertThat(session.gs.capacityExecutionPhysicalImage(request.admissionAttemptId()))
+ .containsOnlyKeys("pttl")
+ .containsEntry("pttl", "-2");
+
+ String transitionBefore = session.gsReceiptImage();
+ var successor = session.beginOriginObservation(CLOCK);
+ assertThat(successor.ordinal()).isEqualTo(2);
+ assertThat(successor.custodyFence()).isGreaterThan(original.custodyFence());
+ session.deliverOriginResolution(resolution, successor, CLOCK);
+ assertThat(session.gs.originBudgetImage())
+ .containsEntry("state", "CLOSURE_CLAIMED")
+ .containsEntry("last_observation_custody_fence", successor.custodyFence());
+ assertThat(session.gs.originPhysicalImage())
+ .containsEntry("state", "CLOSURE_CLAIMED")
+ .containsEntry("owner", successor.custodyOwner())
+ .containsEntry("fence", Long.toString(successor.custodyFence()))
+ .containsEntry("pttl", "-1");
+
+ var closed =
+ session
+ .gs
+ .dsl()
+ .fetchSingle("SELECT * FROM game_session_original_new_capacity_execution");
+ assertThat(closed.get("status", String.class)).isEqualTo("CLOSED");
+ assertThat(closed.get("selected_owner_id", String.class)).isEqualTo(original.custodyOwner());
+ assertThat(closed.get("selected_owner_fence", Long.class)).isEqualTo(original.custodyFence());
+ assertThat(closed.get("execution_digest", String.class)).isEqualTo(execution.digest());
+ assertThat(closed.get("canonical_execution", byte[].class))
+ .containsExactly(execution.canonicalBytes());
+ assertThat(closed.get("terminal_readback", byte[].class)).isNotEmpty();
+ assertThat(session.gs.capacityExecutionPhysicalImage(request.admissionAttemptId()))
+ .isEqualTo(
+ Map.of(
+ "state",
+ "CLOSED",
+ "digest",
+ execution.digest(),
+ "binding",
+ new String(execution.canonicalBytes(), StandardCharsets.UTF_8),
+ "pttl",
+ "-1"));
+
+ var read =
+ session.capacityRead.readExact(request, reservation, CLOCK.instant().plusSeconds(5));
+ assertThat(read.disposition())
+ .isEqualTo(
+ net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker
+ .Disposition.NOT_EXECUTED_AFTER_AUTHORIZATION);
+ assertThat(read.authenticatedOwnerWorkload()).isEqualTo(GS);
+ assertThat(read.reservation()).isEqualTo(reservation);
+ assertThat(read.currentOwnerFence()).isEqualTo(successor.custodyFence());
+ assertThat(read.authoritativeStateDigest()).isEqualTo(execution.candidateDigest());
+ var usage =
+ session.dsl.fetchSingle(
+ "SELECT held_units,used_units FROM account_tenant_capacity_usage WHERE tenant_uuid=? AND owner_service='game-session-service'",
+ request.identity().tenantId());
+ assertThat(usage.get("held_units", Long.class)).isOne();
+ assertThat(usage.get("used_units", Long.class)).isZero();
+ assertThat(session.capacityImage()).isEqualTo(accountBefore);
+ assertThat(session.gsReceiptImage()).isEqualTo(transitionBefore);
+ assertProvisionalUnchanged(session, candidate);
+ assertThat(session.gs.finalReadCalls()).isZero();
+ }
+ }
+
@Test
void originOnlyCompletedHandoffRecoversWithTheSameLivePrivateGrant() throws Exception {
try (Session session = session()) {
@@ -479,10 +600,17 @@ void actualOriginObservationExhaustionRetainsHoldAndCannotResetOnRecreatedReceiv
try (Session session = session()) {
session.enableOriginReceiving();
session.gs.prepareReceivingOrigin(session.capacityRequest);
- for (int ordinal = 1; ordinal <= 12; ordinal++)
- assertThat(session.beginOriginObservation(CLOCK).ordinal()).isEqualTo(ordinal);
+ Clock observationClock = Clock.fixed(CLOCK.instant(), ZoneOffset.UTC);
+ for (int ordinal = 1; ordinal <= 12; ordinal++) {
+ var permit = session.beginOriginObservation(observationClock, Duration.ofSeconds(2));
+ assertThat(permit.ordinal()).isEqualTo(ordinal);
+ observationClock = Clock.fixed(permit.deadline(), ZoneOffset.UTC);
+ }
var before = session.gs.originBudgetImage();
- assertThatThrownBy(() -> session.beginOriginObservation(CLOCK))
+ Clock exhaustedClock = observationClock;
+ assertThat(exhaustedClock.instant())
+ .isBefore(((java.time.OffsetDateTime) before.get("recovery_deadline")).toInstant());
+ assertThatThrownBy(() -> session.beginOriginObservation(exhaustedClock))
.isInstanceOf(StatusRuntimeException.class);
assertThat(session.gs.originBudgetImage()).isEqualTo(before).containsEntry("state", "OPEN");
assertThat(
@@ -588,6 +716,156 @@ void actualCapacityCommitAndAuthenticatedFinalReadFinalizeExactlyOneHold() throw
}
}
+ @Test
+ void historicalFinalReceiptSettlesTheSameHoldAfterPhysicalFinalLosesOriginalSqlCommit()
+ throws Exception {
+ try (Session session = session()) {
+ byte[] candidate = session.gs.physicalSession();
+ assertThatThrownBy(
+ () ->
+ session.gs.completeWithLostOriginalAdmissionCommit(
+ session.client,
+ session.jwks,
+ session.jwt,
+ System.currentTimeMillis() + 10_000L,
+ session.capacityClient,
+ session.capacityRequest))
+ .isInstanceOf(IllegalStateException.class)
+ .hasRootCauseMessage("Controlled loss of original admission SQL commit reply");
+
+ byte[] finalSession = session.gs.physicalSession();
+ assertThat(finalSession).isNotNull().isNotEqualTo(candidate);
+ var physical =
+ tools.jackson.databind.json.JsonMapper.builder().build().readTree(finalSession);
+ assertThat(physical.path("schemaVersion").asInt()).isEqualTo(2);
+ assertThat(physical.path("admissionState").asText()).isEqualTo("COMPLETE");
+ var transition =
+ session
+ .gs
+ .dsl()
+ .fetchSingle(
+ "SELECT status, original_new_final_session_sha256 FROM game_session_canonical_binding_transition WHERE transition_id = ?",
+ session.gs.decisionId());
+ assertThat(transition.get("status", String.class)).isEqualTo("PROVISIONAL");
+ assertThat(transition.get("original_new_final_session_sha256", String.class)).isNull();
+ assertThat(
+ session
+ .gs
+ .dsl()
+ .fetchSingle(
+ "SELECT status FROM game_session_original_new_capacity_execution WHERE transition_id = ?",
+ session.gs.decisionId())
+ .get(0, String.class))
+ .isEqualTo("AUTHORIZED");
+
+ var reservation =
+ session.capacityClient.commit(session.capacityRequest, CLOCK.millis() + 5_000L);
+ assertThat(reservation.state()).isEqualTo(TenantCapacityAdmission.State.RESERVED);
+ 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();
+
+ assertThatThrownBy(
+ () ->
+ session.capacityRead.readExact(
+ session.capacityRequest, reservation, CLOCK.instant().plusSeconds(5)))
+ .isInstanceOf(StatusRuntimeException.class)
+ .satisfies(
+ failure ->
+ assertThat(((StatusRuntimeException) failure).getStatus().getCode())
+ .isEqualTo(Status.Code.UNAVAILABLE));
+
+ var recovery =
+ new net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker(
+ session.capacityOwner,
+ session.dsl,
+ session.capacityRead,
+ session.capacityRead,
+ CLOCK);
+ var beforeFence = recovery.reconcileHistoricalFinal(session.capacityRequest);
+ assertThat(beforeFence.state()).isEqualTo(TenantCapacityAdmission.State.RESERVED);
+ assertThat(beforeFence.reservationId()).isEqualTo(reservation.reservationId());
+ assertThat(beforeFence.admissionAttemptId()).isEqualTo(reservation.admissionAttemptId());
+ assertThat(beforeFence.capacityRearmFence()).isEqualTo(reservation.capacityRearmFence());
+ var unresolvedUsage =
+ 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(unresolvedUsage.get("held_units", Long.class)).isOne();
+ assertThat(unresolvedUsage.get("used_units", Long.class)).isZero();
+
+ UUID fenceOperationId =
+ session.gs.acquireAccountFenceAndCaptureFinal(
+ session.capacityRequest, reservation, CLOCK.millis() + 5_000L);
+ var frozenGameSession = session.gs.capacityStateImage();
+ var frozenAccountFence = session.gs.accountAdmissionFenceImage();
+ var frozenAdmission = session.durableImage();
+ var historical =
+ session.capacityRead.readHistoricalFinal(
+ session.capacityRequest, reservation, CLOCK.instant().plusSeconds(5));
+ assertThat(historical.authenticatedOwnerWorkload()).isEqualTo(GS);
+ assertThat(historical.receipt().fenceOperationId()).isEqualTo(fenceOperationId);
+ assertThat(historical.receipt().execution().reservation()).isEqualTo(reservation);
+ assertThat(historical.receipt().finalSessionSha256())
+ .isEqualTo(
+ java.util.HexFormat.of()
+ .formatHex(MessageDigest.getInstance("SHA-256").digest(finalSession)));
+
+ var settled = recovery.reconcileHistoricalFinal(session.capacityRequest);
+ assertThat(settled.state()).isEqualTo(TenantCapacityAdmission.State.FINALIZED);
+ assertThat(settled.reservationId()).isEqualTo(reservation.reservationId());
+ assertThat(settled.reservationFence()).isEqualTo(reservation.reservationFence());
+ assertThat(settled.admissionAttemptId()).isEqualTo(reservation.admissionAttemptId());
+ assertThat(settled.capacityRearmFence()).isEqualTo(reservation.capacityRearmFence());
+
+ var replayedHistorical =
+ session.capacityRead.readHistoricalFinal(
+ session.capacityRequest, reservation, CLOCK.instant().plusSeconds(5));
+ assertThat(replayedHistorical).isEqualTo(historical);
+ assertThat(recovery.reconcileHistoricalFinal(session.capacityRequest)).isEqualTo(settled);
+ assertThatThrownBy(
+ () ->
+ session.capacityRead.readExact(
+ session.capacityRequest, reservation, CLOCK.instant().plusSeconds(5)))
+ .isInstanceOf(StatusRuntimeException.class);
+
+ var settledUsage =
+ 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(settledUsage.get("held_units", Long.class)).isZero();
+ assertThat(settledUsage.get("used_units", Long.class)).isOne();
+ assertThat(
+ session.dsl.fetchCount(
+ org.jooq.impl.DSL.table("account_tenant_capacity_reservations")))
+ .isOne();
+ assertThat(
+ session
+ .dsl
+ .fetchSingle(
+ "SELECT count(*) FROM account_tenant_capacity_recovery_evidence WHERE admission_attempt_id = ?",
+ reservation.admissionAttemptId())
+ .get(0, Long.class))
+ .isEqualTo(2L);
+ assertThat(session.gs.physicalSession()).containsExactly(finalSession);
+ assertThat(session.gs.capacityStateImage()).isEqualTo(frozenGameSession);
+ assertThat(session.gs.accountAdmissionFenceImage()).isEqualTo(frozenAccountFence);
+ assertThat(session.durableImage()).isEqualTo(frozenAdmission);
+ assertThat(
+ session
+ .gs
+ .dsl()
+ .fetchSingle(
+ "SELECT status, original_new_final_session_sha256 FROM game_session_canonical_binding_transition WHERE transition_id = ?",
+ session.gs.decisionId())
+ .get("status", String.class))
+ .isEqualTo("PROVISIONAL");
+ }
+ }
+
@Test
void retainedActualCasEvidenceStillFinalizesCapacityAfterControlledServingRetirement()
throws Exception {
@@ -1383,8 +1661,12 @@ private void enableOriginReceiving() throws Exception {
gs.enableOriginReceiving();
}
- private net.firedevops.firemud.common.account.capacity.AccountCapacityOriginContinuation.Permit
- beginOriginObservation(Clock clock) throws Exception {
+ private Permit beginOriginObservation(Clock clock) throws Exception {
+ return beginOriginObservation(clock, Duration.ofSeconds(5));
+ }
+
+ private Permit beginOriginObservation(Clock clock, Duration observationWindow)
+ throws Exception {
var receiver = gs.originReceiver(clock);
return OriginReceivingMtlsTestBridge.call(
pki.keyManagerFactory(pki.identity("gs")),
@@ -1393,13 +1675,13 @@ private void enableOriginReceiving() throws Exception {
net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest.preimage(
capacityRequest),
headers ->
- receiver.beginObservation(capacityRequest, clock.instant().plusSeconds(5), headers));
+ receiver.beginObservation(
+ capacityRequest, clock.instant().plus(observationWindow), headers));
}
private void deliverOriginResolution(
net.firedevops.firemud.common.account.capacity.AccountCapacityOriginResolution resolution,
- net.firedevops.firemud.common.account.capacity.AccountCapacityOriginContinuation.Permit
- permit,
+ Permit permit,
Clock clock)
throws Exception {
var receiver = gs.originReceiver(clock);
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java
index 012428b62e..a3c94d81c9 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java
@@ -91,14 +91,18 @@ void freshInstallAppliesEveryForwardMigrationThroughV98() {
+ "WHERE success AND version = '98'")
.fetchOne(0, String.class))
.isEqualTo("98");
- assertThat(
- context
- .dsl()
- .resultQuery(
- "SELECT count(*) FROM flyway_schema_history "
- + "WHERE version::numeric BETWEEN 74 AND 98 AND success")
- .fetchOne(0, Long.class))
- .isEqualTo(25L);
+ // Match exact scalar identities without parsing later dotted Flyway versions as numbers.
+ for (int version = 74; version <= 98; version++) {
+ assertThat(
+ context
+ .dsl()
+ .resultQuery(
+ "SELECT count(*) FROM flyway_schema_history WHERE version = ? AND success",
+ Integer.toString(version))
+ .fetchOne(0, Long.class))
+ .as("successful forward migration V%s", version)
+ .isEqualTo(1L);
+ }
for (String relation :
new String[] {
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java
index 7ec5309bec..9d9eac0ed1 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java
@@ -88,9 +88,13 @@ void boundsActualKeysAfterPressureCounterLossAndFullReset() {
service.admit(source("192.0.2." + (i + 1)), "candidate" + i + "@example.test");
assertEnvelope(inspector, policy);
}
- for (byte[] pressure :
- inspector.sync().keys(AccountCredentialAbuseSubjectKeys.PREFIX + "pressure:*")) {
- inspector.sync().del(pressure);
+ byte[][] pressureKeys =
+ inspector
+ .sync()
+ .keys(AccountCredentialAbuseSubjectKeys.PREFIX + "pressure:*")
+ .toArray(new byte[0][]);
+ if (pressureKeys.length > 0) {
+ inspector.sync().del(pressureKeys);
}
for (int i = 0; i < 24; i++) {
service.admit(source("198.51.100." + (i + 1)), "new" + i + "@example.test");
@@ -333,8 +337,7 @@ private static GenericContainer> container(boolean cluster) {
.withStartupTimeout(Duration.ofSeconds(30))
.withCreateContainerCmdModifier(
command ->
- command
- .getHostConfig()
+ java.util.Objects.requireNonNull(command.getHostConfig())
.withMemory(PROCESS_BYTES)
.withMemorySwap(PROCESS_BYTES)
.withPidsLimit(128L))
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java
index 12ce93ff0a..7a77ae23d1 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java
@@ -129,8 +129,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest {
.withStartupTimeout(java.time.Duration.ofSeconds(60))
.withCreateContainerCmdModifier(
command ->
- command
- .getHostConfig()
+ java.util.Objects.requireNonNull(command.getHostConfig())
.withMemory(512L * 1024 * 1024)
.withMemorySwap(512L * 1024 * 1024)
.withPidsLimit(256L));
@@ -144,8 +143,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest {
.withStartupTimeout(java.time.Duration.ofSeconds(30))
.withCreateContainerCmdModifier(
command ->
- command
- .getHostConfig()
+ java.util.Objects.requireNonNull(command.getHostConfig())
.withMemory(256L * 1024 * 1024)
.withMemorySwap(256L * 1024 * 1024)
.withPidsLimit(128L))
@@ -176,8 +174,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest {
.withStartupTimeout(java.time.Duration.ofSeconds(30))
.withCreateContainerCmdModifier(
command ->
- command
- .getHostConfig()
+ java.util.Objects.requireNonNull(command.getHostConfig())
.withMemory(256L * 1024 * 1024)
.withMemorySwap(256L * 1024 * 1024)
.withPidsLimit(128L))
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
index 9625545da1..cf307b5d35 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java
@@ -639,7 +639,8 @@ void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthori
assertThat(revoking.status).isEqualTo("REVOKING");
} else {
serviceClock.advance(Duration.ofSeconds(31));
- assertThatThrownBy(fixture::issueCreator).isInstanceOf(IllegalStateException.class);
+ assertThatThrownBy(fixture::issueCreator)
+ .isInstanceOf(AccountControlUiIssuanceService.PermanentRecoveryDenialException.class);
}
assertThat(
f.dsl
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClientTest.java
index 8ea923ff2f..f5cf28966d 100644
--- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClientTest.java
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeFirstInvoiceHttpClientTest.java
@@ -2,63 +2,151 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+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 com.stripe.exception.ApiConnectionException;
-import com.sun.net.httpserver.HttpServer;
-import java.io.IOException;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Flow;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Test;
+import org.springframework.test.util.ReflectionTestUtils;
class StripeFirstInvoiceHttpClientTest {
@Test
void cancelsASlowlyStreamingStripeBodyWithoutAnotherRequest() throws Exception {
- var streaming = new CountDownLatch(1);
- var closed = new CountDownLatch(1);
- var attempts = new java.util.concurrent.atomic.AtomicInteger();
- var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
- server.createContext(
- "/v1/invoices/in_exact",
- exchange -> {
- attempts.incrementAndGet();
- try (exchange) {
- exchange.getResponseHeaders().set("Content-Type", "application/json");
- exchange.sendResponseHeaders(200, 0);
- try (var body = exchange.getResponseBody()) {
- byte[] chunk = new byte[512];
- java.util.Arrays.fill(chunk, (byte) ' ');
- streaming.countDown();
- for (int index = 0; index < 150; index++) {
- body.write(chunk);
- body.flush();
- Thread.sleep(20);
+ var streaming = new CountDownLatch(5);
+ try (var server = new ServerSocket();
+ var serverExecutor = Executors.newSingleThreadExecutor();
+ var transport = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(1)).build()) {
+ server.bind(new InetSocketAddress("127.0.0.1", 0));
+ server.setSoTimeout(5_000);
+ var peerClosed =
+ serverExecutor.submit(() -> {
+ try (var peer = server.accept()) {
+ peer.setSoTimeout(5_000);
+ var inbound =
+ new BufferedReader(
+ new InputStreamReader(peer.getInputStream(), StandardCharsets.US_ASCII));
+ assertThat(inbound.readLine()).startsWith("GET /v1/invoices/in_exact HTTP/");
+ String header;
+ do {
+ header = inbound.readLine();
+ assertThat(header)
+ .as("request headers terminate before the body fixture")
+ .isNotNull();
+ } while (!header.isEmpty());
+ var outbound = peer.getOutputStream();
+ outbound.write(
+ ("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
+ + "Transfer-Encoding: chunked\r\n\r\n"
+ + "8\r\n{\"held\":\r\n")
+ .getBytes(StandardCharsets.US_ASCII));
+ outbound.flush();
+ // Keep making progress with valid JSON whitespace chunks. The provider deadline,
+ // rather than an idle socket, must end this otherwise-live response body.
+ long fixtureDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(4);
+ try {
+ byte[] chunk = "1\r\n \r\n".getBytes(StandardCharsets.US_ASCII);
+ while (System.nanoTime() < fixtureDeadline) {
+ outbound.write(chunk);
+ outbound.flush();
+ Thread.sleep(20);
+ }
+ return false;
+ } catch (java.io.IOException resetAfterBodyChunk) {
+ return true;
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ return false;
}
- } catch (IOException canceled) {
- closed.countDown();
- } catch (InterruptedException interrupted) {
- Thread.currentThread().interrupt();
}
- }
- });
- server.start();
- try {
+ });
+ var client = new StripeFirstInvoiceHttpClient(Duration.ofSeconds(1), Duration.ofSeconds(2));
+ var observedTransport = mock(HttpClient.class);
+ when(observedTransport.sendAsync(
+ any(HttpRequest.class),
+ org.mockito.ArgumentMatchers.>any()))
+ .thenAnswer(invocation -> {
+ HttpRequest request = invocation.getArgument(0);
+ HttpResponse.BodyHandler handler = invocation.getArgument(1);
+ return transport.sendAsync(
+ request, response -> observeBodyChunks(handler.apply(response), streaming));
+ });
+ ReflectionTestUtils.setField(client, "transport", observedTransport);
var stripe =
com.stripe.StripeClient.builder()
.setApiKey("sk_test_controlled")
- .setApiBase("http://127.0.0.1:" + server.getAddress().getPort())
+ .setApiBase("http://127.0.0.1:" + server.getLocalPort())
.setMaxNetworkRetries(0)
- .setHttpClient(
- new StripeFirstInvoiceHttpClient(Duration.ofSeconds(1), Duration.ofMillis(500)))
+ .setHttpClient(client)
.build();
- assertThatThrownBy(() -> stripe.invoices().retrieve("in_exact"))
- .isInstanceOf(ApiConnectionException.class);
- assertThat(streaming.getCount()).isZero();
- assertThat(closed.await(2, TimeUnit.SECONDS)).isTrue();
- assertThat(attempts.get()).isOne();
- } finally {
- server.stop(0);
+ assertTimeoutPreemptively(
+ Duration.ofSeconds(5),
+ () ->
+ assertThatThrownBy(() -> stripe.invoices().retrieve("in_exact"))
+ .isInstanceOf(ApiConnectionException.class)
+ .hasMessageContaining("First-invoice provider response deadline expired")
+ .hasCauseInstanceOf(TimeoutException.class));
+ assertThat(streaming.await(1, TimeUnit.SECONDS))
+ .as("the client continued receiving small chunks without an idle gap")
+ .isTrue();
+ assertThat(peerClosed.get(5, TimeUnit.SECONDS))
+ .as("the real client closed the peer connection after receiving body bytes")
+ .isTrue();
+ verify(observedTransport)
+ .sendAsync(
+ any(HttpRequest.class),
+ org.mockito.ArgumentMatchers.>any());
}
}
+
+ private static HttpResponse.BodySubscriber observeBodyChunks(
+ HttpResponse.BodySubscriber delegate, CountDownLatch observed) {
+ return new HttpResponse.BodySubscriber<>() {
+ @Override
+ public CompletionStage getBody() {
+ return delegate.getBody();
+ }
+
+ @Override
+ public void onSubscribe(Flow.Subscription subscription) {
+ delegate.onSubscribe(subscription);
+ }
+
+ @Override
+ public void onNext(List chunks) {
+ boolean receivedBytes = chunks.stream().anyMatch(ByteBuffer::hasRemaining);
+ delegate.onNext(chunks);
+ if (receivedBytes) observed.countDown();
+ }
+
+ @Override
+ public void onError(Throwable failure) {
+ delegate.onError(failure);
+ }
+
+ @Override
+ public void onComplete() {
+ delegate.onComplete();
+ }
+ };
+ }
}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwnerTest.java
new file mode 100644
index 0000000000..385aa1b127
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwnerTest.java
@@ -0,0 +1,512 @@
+package 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.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+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.time.Instant;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionInspectionOwner.Blocker;
+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 org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jooq.Result;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.TransactionStatus;
+import org.springframework.transaction.support.SimpleTransactionStatus;
+
+/** Controlled read-only inspection proof, not approval, live hold authority or deletion proof. */
+class AccountCapacityEvaluationRetentionInspectionOwnerTest {
+ private static final Instant NOW = Instant.parse("2026-11-11T12:00:00Z");
+
+ @Test
+ void inspectionBoundsApplyBeforeAnyDatabaseWork() {
+ DSLContext dsl = mock(DSLContext.class);
+ PlatformTransactionManager transactions = mock(PlatformTransactionManager.class);
+ var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, transactions);
+ for (int invalid : new int[] {-1, 0, 1001, Integer.MAX_VALUE}) {
+ assertThatThrownBy(() -> owner.observe(invalid)).isInstanceOf(IllegalArgumentException.class);
+ }
+ verifyNoInteractions(dsl, transactions);
+ }
+
+ @Test
+ void observationUsesOneBoundedOldestWindowAndFixedBlockerCategoriesWithoutReadingPayloads() {
+ DSLContext dsl = mock(DSLContext.class);
+ Record metadata = mock(Record.class);
+ when(metadata.get("observed_at", OffsetDateTime.class)).thenReturn(at(NOW));
+ when(metadata.get("relation_bytes", Long.class)).thenReturn(4096L);
+ when(metadata.get("estimated_rows", Long.class)).thenReturn(-1L);
+ when(dsl.fetchOne(anyString())).thenReturn(metadata);
+ Result rows = result();
+ when(rows.size()).thenReturn(4);
+ Record referenced = row(NOW.minusSeconds(30), NOW.minusSeconds(20), true, 262144);
+ Record expired = row(NOW.minusSeconds(20), NOW.minusSeconds(1), false, 3);
+ Record live = row(NOW.minusSeconds(10), NOW.plusSeconds(1), false, 5);
+ when(rows.get(0)).thenReturn(referenced);
+ when(rows.get(1)).thenReturn(expired);
+ when(rows.get(2)).thenReturn(live);
+ when(dsl.fetch(anyString(), any(Object[].class))).thenReturn(rows);
+ var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, new ReadTransactions());
+
+ var observation = owner.observe(3);
+
+ assertThat(observation.totalRelationBytes()).isEqualTo(4096);
+ assertThat(observation.estimatedTableRows()).isEmpty();
+ assertThat(observation.sampledRows()).isEqualTo(3);
+ assertThat(observation.sampleTruncated()).isTrue();
+ assertThat(observation.governanceBlocker())
+ .isEqualTo(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE);
+ assertThat(observation.scheduleVersion()).isEmpty();
+ assertThat(observation.candidates().rows()).isZero();
+ assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).evidenceBytes())
+ .isEqualTo(262144);
+ assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).oldestEvaluatedAt())
+ .contains(NOW.minusSeconds(30));
+ assertThat(observation.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows())
+ .isEqualTo(1);
+ assertThat(observation.blockers().get(Blocker.LIVE_EVALUATION).rows()).isEqualTo(1);
+ ArgumentCaptor query = ArgumentCaptor.forClass(String.class);
+ verify(dsl).fetch(query.capture(), eq(4));
+ assertThat(query.getValue())
+ .contains("LIMIT ?", "octet_length(canonical_evidence)")
+ .contains("reservation.tenant_uuid = sample.tenant_uuid")
+ .contains("reservation.owner_service = sample.owner_service")
+ .doesNotContain("reservation.evaluation_identity", "DELETE", "UPDATE", "SUM(", "COUNT(");
+ assertThatThrownBy(() -> observation.blockers().clear())
+ .isInstanceOf(UnsupportedOperationException.class);
+ }
+
+ @Test
+ void emptyTableHasNoInventedOldestBlockerAndCatalogEstimateStaysExplicit() {
+ DSLContext dsl = mock(DSLContext.class);
+ Record metadata = mock(Record.class);
+ when(metadata.get("observed_at", OffsetDateTime.class)).thenReturn(at(NOW));
+ when(metadata.get("relation_bytes", Long.class)).thenReturn(8192L);
+ when(metadata.get("estimated_rows", Long.class)).thenReturn(0L);
+ when(dsl.fetchOne(anyString())).thenReturn(metadata);
+ Result rows = result();
+ when(rows.size()).thenReturn(0);
+ when(dsl.fetch(anyString(), any(Object[].class))).thenReturn(rows);
+ var observation =
+ new AccountCapacityEvaluationRetentionInspectionOwner(dsl, new ReadTransactions())
+ .observe(1000);
+ assertThat(observation.sampledRows()).isZero();
+ assertThat(observation.sampleTruncated()).isFalse();
+ assertThat(observation.estimatedTableRows()).hasValue(0);
+ assertThat(observation.governanceBlocker())
+ .isEqualTo(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE);
+ assertThat(observation.blockers().values())
+ .allSatisfy(
+ window -> {
+ assertThat(window.rows()).isZero();
+ assertThat(window.evidenceBytes()).isZero();
+ assertThat(window.oldestEvaluatedAt()).isEmpty();
+ });
+ verify(dsl).fetch(anyString(), eq(1001));
+ }
+
+ @Test
+ void currentPolicyUsesExactHistoryLineageAndLeavesAnUnrelatedEvaluationUnblocked() {
+ DSLContext dsl = mock(DSLContext.class);
+ metadata(dsl);
+ TenantCapacityAdmission.Request request = CapacityAdmissionTestFixture.playerRequest();
+ String referencedIdentity = request.evidence().evaluationIdentity();
+ String unrelatedIdentity = "sha256:" + "c".repeat(64);
+ Result samples = result();
+ when(samples.size()).thenReturn(2);
+ Instant evaluated = NOW.minusSeconds(10 * 86400L);
+ doReturn(sample(referencedIdentity, true, false, evaluated)).when(samples).get(0);
+ doReturn(sample(unrelatedIdentity, true, false, evaluated)).when(samples).get(1);
+ Result reservations = result();
+ when(reservations.size()).thenReturn(1);
+ when(reservations.iterator()).thenAnswer(ignored -> List.of(reservations.get(0)).iterator());
+ doReturn(reservation(request)).when(reservations).get(0);
+ Result historyKeys = result();
+ when(historyKeys.size()).thenReturn(1);
+ when(historyKeys.iterator()).thenAnswer(ignored -> List.of(historyKeys.get(0)).iterator());
+ doReturn(historyKey(request)).when(historyKeys).get(0);
+ Result payloads = result();
+ when(payloads.size()).thenReturn(1);
+ when(payloads.iterator()).thenAnswer(ignored -> List.of(payloads.get(0)).iterator());
+ doReturn(historyPayload(request)).when(payloads).get(0);
+ when(dsl.fetch(anyString(), any(Object[].class)))
+ .thenAnswer(
+ invocation -> {
+ String query = invocation.getArgument(0);
+ if (query.contains("WITH sample AS MATERIALIZED")) return samples;
+ if (query.contains("WITH scopes(tenant_uuid")) return reservations;
+ if (query.contains("WITH reservations(tenant_uuid")) return historyKeys;
+ if (query.contains("WITH selected(tenant_uuid")) return payloads;
+ throw new AssertionError("Unexpected inspection query: " + query);
+ });
+
+ var observation =
+ owner(dsl).observe(2, schedule(), safety(referencedIdentity, unrelatedIdentity));
+
+ assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isEqualTo(1);
+ assertThat(observation.candidates().rows()).isEqualTo(1);
+ assertThat(observation.governanceBlocker()).isNull();
+ verify(dsl, times(4)).fetch(anyString(), any(Object[].class));
+ }
+
+ @Test
+ void historyAbovePerScopeBoundFailsClosedWithoutReadingPayloads() {
+ DSLContext dsl = mock(DSLContext.class);
+ metadata(dsl);
+ TenantCapacityAdmission.Request request = CapacityAdmissionTestFixture.playerRequest();
+ Result samples = result();
+ when(samples.size()).thenReturn(1);
+ doReturn(sample("sha256:" + "c".repeat(64), true, false, NOW.minusSeconds(10 * 86400L)))
+ .when(samples)
+ .get(0);
+ Result reservations = result();
+ when(reservations.size()).thenReturn(1);
+ when(reservations.iterator()).thenAnswer(ignored -> List.of(reservations.get(0)).iterator());
+ doReturn(reservation(request)).when(reservations).get(0);
+ Result historyKeys = result();
+ when(historyKeys.size()).thenReturn(9);
+ when(historyKeys.iterator())
+ .thenAnswer(
+ ignored ->
+ java.util.stream.IntStream.range(0, 9).mapToObj(historyKeys::get).iterator());
+ for (int index = 0; index < 9; index++) {
+ doReturn(historyKey(request, UUID.randomUUID())).when(historyKeys).get(index);
+ }
+ when(dsl.fetch(anyString(), any(Object[].class)))
+ .thenAnswer(
+ invocation -> {
+ String query = invocation.getArgument(0);
+ if (query.contains("WITH sample AS MATERIALIZED")) return samples;
+ if (query.contains("WITH scopes(tenant_uuid")) return reservations;
+ if (query.contains("WITH reservations(tenant_uuid")) return historyKeys;
+ throw new AssertionError("Over-limit lineage must not fetch payload bytes");
+ });
+
+ var observation = owner(dsl).observe(1, schedule(), safety("sha256:" + "c".repeat(64)));
+
+ assertThat(observation.candidates().rows()).isZero();
+ assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isOne();
+ }
+
+ @Test
+ void malformedHistoryPayloadFailsClosedForItsScope() {
+ DSLContext dsl = mock(DSLContext.class);
+ metadata(dsl);
+ TenantCapacityAdmission.Request request = CapacityAdmissionTestFixture.playerRequest();
+ Result samples = result();
+ when(samples.size()).thenReturn(1);
+ doReturn(sample("sha256:" + "c".repeat(64), true, false, NOW.minusSeconds(10 * 86400L)))
+ .when(samples)
+ .get(0);
+ Result reservations = result();
+ when(reservations.size()).thenReturn(1);
+ when(reservations.iterator()).thenAnswer(ignored -> List.of(reservations.get(0)).iterator());
+ doReturn(reservation(request)).when(reservations).get(0);
+ Result historyKeys = result();
+ when(historyKeys.size()).thenReturn(1);
+ when(historyKeys.iterator()).thenAnswer(ignored -> List.of(historyKeys.get(0)).iterator());
+ doReturn(historyKey(request)).when(historyKeys).get(0);
+ Result payloads = result();
+ when(payloads.size()).thenReturn(1);
+ when(payloads.iterator()).thenAnswer(ignored -> List.of(payloads.get(0)).iterator());
+ Record malformed = historyPayload(request);
+ when(malformed.get("canonical_payload", byte[].class)).thenReturn(new byte[] {1});
+ doReturn(malformed).when(payloads).get(0);
+ when(dsl.fetch(anyString(), any(Object[].class)))
+ .thenAnswer(
+ invocation -> {
+ String query = invocation.getArgument(0);
+ if (query.contains("WITH sample AS MATERIALIZED")) return samples;
+ if (query.contains("WITH scopes(tenant_uuid")) return reservations;
+ if (query.contains("WITH reservations(tenant_uuid")) return historyKeys;
+ if (query.contains("WITH selected(tenant_uuid")) return payloads;
+ throw new AssertionError("Unexpected inspection query: " + query);
+ });
+
+ var observation = owner(dsl).observe(1, schedule(), safety("sha256:" + "c".repeat(64)));
+
+ assertThat(observation.candidates().rows()).isZero();
+ assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isOne();
+ }
+
+ @Test
+ void missingFenceInRetainedHistoryChainFailsClosed() {
+ DSLContext dsl = mock(DSLContext.class);
+ metadata(dsl);
+ TenantCapacityAdmission.Request request = CapacityAdmissionTestFixture.playerRequest();
+ Result samples = result();
+ when(samples.size()).thenReturn(1);
+ doReturn(sample("sha256:" + "c".repeat(64), true, false, NOW.minusSeconds(10 * 86400L)))
+ .when(samples)
+ .get(0);
+ Result reservations = result();
+ when(reservations.size()).thenReturn(1);
+ when(reservations.iterator()).thenAnswer(ignored -> List.of(reservations.get(0)).iterator());
+ doReturn(reservation(request, 3L)).when(reservations).get(0);
+ Result historyKeys = result();
+ when(historyKeys.size()).thenReturn(1);
+ when(historyKeys.iterator()).thenAnswer(ignored -> List.of(historyKeys.get(0)).iterator());
+ doReturn(historyKey(request)).when(historyKeys).get(0);
+ when(dsl.fetch(anyString(), any(Object[].class)))
+ .thenAnswer(
+ invocation -> {
+ String query = invocation.getArgument(0);
+ if (query.contains("WITH sample AS MATERIALIZED")) return samples;
+ if (query.contains("WITH scopes(tenant_uuid")) return reservations;
+ if (query.contains("WITH reservations(tenant_uuid")) return historyKeys;
+ throw new AssertionError(
+ "A gap in the fence chain must be found before payload reads");
+ });
+
+ var observation = owner(dsl).observe(1, schedule(), safety("sha256:" + "c".repeat(64)));
+
+ assertThat(observation.candidates().rows()).isZero();
+ assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isOne();
+ }
+
+ @Test
+ void aggregateHistoryBoundFailsClosedForAllQueriedScopesWithoutPayloadReads() {
+ DSLContext dsl = mock(DSLContext.class);
+ metadata(dsl);
+ Result samples = result();
+ Result reservations = result();
+ Result historyKeys = result();
+ int scopeCount = 4;
+ when(samples.size()).thenReturn(scopeCount);
+ when(reservations.size()).thenReturn(scopeCount);
+ when(reservations.iterator())
+ .thenAnswer(
+ ignored ->
+ java.util.stream.IntStream.range(0, scopeCount)
+ .mapToObj(reservations::get)
+ .iterator());
+ when(historyKeys.size()).thenReturn(33);
+ Instant evaluated = NOW.minusSeconds(10 * 86400L);
+ List identities = new java.util.ArrayList<>();
+ for (int scopeIndex = 0; scopeIndex < scopeCount; scopeIndex++) {
+ UUID tenantId = UUID.randomUUID();
+ UUID requestId = UUID.randomUUID();
+ UUID admissionId = UUID.randomUUID();
+ UUID evaluationId = UUID.randomUUID();
+ String identity = "sha256:" + evaluationId.toString().replace("-", "");
+ identities.add(identity);
+ doReturn(sample(identity, tenantId, true, false, evaluated)).when(samples).get(scopeIndex);
+ doReturn(reservation(tenantId, requestId, admissionId)).when(reservations).get(scopeIndex);
+ }
+ for (int index = 0; index < 33; index++) {
+ int scopeIndex = index % scopeCount;
+ Record reservation = reservations.get(scopeIndex);
+ doReturn(
+ historyKey(
+ reservation.get("tenant_uuid", UUID.class),
+ reservation.get("request_id", UUID.class),
+ reservation.get("admission_id", UUID.class),
+ UUID.randomUUID()))
+ .when(historyKeys)
+ .get(index);
+ }
+ when(dsl.fetch(anyString(), any(Object[].class)))
+ .thenAnswer(
+ invocation -> {
+ String query = invocation.getArgument(0);
+ if (query.contains("WITH sample AS MATERIALIZED")) return samples;
+ if (query.contains("WITH scopes(tenant_uuid")) return reservations;
+ if (query.contains("WITH reservations(tenant_uuid")) return historyKeys;
+ throw new AssertionError("Aggregate over-limit lineage must not fetch payload bytes");
+ });
+
+ var observation = owner(dsl).observe(4, schedule(), safety(identities.toArray(String[]::new)));
+
+ assertThat(observation.candidates().rows()).isZero();
+ assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows())
+ .isEqualTo(scopeCount);
+ verify(dsl, times(3)).fetch(anyString(), any(Object[].class));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Result result() {
+ return mock(Result.class);
+ }
+
+ private static Record row(Instant evaluated, Instant expires, boolean referenced, long bytes) {
+ Record row = mock(Record.class);
+ when(row.get("evaluation_identity", String.class)).thenReturn("sha256:" + "a".repeat(64));
+ when(row.get("tenant_uuid", UUID.class)).thenReturn(CapacityAdmissionTestFixture.TENANT);
+ when(row.get("owner_service", String.class)).thenReturn("game-session-service");
+ when(row.get("evaluated_at", OffsetDateTime.class)).thenReturn(at(evaluated));
+ when(row.get("expires_at", OffsetDateTime.class)).thenReturn(at(expires));
+ when(row.get("scope_referenced", Boolean.class)).thenReturn(referenced);
+ when(row.get("evidence_bytes", Long.class)).thenReturn(bytes);
+ return row;
+ }
+
+ private static Record metadata(DSLContext dsl) {
+ Record metadata = mock(Record.class);
+ when(metadata.get("observed_at", OffsetDateTime.class)).thenReturn(at(NOW));
+ when(metadata.get("relation_bytes", Long.class)).thenReturn(4096L);
+ when(metadata.get("estimated_rows", Long.class)).thenReturn(2L);
+ when(dsl.fetchOne(anyString())).thenReturn(metadata);
+ return metadata;
+ }
+
+ private static AccountCapacityEvaluationRetentionInspectionOwner owner(DSLContext dsl) {
+ return new AccountCapacityEvaluationRetentionInspectionOwner(dsl, new ReadTransactions());
+ }
+
+ private static AccountCapacityEvaluationRetentionPolicy.Schedule schedule() {
+ return new AccountCapacityEvaluationRetentionPolicy.Schedule(
+ "fixture/v1",
+ java.time.Duration.ofDays(30),
+ java.time.Duration.ofDays(2),
+ java.time.Duration.ofDays(3),
+ java.time.Duration.ofDays(4),
+ java.time.Duration.ofDays(5),
+ java.time.Duration.ofDays(6));
+ }
+
+ private static AccountCapacityEvaluationRetentionPolicy.Safety safety(String... identities) {
+ Map holds = new java.util.HashMap<>();
+ for (String identity : identities)
+ holds.put(identity, AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR);
+ return new AccountCapacityEvaluationRetentionPolicy.Safety(
+ "fixture/v1", NOW.minusSeconds(1), NOW.plusSeconds(60), NOW.minusSeconds(1), holds);
+ }
+
+ private static Record sample(
+ String identity, boolean scopeReferenced, boolean direct, Instant evaluated) {
+ return sample(
+ identity, CapacityAdmissionTestFixture.TENANT, scopeReferenced, direct, evaluated);
+ }
+
+ private static Record sample(
+ String identity, UUID tenantId, boolean scopeReferenced, boolean direct, Instant evaluated) {
+ Record row = mock(Record.class);
+ when(row.get("evaluation_identity", String.class)).thenReturn(identity);
+ when(row.get("tenant_uuid", UUID.class)).thenReturn(tenantId);
+ when(row.get("owner_service", String.class)).thenReturn("game-session-service");
+ when(row.get("evaluated_at", OffsetDateTime.class)).thenReturn(at(evaluated));
+ when(row.get("expires_at", OffsetDateTime.class)).thenReturn(at(evaluated.plusSeconds(1)));
+ when(row.get("evidence_bytes", Long.class)).thenReturn(10L);
+ when(row.get("scope_referenced", Boolean.class)).thenReturn(scopeReferenced);
+ when(row.get("directly_referenced", Boolean.class)).thenReturn(direct);
+ return row;
+ }
+
+ private static Record reservation(TenantCapacityAdmission.Request request) {
+ return reservation(request, 2L);
+ }
+
+ private static Record reservation(TenantCapacityAdmission.Request request, long rearmFence) {
+ Record row =
+ reservation(
+ request.identity().tenantId(),
+ request.identity().requestId(),
+ request.identity().admissionId());
+ when(row.get("owner_service", String.class)).thenReturn(request.context().owner().service());
+ when(row.get("caller_workload", String.class)).thenReturn(request.evidence().callerWorkload());
+ when(row.get("capacity_rearm_fence", Long.class)).thenReturn(rearmFence);
+ return row;
+ }
+
+ private static Record reservation(UUID tenantId, UUID requestId, UUID admissionId) {
+ Record row = mock(Record.class);
+ when(row.get("tenant_uuid", UUID.class)).thenReturn(tenantId);
+ when(row.get("owner_service", String.class)).thenReturn("game-session-service");
+ when(row.get("request_id", UUID.class)).thenReturn(requestId);
+ when(row.get("admission_id", UUID.class)).thenReturn(admissionId);
+ when(row.get("capacity_rearm_fence", Long.class)).thenReturn(2L);
+ when(row.get("caller_workload", String.class)).thenReturn("test-workload");
+ return row;
+ }
+
+ private static Record historyKey(TenantCapacityAdmission.Request request) {
+ return historyKey(request, request.admissionAttemptId());
+ }
+
+ private static Record historyKey(TenantCapacityAdmission.Request request, UUID attemptId) {
+ Record row =
+ historyKey(
+ request.identity().tenantId(),
+ request.identity().requestId(),
+ request.identity().admissionId(),
+ attemptId);
+ when(row.get("owner_service", String.class)).thenReturn(request.context().owner().service());
+ when(row.get("capacity_rearm_fence", Long.class)).thenReturn(request.capacityRearmFence());
+ when(row.get("mutation_digest", String.class)).thenReturn(request.mutationDigest());
+ when(row.get("caller_workload", String.class)).thenReturn(request.evidence().callerWorkload());
+ when(row.get("payload_bytes", Long.class))
+ .thenReturn((long) CapacityAdmissionDigest.preimage(request).length);
+ return row;
+ }
+
+ private static Record historyKey(
+ UUID tenantId, UUID requestId, UUID admissionId, UUID attemptId) {
+ Record row = mock(Record.class);
+ when(row.get("tenant_uuid", UUID.class)).thenReturn(tenantId);
+ when(row.get("owner_service", String.class)).thenReturn("game-session-service");
+ when(row.get("request_id", UUID.class)).thenReturn(requestId);
+ when(row.get("admission_id", UUID.class)).thenReturn(admissionId);
+ when(row.get("admission_attempt_id", UUID.class)).thenReturn(attemptId);
+ when(row.get("caller_workload", String.class)).thenReturn("test-workload");
+ when(row.get("capacity_rearm_fence", Long.class)).thenReturn(1L);
+ when(row.get("mutation_digest", String.class)).thenReturn("f".repeat(64));
+ when(row.get("payload_bytes", Long.class)).thenReturn(1L);
+ return row;
+ }
+
+ private static Record historyPayload(TenantCapacityAdmission.Request request) {
+ 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("capacity_rearm_fence", Long.class)).thenReturn(request.capacityRearmFence());
+ when(row.get("mutation_digest", String.class)).thenReturn(request.mutationDigest());
+ when(row.get("canonical_payload", byte[].class))
+ .thenReturn(CapacityAdmissionDigest.preimage(request));
+ return row;
+ }
+
+ private static OffsetDateTime at(Instant value) {
+ return value.atOffset(ZoneOffset.UTC);
+ }
+
+ private static final class ReadTransactions implements PlatformTransactionManager {
+ @Override
+ public TransactionStatus getTransaction(
+ @org.jspecify.annotations.Nullable TransactionDefinition definition) {
+ assertThat(definition).isNotNull();
+ assertThat(definition.getPropagationBehavior())
+ .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+ assertThat(definition.getIsolationLevel())
+ .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ);
+ assertThat(definition.isReadOnly()).isTrue();
+ assertThat(definition.getTimeout()).isEqualTo(5);
+ return new SimpleTransactionStatus();
+ }
+
+ @Override
+ public void commit(TransactionStatus status) {}
+
+ @Override
+ public void rollback(TransactionStatus status) {}
+ }
+}
diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicyTest.java
new file mode 100644
index 0000000000..053515bc2c
--- /dev/null
+++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicyTest.java
@@ -0,0 +1,207 @@
+package net.firedevops.firemud.accountservice.service;
+
+import static net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.classify;
+import static net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.current;
+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.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.Classification;
+import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.Hold;
+import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.Safety;
+import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.Schedule;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jooq.Result;
+import org.junit.jupiter.api.Test;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.support.SimpleTransactionStatus;
+
+class AccountCapacityEvaluationRetentionPolicyTest {
+ private static final String VERSION = "test-capacity-retention/v1";
+ private static final String EVALUATION = "sha256:" + "a".repeat(64);
+ private static final Instant EVALUATED = Instant.parse("2026-01-01T00:00:00Z");
+ private static final Instant EXPIRES = EVALUATED.plus(Duration.ofDays(1));
+ private static final Instant OBSERVED = EVALUATED.plus(Duration.ofDays(5));
+
+ @Test
+ void candidateRequiresAllWindowsToCloseAndIncludesTheWatermarkBoundary() {
+ var schedule = schedule(Duration.ofDays(6), Duration.ofDays(2));
+ var safety = safety(VERSION, EVALUATED, Map.of(EVALUATION, Hold.CLEAR));
+
+ assertThat(classify(schedule, safety, OBSERVED, EVALUATION, EVALUATED, EXPIRES, false))
+ .isEqualTo(Classification.CANDIDATE);
+ assertThat(
+ classify(
+ schedule, safety, OBSERVED.minusNanos(1), EVALUATION, EVALUATED, EXPIRES, false))
+ .isEqualTo(Classification.RETENTION_WINDOW_OPEN);
+ assertThat(
+ classify(
+ schedule,
+ safety(VERSION, EVALUATED.minusNanos(1), Map.of(EVALUATION, Hold.CLEAR)),
+ OBSERVED,
+ EVALUATION,
+ EVALUATED,
+ EXPIRES,
+ false))
+ .isEqualTo(Classification.ABOVE_SAFE_WATERMARK);
+ assertThat(
+ classify(
+ schedule, safety, OBSERVED, EVALUATION, EVALUATED, OBSERVED.plusNanos(1), false))
+ .isEqualTo(Classification.LIVE_EVALUATION);
+ assertThat(classify(schedule, safety, OBSERVED, EVALUATION, EVALUATED, EXPIRES, true))
+ .isEqualTo(Classification.RETAINED_RESERVATION_SCOPE);
+ }
+
+ @Test
+ void heldMissingStaleAndMismatchedObservationsRefuse() {
+ var schedule = schedule(Duration.ofDays(6), Duration.ofDays(2));
+ var holds = new HashMap<>(Map.of(EVALUATION, Hold.HELD));
+ var held = safety(VERSION, EVALUATED, holds);
+ holds.put(EVALUATION, Hold.CLEAR);
+ assertThat(classify(schedule, held, OBSERVED, EVALUATION, EVALUATED, EXPIRES, false))
+ .isEqualTo(Classification.HELD);
+ assertThat(current(schedule, held, held.observedAt())).isTrue();
+ assertThat(current(schedule, held, held.observedAt().minusNanos(1))).isFalse();
+ assertThat(current(schedule, held, held.validUntil())).isFalse();
+ assertThat(current(null, held, OBSERVED)).isFalse();
+ assertThat(current(schedule, null, OBSERVED)).isFalse();
+ assertThat(classify(schedule, held, OBSERVED, EVALUATION, EVALUATED, EXPIRES, null))
+ .isEqualTo(Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE);
+ assertThat(classify(schedule, held, held.validUntil(), EVALUATION, EVALUATED, EXPIRES, false))
+ .isEqualTo(Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE);
+ assertThat(classify(schedule, null, OBSERVED, EVALUATION, EVALUATED, EXPIRES, false))
+ .isEqualTo(Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE);
+ for (var unavailable :
+ new Safety[] {
+ safety("other-version", EVALUATED, Map.of(EVALUATION, Hold.CLEAR)),
+ safety(VERSION, EVALUATED, Map.of())
+ }) {
+ assertThat(classify(schedule, unavailable, OBSERVED, EVALUATION, EVALUATED, EXPIRES, false))
+ .isEqualTo(Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE);
+ }
+ }
+
+ @Test
+ void malformedScheduleAndUnboundedOrContradictorySafetyRefuse() {
+ assertThatThrownBy(() -> schedule(Duration.ofDays(6), Duration.ZERO))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> schedule(Duration.ofDays(6), Duration.ofDays(7)))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> new Safety(VERSION, OBSERVED, OBSERVED, EVALUATED, Map.of()))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> safety(VERSION, OBSERVED.plusSeconds(1), Map.of()))
+ .isInstanceOf(IllegalArgumentException.class);
+ Map oversized =
+ IntStream.rangeClosed(0, AccountCapacityEvaluationRetentionInspectionOwner.MAX_SAMPLE_ROWS)
+ .boxed()
+ .collect(Collectors.toMap(index -> "test-evaluation-" + index, index -> Hold.CLEAR));
+ assertThatThrownBy(() -> safety(VERSION, EVALUATED, oversized))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void qualifiedObservationCountsOnlyUnheldUnreferencedCandidatesWithoutWrites() {
+ DSLContext database = mock(DSLContext.class);
+ Record relation = mock(Record.class);
+ when(relation.get("observed_at", OffsetDateTime.class))
+ .thenReturn(OBSERVED.atOffset(ZoneOffset.UTC));
+ when(relation.get("relation_bytes", Long.class)).thenReturn(4096L);
+ when(relation.get("estimated_rows", Long.class)).thenReturn(4L);
+ when(database.fetchOne(anyString())).thenReturn(relation);
+ Result rows = mock(Result.class);
+ when(rows.size()).thenReturn(4);
+ String held = "sha256:" + "b".repeat(64);
+ String unknown = "sha256:" + "c".repeat(64);
+ String referenced = "sha256:" + "d".repeat(64);
+ var candidateRow = evaluation(EVALUATION, false);
+ var heldRow = evaluation(held, false);
+ var unknownRow = evaluation(unknown, false);
+ var referencedRow = evaluation(referenced, true);
+ when(rows.get(0)).thenReturn(candidateRow);
+ when(rows.get(1)).thenReturn(heldRow);
+ when(rows.get(2)).thenReturn(unknownRow);
+ when(rows.get(3)).thenReturn(referencedRow);
+ when(database.fetch(anyString(), any(Object[].class))).thenReturn(rows);
+ PlatformTransactionManager transactions = mock(PlatformTransactionManager.class);
+ when(transactions.getTransaction(any())).thenAnswer(call -> new SimpleTransactionStatus());
+ var owner = new AccountCapacityEvaluationRetentionInspectionOwner(database, transactions);
+ var schedule = schedule(Duration.ofDays(6), Duration.ofDays(2));
+ var safety =
+ safety(
+ VERSION,
+ EVALUATED,
+ Map.of(EVALUATION, Hold.CLEAR, held, Hold.HELD, referenced, Hold.CLEAR));
+
+ var report = owner.observe(4, schedule, safety);
+
+ assertThat(report.scheduleVersion()).contains(VERSION);
+ assertThat(report.governanceBlocker()).isNull();
+ assertThat(report.candidates().rows()).isEqualTo(1);
+ assertThat(report.candidates().evidenceBytes()).isEqualTo(12);
+ assertThat(
+ report
+ .blockers()
+ .get(AccountCapacityEvaluationRetentionInspectionOwner.Blocker.HELD)
+ .rows())
+ .isEqualTo(1);
+ assertThat(
+ report
+ .blockers()
+ .get(
+ AccountCapacityEvaluationRetentionInspectionOwner.Blocker
+ .POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE)
+ .rows())
+ .isEqualTo(1);
+ assertThat(
+ report
+ .blockers()
+ .get(
+ AccountCapacityEvaluationRetentionInspectionOwner.Blocker
+ .RETAINED_RESERVATION_SCOPE)
+ .rows())
+ .isEqualTo(1);
+ verify(database, never()).execute(anyString(), any(Object[].class));
+ }
+
+ private static Record evaluation(String identity, boolean referenced) {
+ Record row = mock(Record.class);
+ when(row.get("evaluation_identity", String.class)).thenReturn(identity);
+ when(row.get("evaluated_at", OffsetDateTime.class))
+ .thenReturn(EVALUATED.atOffset(ZoneOffset.UTC));
+ when(row.get("expires_at", OffsetDateTime.class)).thenReturn(EXPIRES.atOffset(ZoneOffset.UTC));
+ when(row.get("evidence_bytes", Long.class)).thenReturn(12L);
+ when(row.get("scope_referenced", Boolean.class)).thenReturn(referenced);
+ when(row.get("directly_referenced", Boolean.class)).thenReturn(referenced);
+ return row;
+ }
+
+ private static Schedule schedule(Duration maximum, Duration evidence) {
+ return new Schedule(
+ VERSION,
+ maximum,
+ evidence,
+ Duration.ofDays(1),
+ Duration.ofDays(3),
+ Duration.ofDays(5),
+ Duration.ofDays(4));
+ }
+
+ private static Safety safety(String version, Instant watermark, Map holds) {
+ return new Safety(version, OBSERVED.minusSeconds(1), OBSERVED.plusSeconds(1), watermark, holds);
+ }
+}
diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java
index 4f47e873dd..5d363e4a17 100644
--- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java
+++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java
@@ -35,8 +35,7 @@ public static GenericContainer> container() {
.withStartupTimeout(Duration.ofSeconds(30))
.withCreateContainerCmdModifier(
command ->
- command
- .getHostConfig()
+ java.util.Objects.requireNonNull(command.getHostConfig())
.withMemory(PROCESS_BYTES)
.withMemorySwap(PROCESS_BYTES)
.withPidsLimit(128L))
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
index 5536f68777..a2024da01d 100644
--- 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
@@ -1,12 +1,18 @@
package net.firedevops.firemud.common.account.capacity;
import java.io.ByteArrayOutputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Normalizer;
+import java.util.Arrays;
import java.util.Base64;
import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.Map;
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;
@@ -117,6 +123,122 @@ public static String digest(Request request) {
}
}
+ /**
+ * Decodes the one canonical capacity-admission/1 preimage accepted for a new committable
+ * admission. The digest and Account evidence remain content bindings, not proof of authority.
+ */
+ public static Request decodeCommittable(byte[] canonicalPreimage, String mutationDigest) {
+ try {
+ if (canonicalPreimage == null
+ || canonicalPreimage.length == 0
+ || canonicalPreimage.length > MAX_PREIMAGE_BYTES
+ || mutationDigest == null
+ || mutationDigest.length() != 64
+ || !mutationDigest.matches("[0-9a-f]{64}")) throw invalid();
+
+ byte[] preimageBytes = canonicalPreimage.clone();
+ var parser = new Frame(preimageBytes);
+ if (!"mutationDigest/v1".equals(parser.segment())) throw invalid();
+ Map fields = parser.fields(7, 0);
+ if (!parser.done()
+ || !TenantCapacityAdmission.SCHEMA_ID.equals(text(fields, "actionFamilySchemaId"))
+ || !TenantCapacityAdmission.SCHEMA_VERSION.equals(
+ text(fields, "actionFamilySchemaVersion"))) throw invalid();
+
+ var scope = object(fields, "scope");
+ var target = object(fields, "target");
+ var expected = object(fields, "expectedVersion");
+ var mutation = object(fields, "mutation");
+ var identity =
+ new TenantCapacityAdmission.Identity(
+ uuid(scope, "tenantId"), uuid(scope, "requestId"), uuid(scope, "admissionId"));
+
+ String ownerService = text(target, "ownerService");
+ var contextFields = object(target, "ownerContext");
+ TenantCapacityAdmission.OwnerContext context;
+ TenantCapacityAdmission.Owner owner;
+ if (TenantCapacityAdmission.Owner.GAME_SESSION.service().equals(ownerService)) {
+ owner = TenantCapacityAdmission.Owner.GAME_SESSION;
+ context =
+ new PlayerContext(
+ uuid(contextFields, "accountId"),
+ uuid(contextFields, "tenantId"),
+ uuid(contextFields, "playableStateNamespaceId"),
+ uuid(contextFields, "gameInstanceId"),
+ uuid(contextFields, "characterId"),
+ uuid(contextFields, "sessionId"),
+ uuid(contextFields, "realmId"),
+ uuid(contextFields, "requestId"),
+ text(contextFields, "playableStateScope"));
+ } else if (TenantCapacityAdmission.Owner.WORLD_MANAGEMENT.service().equals(ownerService)) {
+ owner = TenantCapacityAdmission.Owner.WORLD_MANAGEMENT;
+ context =
+ new WorldContext(
+ uuid(contextFields, "tenantId"),
+ uuid(contextFields, "operationId"),
+ uuid(contextFields, "lifecycleId"),
+ uuid(contextFields, "gameInstanceId"),
+ uuid(contextFields, "ownerId"),
+ number(contextFields, "ownerFence"));
+ } else {
+ throw invalid();
+ }
+
+ Object rawCapacityDelta = mutation.get("capacityDelta");
+ Long capacityDelta;
+ if (rawCapacityDelta == null) capacityDelta = null;
+ else if (rawCapacityDelta instanceof Long value) capacityDelta = value;
+ else throw invalid();
+ Request request =
+ new Request(
+ identity,
+ uuid(expected, "admissionAttemptId"),
+ number(expected, "capacityRearmFence"),
+ text(target, "targetNamespace"),
+ context,
+ TenantCapacityAdmission.Operation.valueOf(text(mutation, "operation")),
+ shape(object(mutation, "priorShape")),
+ shape(object(mutation, "requestedShape")),
+ TenantCapacityAdmission.Evidence.parse(
+ Base64.getDecoder().decode(text(mutation, "accountEvidence")), owner),
+ capacityDelta,
+ mutationDigest);
+ if (!Arrays.equals(preimageBytes, preimage(request))) throw invalid();
+ request.requireCommittable();
+ return request;
+ } catch (RuntimeException malformed) {
+ throw invalid();
+ }
+ }
+
+ private static Map object(Map fields, String key) {
+ if (!(fields.get(key) instanceof Map, ?> value)) throw invalid();
+ @SuppressWarnings("unchecked")
+ Map result = (Map) value;
+ return result;
+ }
+
+ private static String text(Map fields, String key) {
+ if (!(fields.get(key) instanceof String value)) throw invalid();
+ return value;
+ }
+
+ private static long number(Map fields, String key) {
+ if (!(fields.get(key) instanceof Long value)) throw invalid();
+ return value;
+ }
+
+ private static java.util.UUID uuid(Map fields, String key) {
+ return java.util.UUID.fromString(text(fields, key));
+ }
+
+ private static Shape shape(Map fields) {
+ return new Shape(
+ number(fields, "activeSessions"),
+ number(fields, "concurrentGameInstances"),
+ number(fields, "storageBytes"));
+ }
+
private static byte[] shape(Shape shape) {
return object(
"activeSessions",
@@ -185,4 +307,102 @@ private static byte[] ascii(String value) {
private static IllegalArgumentException invalid() {
return new IllegalArgumentException("Invalid capacity-admission/1 canonical value");
}
+
+ private static String decodeUtf8(byte[] bytes) {
+ try {
+ return StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ } catch (CharacterCodingException malformed) {
+ throw invalid();
+ }
+ }
+
+ /** Bounded parser for the shared ADR 0047 frame grammar. */
+ private static final class Frame {
+ private final byte[] data;
+ private int offset;
+
+ private Frame(byte[] data) {
+ if (data == null || data.length > MAX_PREIMAGE_BYTES) throw invalid();
+ this.data = data;
+ }
+
+ private String segment() {
+ return decodeUtf8(segmentBytes());
+ }
+
+ private byte[] segmentBytes() {
+ int start = offset;
+ while (offset < data.length && data[offset] >= '0' && data[offset] <= '9') offset++;
+ int digits = offset - start;
+ if (digits == 0
+ || digits > 7
+ || offset >= data.length
+ || data[offset++] != ':'
+ || (digits > 1 && data[start] == '0')) throw invalid();
+ int size;
+ try {
+ size = Integer.parseInt(new String(data, start, digits, StandardCharsets.US_ASCII));
+ } catch (NumberFormatException malformed) {
+ throw invalid();
+ }
+ if (size < 0 || size > MAX_SEGMENT_BYTES || size > data.length - offset) throw invalid();
+ byte[] result = Arrays.copyOfRange(data, offset, offset + size);
+ offset += size;
+ return result;
+ }
+
+ private Map fields(int count, int depth) {
+ if (count < 0 || count > 16 || depth > 8) throw invalid();
+ Map result = new LinkedHashMap<>();
+ for (int index = 0; index < count; index++) {
+ String name = segment();
+ String type = segment();
+ if (offset >= data.length) throw invalid();
+ byte presence = data[offset++];
+ byte[] payload = segmentBytes();
+ Object value;
+ if ("object".equals(type) && presence == '1') {
+ Frame nested = new Frame(payload);
+ Map object = nested.fields(parseCount(nested.segment()), depth + 1);
+ if (!nested.done()) throw invalid();
+ value = object;
+ } else if ("string".equals(type) && presence == '1') {
+ value = decodeUtf8(payload);
+ } else if ("number".equals(type) && presence == '1') {
+ String number = decodeUtf8(payload);
+ if (!number.matches("0|[1-9][0-9]{0,18}")) throw invalid();
+ try {
+ value = Long.parseLong(number);
+ } catch (NumberFormatException overflow) {
+ throw invalid();
+ }
+ } else if ("absent".equals(type) && presence == '0' && payload.length == 0) {
+ value = null;
+ } else {
+ throw invalid();
+ }
+ if (result.containsKey(name)) throw invalid();
+ result.put(name, value);
+ }
+ return result;
+ }
+
+ private static int parseCount(String value) {
+ if (value == null || !value.matches("0|[1-9][0-9]{0,1}")) throw invalid();
+ try {
+ return Integer.parseInt(value);
+ } catch (NumberFormatException malformed) {
+ throw invalid();
+ }
+ }
+
+ private boolean done() {
+ return offset == data.length;
+ }
+ }
}
diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java
index a8f6b0e863..53bb3b9041 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
@@ -4,6 +4,7 @@
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
@@ -20,6 +21,38 @@
/** Shared vectors prove content encoding only, never a current Account or runtime grant. */
class CapacityAdmissionDigestTest {
+ @Test
+ void decodesCommittablePreimagesForPlayerAndWorldOwners() {
+ for (Request request :
+ List.of(
+ CapacityAdmissionTestFixture.playerRequest(),
+ CapacityAdmissionTestFixture.worldRequest(17L))) {
+ assertThat(
+ CapacityAdmissionDigest.decodeCommittable(
+ CapacityAdmissionDigest.preimage(request), request.mutationDigest()))
+ .isEqualTo(request);
+ }
+ }
+
+ @Test
+ void rejectsMalformedPreimagesAndInvalidOrIncorrectDigests() {
+ Request request = CapacityAdmissionTestFixture.playerRequest();
+ byte[] preimage = CapacityAdmissionDigest.preimage(request);
+ byte[] trailing = Arrays.copyOf(preimage, preimage.length + 1);
+ trailing[trailing.length - 1] = 'x';
+ String incorrectDigest =
+ (request.mutationDigest().charAt(0) == '0' ? "1" : "0")
+ + request.mutationDigest().substring(1);
+
+ assertThatThrownBy(
+ () -> CapacityAdmissionDigest.decodeCommittable(trailing, request.mutationDigest()))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> CapacityAdmissionDigest.decodeCommittable(preimage, "bad-digest"))
+ .isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> CapacityAdmissionDigest.decodeCommittable(preimage, incorrectDigest))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
@Test
void sharedCorpusFixesCompleteEvidenceAndAbsentZeroPositiveBoundaryPreimages() throws Exception {
var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json");
diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecutionReadGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecutionReadGrpcCodec.java
index 308171c427..68a9514859 100644
--- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecutionReadGrpcCodec.java
+++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecutionReadGrpcCodec.java
@@ -5,6 +5,7 @@
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
+import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalNewCapacityFinalResponse;
import net.firedevops.firemud.gamesession.v1.ReadOriginalNewCapacityExecutionRequest;
import net.firedevops.firemud.gamesession.v1.ReadOriginalNewCapacityExecutionResponse;
@@ -54,6 +55,36 @@ public String toString() {
}
}
+ public record HistoricalFinalReadback(
+ OriginalNewCapacityExecution execution,
+ UUID fenceOperationId,
+ String finalSessionSha256,
+ long admissionAtMillis,
+ long continuityExpiresAtMillis,
+ String inventorySnapshotRevision,
+ String cohortDigest,
+ String barrierTargetDigest) {
+ public HistoricalFinalReadback {
+ TenantCapacityAdmission.uuid(fenceOperationId);
+ if (execution.reservation().state() != TenantCapacityAdmission.State.RESERVED
+ || finalSessionSha256 == null
+ || !finalSessionSha256.matches("[0-9a-f]{64}")
+ || admissionAtMillis <= 0
+ || continuityExpiresAtMillis <= admissionAtMillis
+ || inventorySnapshotRevision == null
+ || !inventorySnapshotRevision.matches("[1-9][0-9]*")
+ || cohortDigest == null
+ || !cohortDigest.matches("sha256:[0-9a-f]{64}")
+ || barrierTargetDigest == null
+ || !barrierTargetDigest.matches("sha256:[0-9a-f]{64}")) throw invalid();
+ }
+
+ @Override
+ public String toString() {
+ return "OriginalNewHistoricalFinalReadback[redacted]";
+ }
+ }
+
public static ReadOriginalNewCapacityExecutionRequest toRequest(Selector selector) {
var wire =
ReadOriginalNewCapacityExecutionRequest.newBuilder()
@@ -128,6 +159,57 @@ public static Readback fromResponse(
one(wire.getCurrentOwnerFenceList()));
}
+ public static ReadHistoricalOriginalNewCapacityFinalResponse toHistoricalResponse(
+ Selector selector, HistoricalFinalReadback receipt) {
+ var execution = receipt.execution();
+ if (!selector.request().equals(execution.request())
+ || !selector.reservation().equals(execution.reservation())) throw invalid();
+ var wire =
+ ReadHistoricalOriginalNewCapacityFinalResponse.newBuilder()
+ .addSelector(toRequest(selector))
+ .addFenceOperationId(receipt.fenceOperationId().toString())
+ .addTransitionId(execution.transitionId().toString())
+ .addCandidateDigest(execution.candidateDigest())
+ .addSelectedOwnerId(execution.selectedOwnerId())
+ .addSelectedOwnerFence(execution.selectedOwnerFence())
+ .addCanonicalExecution(ByteString.copyFrom(execution.canonicalBytes()))
+ .addFinalSessionSha256(receipt.finalSessionSha256())
+ .addAdmissionAtMs(receipt.admissionAtMillis())
+ .addContinuityExpiresAtMs(receipt.continuityExpiresAtMillis())
+ .addInventorySnapshotRevision(receipt.inventorySnapshotRevision())
+ .addCohortDigest(receipt.cohortDigest())
+ .addBarrierTargetDigest(receipt.barrierTargetDigest())
+ .build();
+ clean(wire, MAX_RESPONSE_BYTES);
+ return wire;
+ }
+
+ public static HistoricalFinalReadback fromHistoricalResponse(
+ Selector selector, ReadHistoricalOriginalNewCapacityFinalResponse wire) {
+ clean(wire, MAX_RESPONSE_BYTES);
+ if (!selector.equals(parseRequest(one(wire.getSelectorList())))) throw invalid();
+ var execution =
+ new OriginalNewCapacityExecution(
+ selector.request(),
+ selector.reservation(),
+ uuid(one(wire.getTransitionIdList())),
+ one(wire.getCandidateDigestList()),
+ one(wire.getSelectedOwnerIdList()),
+ one(wire.getSelectedOwnerFenceList()));
+ if (!Arrays.equals(
+ execution.canonicalBytes(), one(wire.getCanonicalExecutionList()).toByteArray()))
+ throw invalid();
+ return new HistoricalFinalReadback(
+ execution,
+ uuid(one(wire.getFenceOperationIdList())),
+ one(wire.getFinalSessionSha256List()),
+ one(wire.getAdmissionAtMsList()),
+ one(wire.getContinuityExpiresAtMsList()),
+ one(wire.getInventorySnapshotRevisionList()),
+ one(wire.getCohortDigestList()),
+ one(wire.getBarrierTargetDigestList()));
+ }
+
private static T one(List values) {
if (values.size() != 1) throw invalid();
return values.getFirst();
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 d8df54ff1e..bcd044dce2 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
@@ -87,6 +87,51 @@ void duplicateUnknownChangedReservationPayloadDigestAndOriginalFenceFailClosed()
.isInstanceOf(IllegalArgumentException.class);
}
+ @Test
+ void historicalFinalRetainsTheOriginalExecutionAndRejectsMalformedProof() {
+ var selector = selector();
+ var execution = execution(selector);
+ var operation = UUID.fromString("d4444444-4444-4444-8444-444444444444");
+ long admissionAt = CapacityAdmissionTestFixture.NOW.toEpochMilli();
+ var proof =
+ new OriginalNewCapacityExecutionReadGrpcCodec.HistoricalFinalReadback(
+ execution,
+ operation,
+ "b".repeat(64),
+ admissionAt,
+ admissionAt + 60_000,
+ "3",
+ "sha256:" + "c".repeat(64),
+ "sha256:" + "d".repeat(64));
+ var wire = OriginalNewCapacityExecutionReadGrpcCodec.toHistoricalResponse(selector, proof);
+ var decoded = OriginalNewCapacityExecutionReadGrpcCodec.fromHistoricalResponse(selector, wire);
+ assertThat(decoded.execution().canonicalBytes()).containsExactly(execution.canonicalBytes());
+ assertThat(OriginalNewCapacityExecutionReadGrpcCodec.toHistoricalResponse(selector, decoded))
+ .isEqualTo(wire);
+
+ var unknown =
+ UnknownFieldSet.newBuilder()
+ .addField(999, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
+ .build();
+ var reservation = wire.getSelector(0).getReservation(0);
+ var changedCommitment = reservation.getCommitment(0).toBuilder().setReservationFence(0, 2);
+ var changedReservation = reservation.toBuilder().setCommitment(0, changedCommitment);
+ var changedSelector = wire.getSelector(0).toBuilder().setReservation(0, changedReservation);
+ for (var malformed :
+ List.of(
+ wire.toBuilder().setSelector(0, changedSelector).build(),
+ wire.toBuilder().addFenceOperationId(operation.toString()).build(),
+ wire.toBuilder().setCanonicalExecution(0, ByteString.copyFromUtf8("changed")).build(),
+ wire.toBuilder().setContinuityExpiresAtMs(0, admissionAt).build(),
+ wire.toBuilder().setUnknownFields(unknown).build())) {
+ assertThatThrownBy(
+ () ->
+ OriginalNewCapacityExecutionReadGrpcCodec.fromHistoricalResponse(
+ selector, malformed))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ }
+
private static OriginalNewCapacityExecutionReadGrpcCodec.Selector selector() {
var request = CapacityAdmissionTestFixture.playerRequest();
var reservation =
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java
index 39977d3bb7..575a963eb2 100644
--- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java
@@ -10,6 +10,7 @@
import java.time.Clock;
import java.time.OffsetDateTime;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
@@ -18,6 +19,8 @@
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
+import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution;
+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.json.Rfc8785CanonicalJson;
@@ -26,6 +29,7 @@
import org.jooq.Record;
import org.jooq.impl.DSL;
import org.springframework.transaction.support.TransactionSynchronizationManager;
+import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
@@ -280,19 +284,224 @@ Optional readFinalObservation(UUID operationId) {
+ " WHERE o.operation_id = ?",
operationId);
if (row == null) return Optional.empty();
- return Optional.of(
- new HistoricalFinalObservation(
- operationId,
- row.get("transition_id", UUID.class),
- row.get("admission_attempt_id", UUID.class),
- row.get("execution_digest", String.class),
- row.get("candidate_digest", String.class),
- row.get("final_session_sha256", String.class),
- row.get("admission_at_ms", Long.class),
- row.get("continuity_expires_at_ms", Long.class),
- readBigInteger(row, "inventory_snapshot_revision"),
- row.get("cohort_digest", String.class),
- row.get("barrier_target_digest", String.class)));
+ return Optional.of(historicalObservation(row));
+ }
+
+ /**
+ * Reads the unique immutable pre-intent FINAL observation for this exact retained reservation.
+ * This path reads only retained execution and fence-observation/intent rows; it does not consult
+ * current account control, admission, serving, or physical owner state.
+ */
+ Optional readHistoricalFinalReceipt(Request request, Result reservation) {
+ if (!validHistoricalSelector(request, reservation)) return Optional.empty();
+ requireNoAmbientTransaction();
+
+ var player = (TenantCapacityAdmission.PlayerContext) request.context();
+ return dsl.transactionResult(
+ configuration -> {
+ DSLContext transaction = DSL.using(configuration);
+ transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY");
+
+ List retainedRows =
+ transaction.fetch(
+ "SELECT tenant_id, request_id, admission_id, admission_attempt_id,"
+ + " capacity_rearm_fence, reservation_id, reservation_fence, mutation_digest,"
+ + " transition_id, execution_digest, canonical_execution, selected_owner_id,"
+ + " selected_owner_fence FROM game_session_original_new_capacity_execution"
+ + " WHERE tenant_id = ? AND request_id = ? AND admission_id = ?"
+ + " AND admission_attempt_id = ? AND capacity_rearm_fence = ?"
+ + " AND reservation_id = ? AND reservation_fence = ? AND mutation_digest = ?",
+ request.identity().tenantId(),
+ request.identity().requestId(),
+ request.identity().admissionId(),
+ request.admissionAttemptId(),
+ request.capacityRearmFence(),
+ reservation.reservationId(),
+ reservation.reservationFence(),
+ request.mutationDigest());
+ if (retainedRows.size() != 1) return Optional.empty();
+
+ Record retained = retainedRows.get(0);
+ OriginalNewCapacityExecution execution;
+ try {
+ byte[] canonical = retained.get("canonical_execution", byte[].class);
+ execution = CanonicalGameplayRegionOwnerTransferRepository.decode(canonical);
+ OriginalNewCapacityExecution selected =
+ new OriginalNewCapacityExecution(
+ request,
+ reservation,
+ execution.transitionId(),
+ execution.candidateDigest(),
+ execution.selectedOwnerId(),
+ execution.selectedOwnerFence());
+ if (!(execution.request().context()
+ instanceof TenantCapacityAdmission.PlayerContext retainedPlayer)) {
+ return Optional.empty();
+ }
+ if (!Arrays.equals(canonical, execution.canonicalBytes())
+ || !Arrays.equals(canonical, selected.canonicalBytes())
+ || !execution.digest().equals(retained.get("execution_digest", String.class))
+ || !execution.transitionId().equals(retained.get("transition_id", UUID.class))
+ || !execution
+ .request()
+ .admissionAttemptId()
+ .equals(retained.get("admission_attempt_id", UUID.class))
+ || !execution
+ .selectedOwnerId()
+ .equals(retained.get("selected_owner_id", String.class))
+ || execution.selectedOwnerFence()
+ != retained.get("selected_owner_fence", Long.class)
+ || !player.accountId().equals(retainedPlayer.accountId())
+ || !player.tenantId().equals(retainedPlayer.tenantId())) {
+ return Optional.empty();
+ }
+ } catch (RuntimeException malformedRetainedExecution) {
+ return Optional.empty();
+ }
+
+ List observations =
+ transaction.fetch(
+ "SELECT * FROM "
+ + FINAL_OBSERVATION
+ + " WHERE account_id = ? AND transition_id = ?"
+ + " AND admission_attempt_id = ? AND execution_digest = ?"
+ + " AND candidate_digest = ? LIMIT 2",
+ player.accountId(),
+ execution.transitionId(),
+ request.admissionAttemptId(),
+ execution.digest(),
+ execution.candidateDigest());
+ if (observations.size() != 1) return Optional.empty();
+
+ Record observationRow = observations.get(0);
+ UUID operationId = observationRow.get("operation_id", UUID.class);
+ if (operationId == null) return Optional.empty();
+ UUID retainedAccountId = observationRow.get("account_id", UUID.class);
+ if (!player.accountId().equals(retainedAccountId)) return Optional.empty();
+ Record intentRow =
+ transaction.fetchOne(
+ "SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId);
+ if (intentRow == null) return Optional.empty();
+
+ CanonicalGameplayAccountAdmissionFenceIntent intent;
+ HistoricalFinalObservation observation;
+ try {
+ intent = loadImmutableIntent(transaction, intentRow);
+ observation = historicalObservation(observationRow);
+ } catch (RuntimeException malformedHistory) {
+ return Optional.empty();
+ }
+ try {
+ if (!exactHistoricalWitness(
+ intent,
+ observation,
+ execution,
+ player.accountId(),
+ player.tenantId(),
+ player.playableStateNamespaceId())) return Optional.empty();
+ return Optional.of(
+ new HistoricalFinalReceipt(
+ retainedAccountId, player.tenantId(), execution, observation));
+ } catch (RuntimeException malformedWitness) {
+ return Optional.empty();
+ }
+ });
+ }
+
+ private static boolean validHistoricalSelector(Request request, Result reservation) {
+ try {
+ Objects.requireNonNull(request, "request").requireCommittable();
+ Objects.requireNonNull(reservation, "reservation").requireBinding(request);
+ if (reservation.state() != TenantCapacityAdmission.State.RESERVED
+ || !(request.context() instanceof TenantCapacityAdmission.PlayerContext player)
+ || player.owner() != TenantCapacityAdmission.Owner.GAME_SESSION
+ || !request.identity().tenantId().equals(player.tenantId())) return false;
+ // The execution constructor enforces the exact original-NEW shape and transition binding.
+ return true;
+ } catch (RuntimeException malformedSelector) {
+ return false;
+ }
+ }
+
+ private static HistoricalFinalObservation historicalObservation(Record row) {
+ return new HistoricalFinalObservation(
+ row.get("operation_id", UUID.class),
+ row.get("transition_id", UUID.class),
+ row.get("admission_attempt_id", UUID.class),
+ row.get("execution_digest", String.class),
+ row.get("candidate_digest", String.class),
+ row.get("final_session_sha256", String.class),
+ row.get("admission_at_ms", Long.class),
+ row.get("continuity_expires_at_ms", Long.class),
+ readBigInteger(row, "inventory_snapshot_revision"),
+ row.get("cohort_digest", String.class),
+ row.get("barrier_target_digest", String.class));
+ }
+
+ private static boolean exactHistoricalWitness(
+ CanonicalGameplayAccountAdmissionFenceIntent intent,
+ HistoricalFinalObservation observation,
+ OriginalNewCapacityExecution execution,
+ UUID accountId,
+ UUID tenantId,
+ UUID playableStateNamespaceId) {
+ if (!(execution.request().context() instanceof TenantCapacityAdmission.PlayerContext player)) {
+ return false;
+ }
+ if (!intent.accountId().equals(accountId)
+ || !intent.operationId().equals(observation.operationId())
+ || !accountId.equals(player.accountId())
+ || !tenantId.equals(execution.request().identity().tenantId())
+ || !tenantId.equals(player.tenantId())
+ || !observation.transitionId().equals(execution.transitionId())
+ || !observation.admissionAttemptId().equals(execution.request().admissionAttemptId())
+ || !observation.executionDigest().equals(execution.digest())
+ || !observation.candidateDigest().equals(execution.candidateDigest())
+ || !observation.inventorySnapshotRevision().equals(intent.inventorySnapshotRevision())
+ || !observation.cohortDigest().equals(intent.cohortDigest())
+ || !observation.barrierTargetDigest().equals(intent.barrierTargetDigest())
+ || observation.finalSessionSha256() == null
+ || !observation.finalSessionSha256().matches("[0-9a-f]{64}")
+ || observation.admissionAtMillis() <= 0
+ || observation.continuityExpiresAtMillis() <= observation.admissionAtMillis()) return false;
+
+ List transitionRows =
+ intent.cohortRows().stream()
+ .filter(
+ row ->
+ row.kind() == CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.TRANSITION
+ && row.sourceKey().equals(execution.transitionId().toString()))
+ .toList();
+ if (transitionRows.size() != 1) return false;
+ var transition = transitionRows.get(0);
+ if (!tenantId.equals(transition.tenantId())
+ || !playableStateNamespaceId.equals(transition.playableStateNamespaceId())
+ || !frozenCandidateMatches(transition, execution)) return false;
+
+ long targetMatches =
+ intent.barrierTargets().stream()
+ .filter(
+ target ->
+ tenantId.equals(target.tenantId())
+ && playableStateNamespaceId.equals(target.playableStateNamespaceId()))
+ .count();
+ return targetMatches == 1;
+ }
+
+ private static boolean frozenCandidateMatches(
+ CanonicalGameplayAccountAdmissionFenceIntent.CohortRow transition,
+ OriginalNewCapacityExecution execution) {
+ try {
+ JsonNode source = CLOSED_BARRIER_JSON.readTree(transition.sourceRecordJson());
+ return source != null
+ && "PROVISIONAL".equals(source.path("status").textValue())
+ && execution.transitionId().toString().equals(source.path("transition_id").textValue())
+ && execution
+ .candidateDigest()
+ .equals(source.path("original_new_candidate_digest").textValue());
+ } catch (RuntimeException malformedSnapshot) {
+ return false;
+ }
}
private record PreIntentFinalObservation(
@@ -314,6 +523,34 @@ record HistoricalFinalObservation(
String cohortDigest,
String barrierTargetDigest) {}
+ record HistoricalFinalReceipt(
+ UUID accountId,
+ UUID tenantId,
+ OriginalNewCapacityExecution execution,
+ HistoricalFinalObservation observation) {
+ HistoricalFinalReceipt {
+ Objects.requireNonNull(accountId, "accountId");
+ Objects.requireNonNull(tenantId, "tenantId");
+ Objects.requireNonNull(execution, "execution");
+ Objects.requireNonNull(observation, "observation");
+ if (!(execution.request().context() instanceof TenantCapacityAdmission.PlayerContext player)
+ || !accountId.equals(player.accountId())
+ || !tenantId.equals(player.tenantId())
+ || execution.reservation().state() != TenantCapacityAdmission.State.RESERVED
+ || !observation.transitionId().equals(execution.transitionId())
+ || !observation.admissionAttemptId().equals(execution.request().admissionAttemptId())
+ || !observation.executionDigest().equals(execution.digest())
+ || !observation.candidateDigest().equals(execution.candidateDigest())) {
+ throw new IllegalArgumentException(
+ "Historical FINAL receipt is not an exact retained witness");
+ }
+ }
+
+ UUID operationId() {
+ return observation.operationId();
+ }
+ }
+
/** Reads and verifies the immutable persisted tuple, cohort rows, and target rows. */
CanonicalGameplayAccountAdmissionFenceIntent readFenceIntent(UUID accountId, UUID requestId) {
requireNonNil(accountId, "accountId");
@@ -926,6 +1163,44 @@ private static void requireBarrierTargetsCoverCohort(
}
}
+ /** Revalidates only immutable intent evidence; it deliberately does not read account control. */
+ private static CanonicalGameplayAccountAdmissionFenceIntent loadImmutableIntent(
+ DSLContext transaction, Record intent) {
+ UUID operationId =
+ Objects.requireNonNull(intent.get("operation_id", UUID.class), "operation id");
+ UUID accountId = Objects.requireNonNull(intent.get("account_id", UUID.class), "account id");
+ if (!"ACQUISITION_INTENT".equals(intent.get("intent_state", String.class))) {
+ throw conflict("Historical FINAL observation is not bound to an acquisition intent");
+ }
+ List cohortRows =
+ readCohortRows(transaction, operationId);
+ List barrierTargets =
+ readBarrierTargets(transaction, operationId);
+ String cohortDigest = digestCohortRows(cohortRows);
+ String targetDigest = digestBarrierTargets(barrierTargets);
+ if (cohortRows.size() != readLong(intent, "cohort_row_count")
+ || !cohortDigest.equals(intent.get("cohort_digest", String.class))
+ || barrierTargets.size() != readLong(intent, "barrier_target_count")
+ || !targetDigest.equals(intent.get("barrier_target_digest", String.class))) {
+ throw conflict("Immutable account-fence intent cohort or barrier target changed on readback");
+ }
+ requireResolvableCohortScopes(cohortRows);
+ requireBarrierTargetsCoverCohort(cohortRows, barrierTargets);
+ return new CanonicalGameplayAccountAdmissionFenceIntent(
+ operationId,
+ intent.get("request_id", UUID.class),
+ accountId,
+ readBigInteger(intent, "operation_fence"),
+ intent.get("planned_account_admission_fence", UUID.class),
+ readBigInteger(intent, "inventory_snapshot_revision"),
+ readPersistedLegacyDisposition(intent),
+ CanonicalGameplayAccountAdmissionFenceIntent.State.ACQUISITION_INTENT,
+ cohortRows,
+ barrierTargets,
+ cohortDigest,
+ targetDigest);
+ }
+
private static CanonicalGameplayAccountAdmissionFenceIntent loadAndRequireCurrent(
DSLContext transaction, Record control, Record intent) {
UUID operationId =
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginRepository.java
index fcfc3ef2b5..7ee11b6339 100644
--- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginRepository.java
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginRepository.java
@@ -215,6 +215,13 @@ private static Retained claimBytesInTransaction(
var retained = exact(row, origin);
if (!retained.ownerId().equals(current.ownerId())
|| retained.ownerFence() != current.ownerFence()) throw unavailable();
+ var lastDeadline = row.get("last_observation_deadline", java.time.OffsetDateTime.class);
+ Long issuingFence = row.get("last_observation_custody_fence", Long.class);
+ // Keep the live permit until expiry unless custody has advanced past its issuing fence.
+ if (lastDeadline != null
+ && now.isBefore(lastDeadline.toInstant())
+ && (issuingFence == null || issuingFence >= retained.ownerFence()))
+ throw unavailable();
var policy =
new net.firedevops.firemud.common.account.capacity.AccountCapacityOriginContinuation
.Policy(
@@ -228,9 +235,10 @@ private static Retained claimBytesInTransaction(
if (tx.execute(
"UPDATE "
+ TABLE
- + " SET recovery_observations=?,last_observation_deadline=?::timestamptz WHERE admission_attempt_id=? AND recovery_observations=?",
+ + " SET recovery_observations=?,last_observation_deadline=?::timestamptz,last_observation_custody_fence=? WHERE admission_attempt_id=? AND recovery_observations=?",
admission.ordinal(),
admission.deadline().toString(),
+ retained.ownerFence(),
origin.request().admissionAttemptId(),
consumed)
!= 1) throw unavailable();
@@ -260,8 +268,11 @@ static boolean requireObservationInTransaction(
refuseFrozen(tx, origin);
Record row = find(tx, origin, true);
var retained = exact(row, origin);
+ Long issuingFence = row.get("last_observation_custody_fence", Long.class);
if (!retained.ownerId().equals(permit.custodyOwner())
|| retained.ownerFence() != permit.custodyFence()
+ || issuingFence == null
+ || issuingFence != permit.custodyFence()
|| row.get("recovery_observations", Integer.class) != permit.ordinal()
|| !row.get("last_observation_deadline", java.time.OffsetDateTime.class)
.toInstant()
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepository.java
index d49100f03a..3a67833418 100644
--- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepository.java
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepository.java
@@ -6,6 +6,7 @@
import java.util.List;
import java.util.Objects;
import java.util.UUID;
+import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest;
import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution;
import org.jooq.DSLContext;
import org.jooq.Record;
@@ -550,7 +551,7 @@ private static byte[] encodeReadback(Item item, String state) {
static CanonicalGameplayCapacityOrigin decodeOrigin(Record row) {
var request =
- CanonicalGameplayRegionOwnerTransferRepository.decodeRequest(
+ CapacityAdmissionDigest.decodeCommittable(
row.get("canonical_request", byte[].class), row.get("mutation_digest", String.class));
var candidate =
CanonicalGameplayOriginalNewCandidate.parseCanonical(
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAdmittedLogoutIntentRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAdmittedLogoutIntentRepository.java
new file mode 100644
index 0000000000..bc7fdb7143
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAdmittedLogoutIntentRepository.java
@@ -0,0 +1,150 @@
+package net.firedevops.firemud.gamesession.repository;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution;
+import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jooq.impl.DSL;
+import org.jspecify.annotations.Nullable;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Unregistered durable preparation for logout of one exact admitted original NEW binding. */
+final class CanonicalGameplayOriginalNewAdmittedLogoutIntentRepository {
+ private final DSLContext dsl;
+
+ CanonicalGameplayOriginalNewAdmittedLogoutIntentRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl);
+ }
+
+ /**
+ * Records the intent before any serving mutation. The caller obtains the current physical bytes
+ * under protected Game Session custody. Only their hashes are retained.
+ */
+ Intent prepare(
+ UUID logoutId,
+ CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source,
+ OriginalNewCapacityExecution execution,
+ byte[] observedFinalSession) {
+ requireNoAmbientTransaction();
+ var receipt =
+ source
+ .finalReceipt()
+ .orElseThrow(CanonicalGameplayOriginalNewAdmittedLogoutIntentRepository::conflict);
+ var candidate = source.candidate();
+ if (!candidate.transition().transitionId().equals(execution.transitionId())
+ || !source.candidateDigest().equals(execution.candidateDigest())
+ || observedFinalSession.length == 0
+ || observedFinalSession.length
+ > CanonicalGameplayOriginalNewAuthenticatedSession.MAX_SESSION_BYTES
+ || !receipt
+ .finalSessionSha256()
+ .equals(OriginalNewCapacityExecution.sha256(observedFinalSession))) {
+ throw conflict();
+ }
+ var expected =
+ new Intent(
+ logoutId,
+ execution.digest(),
+ execution.transitionId(),
+ candidate.transition().bindingGeneration(),
+ receipt.finalSessionSha256(),
+ sha1(observedFinalSession));
+ dsl.transaction(
+ configuration -> {
+ DSLContext transaction = DSL.using(configuration);
+ var retained = read(transaction, expected.executionDigest());
+ if (retained == null) {
+ transaction.execute(
+ """
+ INSERT INTO game_session_original_new_admitted_logout_intent
+ (logout_id, execution_digest, transition_id, binding_generation,
+ original_final_session_sha256, original_session_sha1)
+ VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT (execution_digest) DO NOTHING
+ """,
+ expected.logoutId(),
+ expected.executionDigest(),
+ expected.transitionId(),
+ new BigDecimal(expected.bindingGeneration()),
+ expected.originalFinalSessionSha256(),
+ expected.originalSessionSha1());
+ retained = read(transaction, expected.executionDigest());
+ }
+ if (!expected.equals(retained)) throw conflict();
+ });
+ var committed = readExact(expected.executionDigest(), logoutId);
+ if (!expected.equals(committed)) throw conflict();
+ return committed;
+ }
+
+ /** A lost reply resumes only the exact originally retained operation. */
+ Intent readExact(String executionDigest, UUID logoutId) {
+ requireNoAmbientTransaction();
+ var retained = read(dsl, executionDigest);
+ if (retained == null || !retained.logoutId().equals(logoutId)) throw conflict();
+ return retained;
+ }
+
+ private static @Nullable Intent read(DSLContext db, String executionDigest) {
+ Record row =
+ db.fetchOne(
+ """
+ SELECT logout_id, execution_digest, transition_id, binding_generation,
+ original_final_session_sha256, original_session_sha1
+ FROM game_session_original_new_admitted_logout_intent
+ WHERE execution_digest = ?
+ """,
+ executionDigest);
+ if (row == null) return null;
+ return new Intent(
+ Objects.requireNonNull(row.get("logout_id", UUID.class)),
+ Objects.requireNonNull(row.get("execution_digest", String.class)),
+ Objects.requireNonNull(row.get("transition_id", UUID.class)),
+ Objects.requireNonNull(row.get("binding_generation", BigDecimal.class)).toBigIntegerExact(),
+ Objects.requireNonNull(row.get("original_final_session_sha256", String.class)),
+ Objects.requireNonNull(row.get("original_session_sha1", String.class)));
+ }
+
+ private static String sha1(byte[] bytes) {
+ // Redis compares its native session digest. The durable FINAL independently requires SHA-256.
+ try {
+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(bytes));
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("Redis session comparison digest is unavailable", impossible);
+ }
+ }
+
+ private static void requireNoAmbientTransaction() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) throw conflict();
+ }
+
+ private static CanonicalGameplayBindingInventoryConflictException conflict() {
+ return new CanonicalGameplayBindingInventoryConflictException(
+ "Admitted logout does not match the retained original operation");
+ }
+
+ record Intent(
+ UUID logoutId,
+ String executionDigest,
+ UUID transitionId,
+ BigInteger bindingGeneration,
+ String originalFinalSessionSha256,
+ String originalSessionSha1) {
+ Intent {
+ TenantCapacityAdmission.uuid(logoutId);
+ TenantCapacityAdmission.uuid(transitionId);
+ if (!executionDigest.matches("sha256:[0-9a-f]{64}")
+ || Objects.requireNonNull(bindingGeneration).signum() <= 0
+ || !originalFinalSessionSha256.matches("[0-9a-f]{64}")
+ || !originalSessionSha1.matches("[0-9a-f]{40}")) throw conflict();
+ }
+ }
+}
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 8fd432e3aa..6108151abf 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
@@ -10,13 +10,16 @@
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisFuture;
+import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.codec.ByteArrayCodec;
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.Arrays;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
@@ -27,13 +30,21 @@
import net.firedevops.firemud.common.account.capacity.AccountCapacityOriginResolution;
import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest;
import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution;
+import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecutionReadGrpcCodec;
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.State;
import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.ArgumentSpec;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.KeySpec;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.MutationEffect;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeCategory;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.OutcomeSpec;
import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot;
import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus;
+import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewAdmittedLogoutRedisScriptContribution;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.impl.DSL;
@@ -1054,6 +1065,29 @@ private static void retainTerminal(
!= 1) throw unavailable();
}
+ /** Reads the historical acquisition witness using the bounded recovery resource pool. */
+ public OriginalNewCapacityExecutionReadGrpcCodec.HistoricalFinalReadback readHistoricalFinal(
+ Request request, Result reservation) {
+ return withinBackground(
+ Long.MAX_VALUE,
+ owner -> {
+ var receipt =
+ new CanonicalGameplayAccountAdmissionBarrierRepository(owner.sql(), clock)
+ .readHistoricalFinalReceipt(request, reservation)
+ .orElseThrow(CanonicalGameplayOriginalNewCapacityExecutionOwner::unavailable);
+ var observation = receipt.observation();
+ return new OriginalNewCapacityExecutionReadGrpcCodec.HistoricalFinalReadback(
+ receipt.execution(),
+ observation.operationId(),
+ observation.finalSessionSha256(),
+ observation.admissionAtMillis(),
+ observation.continuityExpiresAtMillis(),
+ observation.inventorySnapshotRevision().toString(),
+ observation.cohortDigest(),
+ observation.barrierTargetDigest());
+ });
+ }
+
void requireRetainedCommittedOriginal(
CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource source,
CanonicalGameplayRegionRuntimeStatus prior) {
@@ -1130,16 +1164,11 @@ private Snapshot readExact(Request request, Result reservation, boolean verifyFo
throw unavailable();
if ("COMMITTED".equals(row.get("status", String.class))) {
String finalDigest = transition.get("original_new_final_session_sha256", String.class);
- if (!"COMMITTED".equals(transition.get("status", String.class))
- || finalDigest == null
- || !execution
- .digest()
- .equals(transition.get("original_new_capacity_execution_digest", String.class)))
- throw unavailable();
+ var retained =
+ requireRetainedCommittedEvidence(
+ execution, row, transition, transition.get("status", String.class));
String receipt = receiptDigest(transition, execution);
- byte[] retained = execution.terminalEvidence("COMMITTED", "sha256:" + finalDigest, receipt);
- if (!Arrays.equals(retained, row.get("terminal_readback", byte[].class))
- || !observedOwner.equals(currentOwner(candidate))) throw unavailable();
+ if (!observedOwner.equals(currentOwner(candidate))) throw unavailable();
return new Snapshot(
execution,
"COMMITTED",
@@ -1533,6 +1562,184 @@ private Map readExecution(
return result;
}
+ /** Observes only the retained tenant-slot fence for an exact admitted original. */
+ void requireAdmittedLogoutFence(
+ UUID logoutId, OriginalNewCapacityExecution execution, long deadline) {
+ noSql();
+ if (budget == null) {
+ CanonicalGameplayOriginalNewCapacityExecutionBudget.runBackground(
+ clock,
+ deadline,
+ scoped -> {
+ new CanonicalGameplayOriginalNewCapacityExecutionOwner(
+ dsl, redis, scripts, clock, tags, scoped, null)
+ .requireAdmittedLogoutFence(logoutId, execution, deadline);
+ return null;
+ });
+ return;
+ }
+ budget.check();
+ Record row = find(sql(), execution);
+ if (row == null || !"COMMITTED".equals(row.get("status", String.class))) throw unavailable();
+ exact(row, execution);
+ var intent =
+ new CanonicalGameplayOriginalNewAdmittedLogoutIntentRepository(sql())
+ .readExact(execution.digest(), logoutId);
+ Record finalTransition = transition(execution);
+ byte[] candidateBytes = finalTransition.get("original_new_candidate_bytes", byte[].class);
+ if (!"COMMITTED".equals(finalTransition.get("status", String.class))
+ || !execution.transitionId().equals(intent.transitionId())
+ || !execution
+ .digest()
+ .equals(finalTransition.get("original_new_capacity_execution_digest", String.class))
+ || !intent
+ .originalFinalSessionSha256()
+ .equals(finalTransition.get("original_new_final_session_sha256", String.class))
+ || candidateBytes == null
+ || !execution
+ .candidateDigest()
+ .equals("sha256:" + OriginalNewCapacityExecution.sha256(candidateBytes)))
+ throw unavailable();
+ var candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes);
+ if (!candidate.bindingDecisionId().equals(intent.transitionId())
+ || !candidate.transition().bindingGeneration().equals(intent.bindingGeneration()))
+ throw unavailable();
+ var assignment = scopedTags().assignmentForRetainedCapacityExecution(intent.transitionId());
+ String tag = assignment.tenantGameplayTag();
+ if (!tag.equals(row.get("tenant_gameplay_tag", String.class))) throw unavailable();
+ var binding = candidate.bindingIdentity();
+ var ref = binding.bindingRef();
+ byte[][] keys = {
+ bytes(CanonicalGameplaySessionRedisKeys.session(assignment, ref)),
+ bytes(CanonicalGameplaySessionRedisKeys.characterIndex(assignment, ref)),
+ bytes(CanonicalGameplaySessionRedisKeys.accountTenantIndex(assignment, ref)),
+ bytes(CanonicalGameplaySessionRedisKeys.tenantIndex(assignment, ref)),
+ bytes(
+ "session:game:capacity-execution:{"
+ + tag
+ + "}:"
+ + execution.request().admissionAttemptId())
+ };
+ byte[][] arguments = {
+ bytes(binding.tenantId().toString()),
+ bytes(binding.accountId().toString()),
+ bytes(binding.playableStateNamespaceId().toString()),
+ bytes(binding.characterId().toString()),
+ bytes(binding.gameInstanceId().toString()),
+ bytes(binding.sessionId()),
+ bytes(intent.bindingGeneration().toString()),
+ bytes(tag),
+ bytes(intent.executionDigest()),
+ bytes(intent.logoutId().toString()),
+ bytes(Long.toString(budget.absoluteDeadlineMillis())),
+ execution.canonicalBytes(),
+ bytes(intent.originalSessionSha1()),
+ bytes("OBSERVE")
+ };
+ byte[] script = admittedLogoutScript();
+ var connection = connectForRead();
+ try {
+ var commands = connection.async();
+ principal(commands);
+ String sha = await(commands.scriptLoad(script));
+ if (!sha1(script).equals(sha)) throw unavailable();
+ Long observation =
+ await(commands.evalshaReadOnly(sha, ScriptOutputType.INTEGER, keys, arguments));
+ if (!Long.valueOf(2).equals(observation)) throw unavailable();
+ } finally {
+ connection.closeAsync();
+ }
+ budget.check();
+ }
+
+ private byte[] admittedLogoutScript() {
+ try {
+ var descriptor =
+ scripts.require(
+ CanonicalGameplayOriginalNewAdmittedLogoutRedisScriptContribution.SCRIPT_ID);
+ requireAdmittedLogoutDescriptor(descriptor);
+ try (var input = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) {
+ if (input == null) throw unavailable();
+ int maximumBytes = 16 * 1024;
+ byte[] script = input.readNBytes(maximumBytes + 1);
+ if (script.length == 0
+ || script.length > maximumBytes
+ || !descriptor.sha256().equals(OriginalNewCapacityExecution.sha256(script))) {
+ throw unavailable();
+ }
+ return script;
+ }
+ } catch (IOException | RuntimeException failure) {
+ throw unavailable();
+ }
+ }
+
+ private static void requireAdmittedLogoutDescriptor(RedisScriptDescriptor descriptor) {
+ var hashTag = RedisScriptDescriptor.HashTagDeclaration.REQUIRED;
+ var keys =
+ List.of(
+ new KeySpec("session", "session:game:", hashTag),
+ new KeySpec("characterIndex", "session:game:index:character:", hashTag),
+ new KeySpec("accountTenantIndex", "session:game:index:account-tenant:", hashTag),
+ new KeySpec("tenantIndex", "session:game:index:tenant:", hashTag),
+ new KeySpec("capacityExecution", "session:game:capacity-execution:", hashTag));
+ var arguments =
+ List.of(
+ "tenantId",
+ "accountId",
+ "playableStateNamespaceId",
+ "characterId",
+ "gameInstanceId",
+ "sessionId",
+ "bindingGeneration",
+ "tenantGameplayTag",
+ "capacityExecutionDigest",
+ "logoutId",
+ "absoluteDeadlineMillis",
+ "capacityExecutionBytes",
+ "originalSessionSha1",
+ "action")
+ .stream()
+ .map(ArgumentSpec::new)
+ .toList();
+ var outcomes =
+ List.of(
+ new OutcomeSpec(
+ "ADMITTED_LOGOUT_FENCE_INSTALLED",
+ OutcomeCategory.SUCCESS,
+ MutationEffect.MUTATING),
+ new OutcomeSpec(
+ "ADMITTED_LOGOUT_FENCE_OBSERVED",
+ OutcomeCategory.REPLAY,
+ MutationEffect.NON_MUTATING),
+ new OutcomeSpec(
+ "CURRENT_PHYSICAL_STATE_REFUSED",
+ OutcomeCategory.STALE,
+ MutationEffect.NON_MUTATING),
+ new OutcomeSpec(
+ "INVALID_ARGUMENTS",
+ OutcomeCategory.VALIDATION_FAILURE,
+ MutationEffect.NON_MUTATING));
+ if (!CanonicalGameplayOriginalNewAdmittedLogoutRedisScriptContribution.RESOURCE_PATH.equals(
+ descriptor.resourcePath())
+ || !"game-session-service".equals(descriptor.owner())
+ || !"gamesession_coord_app".equals(descriptor.principal())
+ || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION
+ || !keys.equals(descriptor.keys())
+ || !arguments.equals(descriptor.arguments())
+ || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS
+ || !outcomes.equals(descriptor.outcomes())
+ || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER
+ || descriptor.lossClass() != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET
+ || descriptor.compatibilityLevel()
+ != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET
+ || !List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none"))
+ .equals(descriptor.supportedCoexistence())
+ || descriptor.legacyPayloadShape() != null) {
+ throw unavailable();
+ }
+ }
+
/**
* Bound connection establishment itself, including DNS/TLS/auth, to the incoming deadline. A late
* connection cannot escape cancellation into a read; its resource worker retains admission until
@@ -1724,6 +1931,26 @@ private static void exact(Record row, OriginalNewCapacityExecution execution) {
.equals(row.get("admission_attempt_id", UUID.class))) throw unavailable();
}
+ static byte[] requireRetainedCommittedEvidence(
+ OriginalNewCapacityExecution execution,
+ Record row,
+ Record transition,
+ String transitionState) {
+ String finalDigest = transition.get("original_new_final_session_sha256", String.class);
+ if (!"COMMITTED".equals(row.get("status", String.class))
+ || !"COMMITTED".equals(transitionState)
+ || finalDigest == null
+ || !execution
+ .digest()
+ .equals(transition.get("original_new_capacity_execution_digest", String.class)))
+ throw unavailable();
+ byte[] retained =
+ execution.terminalEvidence(
+ "COMMITTED", "sha256:" + finalDigest, receiptDigest(transition, execution));
+ if (!Arrays.equals(retained, row.get("terminal_readback", byte[].class))) throw unavailable();
+ return retained;
+ }
+
private static String receiptDigest(Record row, OriginalNewCapacityExecution execution) {
return receiptDigest(
execution,
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 c505c20518..05c32aebc6 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
@@ -588,8 +588,7 @@ private CurrentContext loadRegionOwnerTransferCurrentContext(
throw new ObservationRejectedException("Protected transfer observation source differs");
}
CanonicalGameplayTenantGameplayTagRepository.Assignment assignment =
- regionOwnerTransferSource.readAssignment(
- context.transitionId(), tenantTagRepository, deadline);
+ regionOwnerTransferSource.readAssignment(context, 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/CanonicalGameplayRegionOwnerTransferObservationSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferObservationSource.java
index bf2282ad5d..b0aea5a2b1 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
@@ -35,6 +35,11 @@ default CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment(
return readAssignment(transitionId, tags);
}
+ default CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment(
+ Context context, CanonicalGameplayTenantGameplayTagRepository tags, long deadline) {
+ return readAssignment(context.transitionId(), tags, deadline);
+ }
+
/**
* 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 a7d16ceba3..d011ca9b63 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
@@ -6,9 +6,7 @@
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;
@@ -1029,6 +1027,17 @@ public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment(
.readAssignmentForRetainedCapacityExecution(transitionId);
}
+ @Override
+ public CanonicalGameplayTenantGameplayTagRepository.Assignment readAssignment(
+ Context context, CanonicalGameplayTenantGameplayTagRepository sourceTags, long deadline) {
+ if (admitted.get() == null)
+ return within(deadline, ignored -> readAssignment(context, sourceTags, deadline));
+ if (deadline < admitted.get().absoluteDeadlineMillis()) throw unavailable();
+ return readItem(
+ context.transferId(), context.targetOrdinal(), context.executionDigest(), sourceTags)
+ .assignment();
+ }
+
static Record observationCurrent(DSLContext tx, UUID id) {
Record row =
tx.fetchOne(
@@ -1063,19 +1072,42 @@ private static String completionDigest(Record transfer) {
}
private Item readItem(UUID transferId, long ordinal, String executionDigest) {
+ return readItem(transferId, ordinal, executionDigest, tags);
+ }
+
+ private Item readItem(
+ UUID transferId,
+ long ordinal,
+ String executionDigest,
+ CanonicalGameplayTenantGameplayTagRepository sourceTags) {
return sql()
.transactionResult(
configuration -> {
DSLContext transaction = DSL.using(configuration);
transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY");
- return loadItem(transaction, transferId, ordinal, executionDigest);
+ return loadItem(transaction, transferId, ordinal, executionDigest, sourceTags);
});
}
private Item loadItem(DSLContext tx, UUID transferId, long ordinal, String executionDigest) {
+ return loadItem(tx, transferId, ordinal, executionDigest, tags);
+ }
+
+ private Item loadItem(
+ DSLContext tx,
+ UUID transferId,
+ long ordinal,
+ String executionDigest,
+ CanonicalGameplayTenantGameplayTagRepository sourceTags) {
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=?",
+ "SELECT e.*, t.status AS transition_status, t.original_new_candidate_bytes,"
+ + " t.original_new_capacity_execution_digest, t.original_new_final_session_sha256,"
+ + " t.original_new_admission_at_ms, t.original_new_continuity_expires_at_ms,"
+ + " t.original_new_session_duration_ms"
+ + " 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 =
@@ -1092,7 +1124,15 @@ private Item loadItem(DSLContext tx, UUID transferId, long ordinal, String execu
.request()
.admissionAttemptId()
.equals(row.get("admission_attempt_id", UUID.class))) throw unavailable();
- var assignment = tags.readAssignmentForRetainedCapacityExecution(tx, execution.transitionId());
+ boolean committed = "COMMITTED".equals(row.get("status", String.class));
+ if (committed) {
+ CanonicalGameplayOriginalNewCapacityExecutionOwner.requireRetainedCommittedEvidence(
+ execution, row, row, row.get("transition_status", String.class));
+ }
+ var assignment =
+ committed
+ ? sourceTags.readAssignmentForCommittedTransferItem(tx, execution.transitionId())
+ : sourceTags.readAssignmentForRetainedCapacityExecution(tx, execution.transitionId());
if (!assignment.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class)))
throw unavailable();
var binding = candidate.bindingIdentity();
@@ -1267,10 +1307,13 @@ static OriginalNewCapacityExecution decode(byte[] canonical) {
throw unavailable();
JsonNode node = JSON.readTree(canonical);
byte[] payload = Base64.getDecoder().decode(node.get("canonicalAttemptPayload").textValue());
- var request = decodeRequest(payload, node.get("mutationDigest").textValue());
+ var request =
+ CapacityAdmissionDigest.decodeCommittable(
+ payload, node.get("mutationDigest").textValue());
+ var identity = request.identity();
var reservation =
new TenantCapacityAdmission.Result(
- request.identity(),
+ identity,
request.admissionAttemptId(),
request.capacityRearmFence(),
request.mutationDigest(),
@@ -1295,83 +1338,6 @@ static OriginalNewCapacityExecution decode(byte[] canonical) {
}
}
- /** Strict canonical request decoder shared by execution envelopes and positive origins. */
- static TenantCapacityAdmission.Request decodeRequest(byte[] payload, String mutationDigest) {
- try {
- if (payload == null
- || payload.length == 0
- || payload.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES) throw unavailable();
- 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"),
- mutationDigest);
- if (!parser.done() || !Arrays.equals(payload, CapacityAdmissionDigest.preimage(request)))
- throw unavailable();
- request.requireCommittable();
- return request;
- } catch (RuntimeException invalid) {
- throw unavailable();
- }
- }
-
- private static TenantCapacityAdmission.Shape shape(Map value) {
- return new TenantCapacityAdmission.Shape(
- number(value, "activeSessions"),
- number(value, "concurrentGameInstances"),
- number(value, "storageBytes"));
- }
-
- @SuppressWarnings("unchecked")
- private static Map object(Map value, String key) {
- if (!(value.get(key) instanceof Map, ?>)) throw unavailable();
- return (Map) value.get(key);
- }
-
- private static String text(Map value, String key) {
- if (!(value.get(key) instanceof String text)) throw unavailable();
- return text;
- }
-
- private static long number(Map value, String key) {
- if (!(value.get(key) instanceof Long number)) throw unavailable();
- return number;
- }
-
- private static UUID uuid(Map value, String key) {
- return UUID.fromString(text(value, key));
- }
-
private static byte[] bytes(String text) {
return text.getBytes(StandardCharsets.UTF_8);
}
@@ -1394,56 +1360,6 @@ private static IllegalStateException unavailable() {
return new IllegalStateException("Normal region owner transfer is held");
}
- private static final class Frame {
- private final byte[] data;
- private int offset;
-
- private Frame(byte[] data) {
- if (data.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES) throw unavailable();
- this.data = data;
- }
-
- private String segment() {
- int start = offset;
- while (offset < data.length && data[offset] >= '0' && data[offset] <= '9') offset++;
- if (offset == start || offset >= data.length || data[offset++] != ':' || offset - start > 8)
- throw unavailable();
- int size =
- Integer.parseInt(new String(data, start, offset - start - 1, StandardCharsets.US_ASCII));
- if (size < 0
- || size > CapacityAdmissionDigest.MAX_SEGMENT_BYTES
- || size > data.length - offset) throw unavailable();
- String result = new String(data, offset, size, StandardCharsets.UTF_8);
- offset += size;
- return result;
- }
-
- private Map fields(int count, int depth) {
- if (count < 0 || count > 16 || depth > 8) throw unavailable();
- Map result = new LinkedHashMap<>();
- for (int index = 0; index < count; index++) {
- String name = segment(), type = segment();
- if (offset >= data.length || data[offset++] != '1') throw unavailable();
- String payload = segment();
- Object value;
- if (type.equals("object")) {
- Frame nested = new Frame(bytes(payload));
- value = nested.fields(Integer.parseInt(nested.segment()), depth + 1);
- if (!nested.done()) throw unavailable();
- } else if (type.equals("string")) value = payload;
- else if (type.equals("number") && payload.matches("0|[1-9][0-9]{0,18}"))
- value = Long.parseLong(payload);
- else throw unavailable();
- if (result.put(name, value) != null) throw unavailable();
- }
- return result;
- }
-
- private boolean done() {
- return offset == data.length;
- }
- }
-
record FrozenOriginal(
UUID transferId, String executionDigest, CanonicalGameplayOriginalNewCandidate candidate) {}
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 845fd108e6..4390b2ab72 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
@@ -71,7 +71,7 @@ Assignment assignmentForRetainedCapacityExecution(UUID transitionId) {
configuration -> {
DSLContext transaction = DSL.using(configuration);
CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction);
- BindingTarget source = retainedCapacityTarget(transaction, transitionId, true);
+ BindingTarget source = retainedCapacityTarget(transaction, transitionId, true, false);
requireTenantClaim(transaction, source.tenantId());
// A retained execution cannot allocate replacement topology after loss of its mapping.
if (transaction.fetchOne(
@@ -94,8 +94,18 @@ Assignment readAssignmentForRetainedCapacityExecution(UUID transitionId) {
}
Assignment readAssignmentForRetainedCapacityExecution(DSLContext transaction, UUID transitionId) {
+ return readRetainedAssignment(transaction, transitionId, false);
+ }
+
+ /** Transfer item topology after the caller proves exact retained COMMITTED evidence. */
+ Assignment readAssignmentForCommittedTransferItem(DSLContext transaction, UUID transitionId) {
+ return readRetainedAssignment(transaction, transitionId, true);
+ }
+
+ private Assignment readRetainedAssignment(
+ DSLContext transaction, UUID transitionId, boolean retainedCommit) {
requireNonNil(transitionId, "transitionId");
- BindingTarget source = retainedCapacityTarget(transaction, transitionId, false);
+ BindingTarget source = retainedCapacityTarget(transaction, transitionId, false, retainedCommit);
requireTenantClaim(transaction, source.tenantId());
Record mapping =
transaction.fetchOne(
@@ -106,7 +116,7 @@ Assignment readAssignmentForRetainedCapacityExecution(DSLContext transaction, UU
}
private BindingTarget retainedCapacityTarget(
- DSLContext transaction, UUID transitionId, boolean lock) {
+ DSLContext transaction, UUID transitionId, boolean lock, boolean retainedCommit) {
Record transition =
transaction.fetchOne(
"SELECT status FROM game_session_canonical_binding_transition WHERE transition_id=?",
@@ -120,7 +130,7 @@ private BindingTarget retainedCapacityTarget(
transaction, transitionId, false);
if (!retained.isAccountAborted()) throw conflict("Exact retained Account abort required");
}
- return loadBindingTarget(transaction, transitionId, null, aborted, lock);
+ return loadBindingTarget(transaction, transitionId, null, aborted, lock, retainedCommit);
}
/** Reads the immutable allocation without changing the transfer's region-lock order. */
@@ -350,7 +360,7 @@ private BindingTarget loadBindingTarget(
private BindingTarget loadBindingTarget(
DSLContext transaction, UUID transitionId, UUID abandonmentId, boolean retainedAbort) {
- return loadBindingTarget(transaction, transitionId, abandonmentId, retainedAbort, true);
+ return loadBindingTarget(transaction, transitionId, abandonmentId, retainedAbort, true, false);
}
private BindingTarget loadBindingTarget(
@@ -358,7 +368,8 @@ private BindingTarget loadBindingTarget(
UUID transitionId,
UUID abandonmentId,
boolean retainedAbort,
- boolean lock) {
+ boolean lock,
+ boolean retainedCommit) {
boolean negative = abandonmentId != null;
String negativeSelector =
negative
@@ -411,6 +422,10 @@ private BindingTarget loadBindingTarget(
byte[] inventoryRefBytes = requiredBytes(row, "binding_ref");
String transitionState = requiredString(row, "status");
String inventoryState = requiredString(row, "lifecycle");
+ boolean retiredCommit =
+ retainedCommit
+ && "COMMITTED".equals(transitionState)
+ && Set.of("TERMINAL_UNRESOLVED", "TERMINAL").contains(inventoryState);
if (!tenantId.equals(inventoryTenantId)
|| !namespaceId.equals(inventoryNamespaceId)
|| !characterId.equals(inventoryCharacterId)
@@ -422,12 +437,13 @@ private BindingTarget loadBindingTarget(
? 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)
+ || (!retiredCommit
+ && !(retainedAbort
+ ? Set.of("TERMINAL_UNRESOLVED", "TERMINAL")
+ : negative
+ ? Set.of("CANDIDATE_PREPARED", "TERMINAL_UNRESOLVED", "TERMINAL")
+ : INVENTORY_STATES)
+ .contains(inventoryState))
|| !transitionRefMatches(
transitionRefBytes, inventoryRefBytes, tenantId, gameInstanceId, sessionId)
|| !requiredBigInteger(row, "candidate_binding_generation")
@@ -440,7 +456,9 @@ private BindingTarget loadBindingTarget(
if (("PREPARED".equals(transitionState) && !"CANDIDATE_PREPARED".equals(inventoryState))
|| ("PROVISIONAL".equals(transitionState) && !"PROVISIONAL".equals(inventoryState))
- || ("COMMITTED".equals(transitionState) && !"ACTIVE".equals(inventoryState))
+ || ("COMMITTED".equals(transitionState)
+ && !"ACTIVE".equals(inventoryState)
+ && !retiredCommit)
|| ("ABORTED".equals(transitionState)
&& !Set.of("TERMINAL_UNRESOLVED", "TERMINAL").contains(inventoryState))) {
throw conflict("The durable transition and candidate inventory lifecycle disagree");
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 54c06a36a6..b05031b9bc 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
@@ -51,9 +51,14 @@ public void requireAccountCaller() {
public ServerCall.Listener interceptCall(
ServerCall call, Metadata headers, ServerCallHandler next) {
Objects.requireNonNull(call, "gRPC server call required");
+ String method = call.getMethodDescriptor().getFullMethodName();
if (!OriginalNewCapacityExecutionReadServiceGrpc.getReadOriginalNewCapacityExecutionMethod()
- .getFullMethodName()
- .equals(call.getMethodDescriptor().getFullMethodName())) {
+ .getFullMethodName()
+ .equals(method)
+ && !OriginalNewCapacityExecutionReadServiceGrpc
+ .getReadHistoricalOriginalNewCapacityFinalMethod()
+ .getFullMethodName()
+ .equals(method)) {
call.close(
Status.PERMISSION_DENIED.withDescription("Exact Account final-result read required"),
new Metadata());
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewAdmittedLogoutRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewAdmittedLogoutRedisScriptContribution.java
new file mode 100644
index 0000000000..83accbbec0
--- /dev/null
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayOriginalNewAdmittedLogoutRedisScriptContribution.java
@@ -0,0 +1,32 @@
+package net.firedevops.firemud.gamesession.service;
+
+import java.util.Collection;
+import java.util.List;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor;
+
+/** Explicit descriptor contribution for the manual admitted logout readback. */
+public final class CanonicalGameplayOriginalNewAdmittedLogoutRedisScriptContribution
+ implements RedisScriptContribution {
+ public static final String SCRIPT_ID = "game-session.original-new-admitted-logout.v1";
+ public static final String RESOURCE_PATH =
+ "redis/lua/game-session-original-new-admitted-logout.lua";
+ private static final String DESCRIPTOR_PATH =
+ "/redis/scripts/game-session-original-new-admitted-logout.json";
+
+ @Override
+ public String ownerId() {
+ return "game-session-service";
+ }
+
+ @Override
+ public Collection descriptors() {
+ return List.of(
+ GameSessionRedisScriptDescriptors.load(
+ getClass(),
+ DESCRIPTOR_PATH,
+ ownerId(),
+ SCRIPT_ID,
+ "Original NEW admitted logout Redis descriptor is unavailable"));
+ }
+}
diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService.java
index 6a3aefe866..fdf2c3a0f9 100644
--- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService.java
+++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService.java
@@ -5,11 +5,14 @@
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import java.util.Objects;
+import java.util.function.Function;
import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecutionReadGrpcCodec;
+import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecutionReadGrpcCodec.Selector;
import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
import net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewCapacityExecutionOwner;
import net.firedevops.firemud.gamesession.security.CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard;
import net.firedevops.firemud.gamesession.v1.OriginalNewCapacityExecutionReadServiceGrpc;
+import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalNewCapacityFinalResponse;
import net.firedevops.firemud.gamesession.v1.ReadOriginalNewCapacityExecutionRequest;
import net.firedevops.firemud.gamesession.v1.ReadOriginalNewCapacityExecutionResponse;
@@ -40,13 +43,47 @@ public CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService(
public void readOriginalNewCapacityExecution(
ReadOriginalNewCapacityExecutionRequest request,
StreamObserver observer) {
+ respond(
+ request,
+ observer,
+ selector -> {
+ var actual = owner.readExact(selector.request(), selector.reservation());
+ var readback =
+ new OriginalNewCapacityExecutionReadGrpcCodec.Readback(
+ actual.execution(),
+ actual.disposition(),
+ actual.physicalDigest(),
+ actual.receiptDigest(),
+ actual.canonicalReadback(),
+ actual.currentOwnerId(),
+ actual.currentOwnerFence());
+ return OriginalNewCapacityExecutionReadGrpcCodec.toResponse(selector, readback);
+ });
+ }
+
+ @Override
+ public void readHistoricalOriginalNewCapacityFinal(
+ ReadOriginalNewCapacityExecutionRequest request,
+ StreamObserver observer) {
+ respond(
+ request,
+ observer,
+ selector ->
+ OriginalNewCapacityExecutionReadGrpcCodec.toHistoricalResponse(
+ selector, owner.readHistoricalFinal(selector.request(), selector.reservation())));
+ }
+
+ private void respond(
+ ReadOriginalNewCapacityExecutionRequest request,
+ StreamObserver observer,
+ Function read) {
try {
guard.requireAccountCaller();
} catch (StatusRuntimeException denied) {
fail(observer, denied.getStatus());
return;
}
- final OriginalNewCapacityExecutionReadGrpcCodec.Selector selector;
+ final Selector selector;
try {
selector = OriginalNewCapacityExecutionReadGrpcCodec.parseRequest(request);
if (!namespace.equals(selector.request().targetNamespace()))
@@ -56,17 +93,7 @@ public void readOriginalNewCapacityExecution(
return;
}
try {
- var actual = owner.readExact(selector.request(), selector.reservation());
- var readback =
- new OriginalNewCapacityExecutionReadGrpcCodec.Readback(
- actual.execution(),
- actual.disposition(),
- actual.physicalDigest(),
- actual.receiptDigest(),
- actual.canonicalReadback(),
- actual.currentOwnerId(),
- actual.currentOwnerFence());
- observer.onNext(OriginalNewCapacityExecutionReadGrpcCodec.toResponse(selector, readback));
+ observer.onNext(read.apply(selector));
observer.onCompleted();
} catch (RuntimeException unavailable) {
fail(observer, Status.UNAVAILABLE);
diff --git a/services/game-session-service/src/main/resources/db/migration/V1066.1__transferred_capacity_origin_recovery.sql b/services/game-session-service/src/main/resources/db/migration/V1066.1__transferred_capacity_origin_recovery.sql
new file mode 100644
index 0000000000..b262cb0b89
--- /dev/null
+++ b/services/game-session-service/src/main/resources/db/migration/V1066.1__transferred_capacity_origin_recovery.sql
@@ -0,0 +1,125 @@
+-- Retain the issuing fence on each counted permit. Earlier NULL issuing fences are never inferred.
+ALTER TABLE game_session_original_new_capacity_origin
+ ADD COLUMN last_observation_custody_fence BIGINT,
+ ADD CONSTRAINT gs_origin_observation_custody_fence CHECK (
+ last_observation_custody_fence IS NULL OR (
+ last_observation_custody_fence > 0 AND last_observation_custody_fence <= custody_owner_fence
+ AND recovery_observations > 0 AND last_observation_deadline IS NOT NULL));
+
+-- [jooq ignore start]
+CREATE FUNCTION guard_gs_origin_observation_issuing_fence() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ IF TG_OP='INSERT' THEN
+ IF NEW.last_observation_custody_fence IS NOT NULL THEN
+ RAISE EXCEPTION 'An origin observation fence must be issued with its counted permit' USING ERRCODE='23514';
+ END IF;
+ ELSIF (NEW.recovery_observations=OLD.recovery_observations
+ AND NEW.last_observation_custody_fence IS DISTINCT FROM OLD.last_observation_custody_fence)
+ OR (NEW.recovery_observations>OLD.recovery_observations
+ AND NEW.last_observation_custody_fence IS DISTINCT FROM NEW.custody_owner_fence) THEN
+ RAISE EXCEPTION 'An origin observation fence must bind its counted permit to current custody' USING ERRCODE='23514';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER gs_origin_observation_issuing_fence BEFORE INSERT OR UPDATE
+ ON game_session_original_new_capacity_origin FOR EACH ROW
+ EXECUTE FUNCTION guard_gs_origin_observation_issuing_fence();
+
+-- Closure-only construction retains the original execution identity and requires current custody.
+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,r.region_epoch,r.lease_token_correlation 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 (NEW.status<>'CLOSURE_CLAIMED' AND (
+ 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=current_owner.owner_instance_id AND t.old_owner_fence=current_owner.executor_fence) THEN
+ RAISE EXCEPTION 'Completed region predecessor cannot acquire dispatch' USING ERRCODE='23514';
+ END IF;
+ IF NEW.status='CLOSURE_CLAIMED' AND NOT EXISTS (
+ SELECT 1 FROM game_session_original_new_capacity_origin o
+ WHERE o.admission_attempt_id=NEW.admission_attempt_id AND o.tenant_id=NEW.tenant_id
+ AND o.request_id=NEW.request_id AND o.admission_id=NEW.admission_id
+ AND o.transition_id=NEW.transition_id AND o.capacity_rearm_fence=NEW.capacity_rearm_fence
+ AND o.mutation_digest=NEW.mutation_digest AND o.tenant_gameplay_tag=NEW.tenant_gameplay_tag
+ AND o.game_instance_id=scope.game_instance_id AND o.region_id=scope.region_id
+ AND o.selected_owner_id=NEW.selected_owner_id AND o.selected_owner_fence=NEW.selected_owner_fence
+ AND o.custody_owner_id=current_owner.owner_instance_id AND o.custody_owner_fence=current_owner.executor_fence
+ AND o.state='CLOSURE_CLAIMED' AND o.account_resolution_bytes IS NOT NULL
+ AND ((o.custody_transfer_id IS NULL AND o.custody_owner_id=o.selected_owner_id
+ AND o.custody_owner_fence=o.selected_owner_fence)
+ OR EXISTS (
+ SELECT 1 FROM game_session_region_owner_transfer t
+ JOIN game_session_capacity_origin_transfer_item i ON i.transfer_id=t.transfer_id
+ WHERE t.transfer_id=o.custody_transfer_id AND t.state='COMPLETED'
+ AND t.tenant_id=o.tenant_id AND t.game_instance_id=o.game_instance_id AND t.region_id=o.region_id
+ AND t.region_epoch=current_owner.region_epoch
+ AND t.new_owner_id=o.custody_owner_id AND t.new_owner_fence=o.custody_owner_fence
+ AND t.new_lease_correlation=current_owner.lease_token_correlation
+ AND i.origin_digest=o.origin_digest AND i.canonical_origin=o.canonical_origin
+ AND i.old_owner_id=t.old_owner_id AND i.old_owner_fence=t.old_owner_fence
+ AND i.captured_state='OPEN' AND i.fence_readback IS NOT NULL
+ AND i.incarnation_digest=t.incarnation_digest AND i.verified_round=t.origin_verification_round))
+ ) THEN
+ RAISE EXCEPTION 'Closure requires the exact current origin custody' 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;
+ original := $needle$WHERE version='1066'
+ ) AND ($needle$;
+ replacement := $replacement$WHERE version='1066'
+ ) AND (
+ SELECT count(*)=1 AND coalesce(bool_and(type='SQL'
+ AND script='V1066.1__transferred_capacity_origin_recovery.sql' AND success),false)
+ FROM "${flyway:table}" WHERE version='1066.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 '1066'$needle$;
+ replacement := original||E'\n AND version IS DISTINCT FROM ''1066.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:1066','V1066__original_new_admitted_logout_intent.sql'$needle$;
+ replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1066.1'',''V1066.1__transferred_capacity_origin_recovery.sql''';
+ IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN
+ RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF;
+ EXECUTE replace(definition,original,replacement);
+END;
+$migration$;
+
+INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)
+SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM (
+ SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM (
+ SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch
+ ) next_epoch
+) seal;
+-- [jooq ignore stop]
diff --git a/services/game-session-service/src/main/resources/db/migration/V1066__original_new_admitted_logout_intent.sql b/services/game-session-service/src/main/resources/db/migration/V1066__original_new_admitted_logout_intent.sql
new file mode 100644
index 0000000000..108bcc3cf0
--- /dev/null
+++ b/services/game-session-service/src/main/resources/db/migration/V1066__original_new_admitted_logout_intent.sql
@@ -0,0 +1,94 @@
+-- Durable intent for the exact original admitted generation. Completion requires a separate
+-- protected teardown receipt after actual serving and resume authority have been fenced.
+CREATE TABLE game_session_original_new_admitted_logout_intent (
+ logout_id UUID PRIMARY KEY CHECK (logout_id <> '00000000-0000-0000-0000-000000000000'),
+ execution_digest VARCHAR(71) NOT NULL UNIQUE
+ REFERENCES game_session_original_new_capacity_execution(execution_digest),
+ transition_id UUID NOT NULL REFERENCES game_session_canonical_binding_transition(transition_id),
+ binding_generation NUMERIC NOT NULL CHECK (binding_generation > 0),
+ original_final_session_sha256 CHAR(64) NOT NULL
+ CHECK (original_final_session_sha256 ~ '^[0-9a-f]{64}$'),
+ original_session_sha1 CHAR(40) NOT NULL CHECK (original_session_sha1 ~ '^[0-9a-f]{40}$')
+);
+
+-- [jooq ignore start]
+CREATE FUNCTION guard_gs_original_new_admitted_logout_intent() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ IF TG_OP <> 'INSERT' THEN
+ RAISE EXCEPTION 'Original NEW admitted logout intent is immutable' USING ERRCODE = '23514';
+ END IF;
+ IF NOT EXISTS (
+ SELECT 1 FROM game_session_original_new_capacity_execution admitted_execution
+ JOIN game_session_canonical_binding_transition admission_transition
+ ON admission_transition.transition_id = admitted_execution.transition_id
+ JOIN game_session_canonical_gameplay_binding_inventory active_binding
+ ON active_binding.binding_ref = admission_transition.candidate_binding_ref
+ AND active_binding.transition_id = admission_transition.transition_id
+ WHERE admitted_execution.execution_digest = NEW.execution_digest
+ AND admitted_execution.transition_id = NEW.transition_id
+ AND admitted_execution.status = 'COMMITTED'
+ AND admission_transition.status = 'COMMITTED'
+ AND admission_transition.original_new_capacity_execution_digest = admitted_execution.execution_digest
+ AND admission_transition.original_new_final_session_sha256 = NEW.original_final_session_sha256
+ AND admission_transition.candidate_binding_generation = NEW.binding_generation
+ AND active_binding.binding_generation = NEW.binding_generation
+ AND active_binding.lifecycle = 'ACTIVE'
+ FOR SHARE OF admission_transition, active_binding
+ ) THEN
+ RAISE EXCEPTION 'Logout intent requires the exact active original NEW final admission'
+ USING ERRCODE = '23514';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER gs_original_new_admitted_logout_intent_guard
+ BEFORE INSERT OR UPDATE OR DELETE ON game_session_original_new_admitted_logout_intent
+ FOR EACH ROW EXECUTE FUNCTION guard_gs_original_new_admitted_logout_intent();
+CREATE TRIGGER gs_original_new_admitted_logout_intent_no_truncate
+ BEFORE TRUNCATE ON game_session_original_new_admitted_logout_intent
+ FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_original_new_admitted_logout_intent();
+
+INSERT INTO game_session_runtime_family_classification
+ (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence)
+VALUES ('game_session_original_new_admitted_logout_intent','game_session_original_new_admitted_logout_intent',
+ 'CONTROL','NOT_PAYLOAD','CONTROL_ONLY','OWNER_POLICY_RETAINED',
+ 'Retain exact admitted-generation logout intent and original FINAL binding. An intent supplies no terminal, replay erasure, or Account usage retirement authority.');
+
+DO $migration$
+DECLARE definition TEXT; original TEXT; replacement TEXT;
+BEGIN
+ SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition;
+ original := $needle$WHERE version='1065.0.3'
+ ) AND ($needle$;
+ replacement := $replacement$WHERE version='1065.0.3'
+ ) AND (
+ SELECT count(*)=1 AND coalesce(bool_and(type='SQL'
+ AND script='V1066__original_new_admitted_logout_intent.sql' AND success),false)
+ FROM "${flyway:table}" WHERE version='1066'
+ ) AND ($replacement$;
+ IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN
+ RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF;
+ EXECUTE replace(definition,original,replacement);
+
+ SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition;
+ original := $needle$AND version IS DISTINCT FROM '1065.0.3'$needle$;
+ replacement := original||E'\n AND version IS DISTINCT FROM ''1066''';
+ IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN
+ RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF;
+ definition := replace(definition,original,replacement);
+ original := $needle$SELECT 'MIGRATION','catalog-installation:1065.0.3','V1065.0.3__require_initial_capacity_execution_dispatch.sql'$needle$;
+ replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1066'',''V1066__original_new_admitted_logout_intent.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-admitted-logout.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-admitted-logout.lua
new file mode 100644
index 0000000000..550838c276
--- /dev/null
+++ b/services/game-session-service/src/main/resources/redis/lua/game-session-original-new-admitted-logout.lua
@@ -0,0 +1,130 @@
+-- Tenant-slot part of admitted original NEW logout. DISPATCH requires the exact
+-- protected incarnation and durable logout intent. OBSERVE checks the postimage on
+-- the selected connection. Terminal settlement and retirement use separate owners.
+local function uuid(value)
+ return type(value) == 'string' and #value == 36 and value == string.lower(value)
+ and value ~= '00000000-0000-0000-0000-000000000000'
+ and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') ~= nil
+end
+
+local function positive(value, maximumLength)
+ return type(value) == 'string' and #value <= maximumLength
+ and string.match(value, '^[1-9][0-9]*$') ~= nil
+end
+
+local function decode(bytes)
+ if type(bytes) ~= 'string' or #bytes == 0 or #bytes > 1048576 then return nil end
+ local ok, value = pcall(cjson.decode, bytes)
+ if not ok or type(value) ~= 'table' then return nil end
+ return value
+end
+
+if #KEYS ~= 5 or #ARGV ~= 14 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 executionDigest, logoutId, deadlineText = ARGV[9], ARGV[10], ARGV[11]
+local executionBytes, sessionSha1 = ARGV[12], ARGV[13]
+local action = ARGV[14]
+if not uuid(tenantId) or not uuid(accountId) or not uuid(namespaceId) or not uuid(characterId)
+ or not uuid(gameInstanceId) or not uuid(sessionId) or not uuid(logoutId)
+ or not positive(generation, 256) or #tag > 44
+ or not string.match(tag, '^g[1-9][0-9]*%-[0-9a-f]+$')
+ or #executionDigest ~= 71 or not string.match(executionDigest, '^sha256:[0-9a-f]+$')
+ or #sessionSha1 ~= 40 or not string.match(sessionSha1, '^[0-9a-f]+$')
+ or not positive(deadlineText, 16)
+ or (action ~= 'DISPATCH' and action ~= 'OBSERVE') then return -2 end
+local deadline = tonumber(deadlineText)
+if not deadline or deadline > 9007199254740991
+ or string.format('%.0f', deadline) ~= deadlineText then return -2 end
+
+local prefix = 'session:game:'
+local slot = '{' .. tag .. '}'
+if KEYS[1] ~= prefix .. slot .. ':' .. gameInstanceId .. ':' .. sessionId
+ or KEYS[2] ~= prefix .. 'index:character:' .. slot .. ':' .. namespaceId .. ':' .. characterId
+ or KEYS[3] ~= prefix .. 'index:account-tenant:' .. slot .. ':' .. accountId
+ or KEYS[4] ~= prefix .. 'index:tenant:' .. slot then return -2 end
+
+-- The admitted marker is the original immutable execution witness, never logout state.
+if redis.call('TYPE', KEYS[5]).ok ~= 'hash' or redis.call('PTTL', KEYS[5]) ~= -1
+ or redis.call('HLEN', KEYS[5]) ~= 6
+ or redis.call('HGET', KEYS[5], 'state') ~= 'COMMITTED'
+ or redis.call('HGET', KEYS[5], 'digest') ~= executionDigest
+ or redis.call('HGET', KEYS[5], 'binding') ~= executionBytes
+ or redis.call('HGET', KEYS[5], 'sessionSha1') ~= sessionSha1 then return -1 end
+local execution = decode(executionBytes)
+if not execution or execution.schema ~= 'gs-original-new-capacity-execution/v1'
+ or execution.tenantId ~= tenantId or not uuid(execution.admissionAttemptId)
+ or KEYS[5] ~= prefix .. 'capacity-execution:' .. slot .. ':' .. execution.admissionAttemptId then
+ return -1
+end
+local admissionAt = redis.call('HGET', KEYS[5], 'admissionAt')
+local continuityExpiresAt = redis.call('HGET', KEYS[5], 'continuityExpiresAt')
+if not positive(admissionAt, 16) or not positive(continuityExpiresAt, 16) then return -1 end
+
+if redis.call('TYPE', KEYS[1]).ok ~= 'string' or redis.call('PTTL', KEYS[1]) ~= -1 then
+ return -1
+end
+local session = redis.call('GET', KEYS[1])
+local characterType = redis.call('TYPE', KEYS[2]).ok
+if characterType ~= 'none'
+ and (characterType ~= 'string' or redis.call('PTTL', KEYS[2]) ~= -1) then return -1 end
+local character = redis.call('GET', KEYS[2])
+local characterExpected = '{"sessionId":"' .. sessionId .. '","gameInstanceId":"' .. gameInstanceId
+ .. '","bindingGeneration":"' .. generation .. '"}'
+local function membership(key)
+ local kind = redis.call('TYPE', key).ok
+ if kind == 'none' then return 0 end
+ if kind ~= 'set' or redis.call('PTTL', key) ~= -1 then return nil end
+ return redis.call('SISMEMBER', key, sessionId)
+end
+local accountMember, tenantMember = membership(KEYS[3]), membership(KEYS[4])
+local tombstone = '{"purpose":"original-new-admitted-logout/v1","bindingGeneration":"' .. generation
+ .. '","capacityExecutionDigest":"' .. executionDigest .. '","logoutId":"' .. logoutId
+ .. '","originalSessionSha1":"' .. sessionSha1 .. '"}'
+
+if session == tombstone then
+ if accountMember ~= 0 or tenantMember ~= 0 then return -1 end
+ if character then
+ -- An exact readback may coexist with a successor, whose pointer must remain intact.
+ local next = decode(character)
+ if not next or not uuid(next.sessionId) or next.sessionId == sessionId
+ or not uuid(next.gameInstanceId) or not positive(next.bindingGeneration, 256)
+ or #next.bindingGeneration < #generation
+ or (#next.bindingGeneration == #generation and next.bindingGeneration <= generation)
+ or character ~= '{"sessionId":"' .. next.sessionId .. '","gameInstanceId":"'
+ .. next.gameInstanceId .. '","bindingGeneration":"' .. next.bindingGeneration .. '"}' then
+ return -1
+ end
+ end
+ return 2
+end
+-- Recovery uses EVALSHA_RO. A live value or absent marker cannot prove a completed fence.
+if action == 'OBSERVE' then return -1 end
+if redis.sha1hex(session) ~= sessionSha1 or character ~= characterExpected
+ or accountMember ~= 1 or tenantMember ~= 1 then return -1 end
+local admitted = decode(session)
+if not admitted or admitted.schemaVersion ~= 2 or admitted.admissionState ~= 'COMPLETE'
+ or admitted.bindingGeneration ~= generation or admitted.capacityExecutionDigest ~= executionDigest
+ or admitted.admissionAt ~= admissionAt or admitted.continuityBindingExpiresAt ~= continuityExpiresAt then
+ return -1
+end
+
+local time = redis.call('TIME')
+local seconds, micros = tonumber(time[1]), tonumber(time[2])
+if not seconds or not micros or seconds < 1 or seconds > math.floor((9007199254740991 - 999) / 1000)
+ or seconds ~= math.floor(seconds) or micros < 0 or micros >= 1000000
+ or micros ~= math.floor(micros) then return -1 end
+local now = seconds * 1000 + math.floor(micros / 1000)
+if now >= deadline then return -1 end
+if not redis.acl_check_cmd('SET', KEYS[1], tombstone)
+ or not redis.acl_check_cmd('DEL', KEYS[2])
+ or not redis.acl_check_cmd('SREM', KEYS[3], sessionId)
+ or not redis.acl_check_cmd('SREM', KEYS[4], sessionId) then return -1 end
+
+-- Replacing the serving key prevents same-binding restoration from treating absence as free.
+-- The pointer and memberships are removed only after the exact current generation matches.
+redis.call('SET', KEYS[1], tombstone)
+redis.call('DEL', KEYS[2])
+redis.call('SREM', KEYS[3], sessionId)
+redis.call('SREM', KEYS[4], sessionId)
+return 1
diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-admitted-logout.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-admitted-logout.json
new file mode 100644
index 0000000000..3e81f4a51e
--- /dev/null
+++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-original-new-admitted-logout.json
@@ -0,0 +1,113 @@
+{
+ "scriptId": "game-session.original-new-admitted-logout.v1",
+ "resourcePath": "redis/lua/game-session-original-new-admitted-logout.lua",
+ "sha256": "a06ee8164ba15e239ddc1e0aea1e7c239da1de74ad857cb66f8cb2b8cf24b10c",
+ "owner": "game-session-service",
+ "principal": "gamesession_coord_app",
+ "role": "COORDINATION",
+ "keys": [
+ {
+ "name": "session",
+ "ownedPrefix": "session:game:",
+ "hashTagDeclaration": "REQUIRED"
+ },
+ {
+ "name": "characterIndex",
+ "ownedPrefix": "session:game:index:character:",
+ "hashTagDeclaration": "REQUIRED"
+ },
+ {
+ "name": "accountTenantIndex",
+ "ownedPrefix": "session:game:index:account-tenant:",
+ "hashTagDeclaration": "REQUIRED"
+ },
+ {
+ "name": "tenantIndex",
+ "ownedPrefix": "session:game:index:tenant:",
+ "hashTagDeclaration": "REQUIRED"
+ },
+ {
+ "name": "capacityExecution",
+ "ownedPrefix": "session:game:capacity-execution:",
+ "hashTagDeclaration": "REQUIRED"
+ }
+ ],
+ "arguments": [
+ {
+ "name": "tenantId"
+ },
+ {
+ "name": "accountId"
+ },
+ {
+ "name": "playableStateNamespaceId"
+ },
+ {
+ "name": "characterId"
+ },
+ {
+ "name": "gameInstanceId"
+ },
+ {
+ "name": "sessionId"
+ },
+ {
+ "name": "bindingGeneration"
+ },
+ {
+ "name": "tenantGameplayTag"
+ },
+ {
+ "name": "capacityExecutionDigest"
+ },
+ {
+ "name": "logoutId"
+ },
+ {
+ "name": "absoluteDeadlineMillis"
+ },
+ {
+ "name": "capacityExecutionBytes"
+ },
+ {
+ "name": "originalSessionSha1"
+ },
+ {
+ "name": "action"
+ }
+ ],
+ "category": "SESSION_CAS",
+ "outcomes": [
+ {
+ "code": "ADMITTED_LOGOUT_FENCE_INSTALLED",
+ "category": "SUCCESS",
+ "effect": "MUTATING"
+ },
+ {
+ "code": "ADMITTED_LOGOUT_FENCE_OBSERVED",
+ "category": "REPLAY",
+ "effect": "NON_MUTATING"
+ },
+ {
+ "code": "CURRENT_PHYSICAL_STATE_REFUSED",
+ "category": "STALE",
+ "effect": "NON_MUTATING"
+ },
+ {
+ "code": "INVALID_ARGUMENTS",
+ "category": "VALIDATION_FAILURE",
+ "effect": "NON_MUTATING"
+ }
+ ],
+ "resetSensitivity": "CLUSTER",
+ "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET",
+ "tailLossBehavior": "The manually composed owner only invokes OBSERVE with EVALSHA_RO. A live serving value, missing or changed logout marker, or contradictory indexes cannot prove a logout fence. Exact observation is read-only and preserves a valid newer character pointer. The script also contains a held DISPATCH branch that replaces the exact original serving value and removes its local index entries. This descriptor supplies no dispatch or terminal settlement authority. Loss of the marker remains indeterminate and must not recreate it.",
+ "compatibilityLevel": "REQUIRES_CLUSTER_RESET",
+ "supportedCoexistence": [
+ {
+ "callerVersion": "v1",
+ "payloadVersion": "none"
+ }
+ ],
+ "legacyPayloadShape": null
+}
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java
index 0f236999f3..59113af3aa 100644
--- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java
@@ -668,9 +668,14 @@ static Target target(CanonicalPlayableTarget target) {
/** Retains the existing controlled upstream lease before any provisional publication. */
CanonicalGameplayAdmissionDecision originalPreparedDecisionWithControlledAccountLease() {
+ return originalPreparedDecisionWithControlledAccountLease(false);
+ }
+
+ CanonicalGameplayAdmissionDecision originalPreparedDecisionWithControlledAccountLease(
+ boolean capacityAuthority) {
return new CanonicalGameplayAdmissionDecision(
transitionId,
- controlledLeaseEvidence(identity, generation, target),
+ controlledLeaseEvidence(identity, generation, target, capacityAuthority),
identity,
generation,
null,
@@ -1295,9 +1300,25 @@ public boolean hasExactOtherControllerMember(String seed) {
}
}
- /** Publishes a controlled Account lease through the actual SQL and Redis provisional owners. */
+ /** Publishes a controlled Account lease and projects the issuer member through real owners. */
public void publishOtherControllerNew(String seed) {
var operation = otherOperation(seed);
+ var decision = otherControllerDecision(seed);
+ repository.markProvisional(
+ repository.readProvisionalCasEvidence(decision.bindingDecisionId()), decision);
+ new CanonicalGameplayIssuerBindingLocalRedisOwner(
+ issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource)
+ .projectAndRead(operation);
+ }
+
+ /** Supplies the controlled Account decision without advancing its prepared transition. */
+ CanonicalGameplayAdmissionDecision otherControllerDecision(String seed) {
+ return otherControllerDecision(seed, false);
+ }
+
+ CanonicalGameplayAdmissionDecision otherControllerDecision(
+ String seed, boolean capacityAuthority) {
+ var operation = otherOperation(seed);
var transitionId = operation.request().transitionId();
var evidence = repository.readProvisionalCasEvidence(transitionId);
var lease =
@@ -1307,19 +1328,27 @@ public void publishOtherControllerNew(String seed) {
controlledLeaseEvidence(
operation.request().candidate(),
evidence.transition().bindingGeneration(),
- target));
- repository.markProvisional(
- evidence,
- new CanonicalGameplayAdmissionDecision(
- transitionId,
- lease,
- operation.request().candidate(),
- evidence.transition().bindingGeneration(),
- null,
- target));
- new CanonicalGameplayIssuerBindingLocalRedisOwner(
- issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource)
- .projectAndRead(operation);
+ target,
+ capacityAuthority));
+ return new CanonicalGameplayAdmissionDecision(
+ transitionId,
+ lease,
+ operation.request().candidate(),
+ evidence.transition().bindingGeneration(),
+ null,
+ target);
+ }
+
+ /** Persists the exact projected issuer ACK for an independently retained NEW operation. */
+ public CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledgeOtherControllerNew(
+ String seed) {
+ var operation = otherOperation(seed);
+ var physicalReadback =
+ new CanonicalGameplayIssuerBindingLocalRedisOwner(
+ issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource)
+ .projectAndRead(operation);
+ return new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource)
+ .acknowledge(physicalReadback);
}
/** Records a controlled Account abort through the actual Game Session SQL abort owner. */
@@ -1786,6 +1815,14 @@ private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence(
CanonicalGameplayBindingIdentity candidate,
BigInteger bindingGeneration,
CanonicalPlayableTarget target) {
+ return controlledLeaseEvidence(candidate, bindingGeneration, target, false);
+ }
+
+ private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence(
+ CanonicalGameplayBindingIdentity candidate,
+ BigInteger bindingGeneration,
+ CanonicalPlayableTarget target,
+ boolean capacityAuthority) {
long now = System.currentTimeMillis();
String nowSeconds = Long.toString(now / 1000L);
Map carrier = new LinkedHashMap<>();
@@ -1817,14 +1854,25 @@ private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence(
scope.put("regionId", candidate.regionId().toString());
scope.put("regionEpoch", candidate.regionEpoch().toString());
carrier.put("bindingScope", scope);
- carrier.put(
- "authorityTuple",
- Map.of(
- "issuerAuthGeneration", candidate.issuerAuthGeneration().toString(),
- "accountAuthorityGeneration", "1",
- "tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"),
- "membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1"),
- "privateRealmGrantVersions", List.of()));
+ String tenant = candidate.tenantId().toString();
+ Map authority = new LinkedHashMap<>();
+ authority.put("issuerAuthGeneration", candidate.issuerAuthGeneration().toString());
+ authority.put("accountAuthorityGeneration", "1");
+ authority.put("tenantAuthorityGeneration", Map.of(tenant, capacityAuthority ? "2" : "1"));
+ authority.put("membershipAuthorityGeneration", Map.of(tenant, "1"));
+ authority.put("privateRealmGrantVersions", List.of());
+ if (capacityAuthority) {
+ authority.put(
+ "tenantBillingCutoff",
+ Map.of(
+ tenant,
+ Map.of(
+ "tenantAuthorityGeneration", "2",
+ "tenantBillingSequence", "1",
+ "outboxStreamKey", "account:auth-authority:v1:tenant/" + tenant,
+ "outboxSequence", "1")));
+ }
+ carrier.put("authorityTuple", authority);
carrier.put("issuanceFence", "1");
carrier.put(
"membershipBaseline",
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledOriginTransferObservationFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledOriginTransferObservationFixture.java
index d56605a763..3ee0bb4d88 100644
--- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledOriginTransferObservationFixture.java
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayControlledOriginTransferObservationFixture.java
@@ -10,6 +10,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
import tools.jackson.databind.json.JsonMapper;
@@ -25,18 +26,31 @@ final class CanonicalGameplayControlledOriginTransferObservationFixture {
private static final JsonMapper JSON = JsonMapper.builder().build();
private final KeyPair keys;
private final Clock clock;
+ private final Duration observationLatency;
+ private final AtomicInteger observationCount = new AtomicInteger();
CanonicalGameplayControlledOriginTransferObservationFixture() throws Exception {
- this(Clock.systemUTC());
+ this(Clock.systemUTC(), Duration.ZERO);
}
CanonicalGameplayControlledOriginTransferObservationFixture(Clock clock) throws Exception {
+ this(clock, Duration.ZERO);
+ }
+
+ CanonicalGameplayControlledOriginTransferObservationFixture(
+ Clock clock, Duration observationLatency) throws Exception {
this.clock = Objects.requireNonNull(clock, "clock");
+ this.observationLatency = Objects.requireNonNull(observationLatency, "observationLatency");
+ if (observationLatency.isNegative()) throw new IllegalArgumentException();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
keys = generator.generateKeyPair();
}
+ int observationCount() {
+ return observationCount.get();
+ }
+
CanonicalGameplayProtectedIncarnationReceiver receiver(
CanonicalGameplayCapacityOriginTransferRepository source,
CanonicalGameplayTenantGameplayTagRepository tags) {
@@ -82,6 +96,17 @@ private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe(
!= CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.ORIGIN_OWNER_TRANSFER) {
throw new IllegalArgumentException("Controlled channel is limited to transfer observations");
}
+ long observedAt = request.issuedAtEpochMillis();
+ if (!observationLatency.isZero()) {
+ try {
+ Thread.sleep(observationLatency);
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Controlled origin observation interrupted", interrupted);
+ }
+ observedAt = clock.millis();
+ }
+ observationCount.incrementAndGet();
var transfer = context.originTransferContext();
Map owner = new LinkedHashMap<>();
owner.put("ownerKind", context.ownerKind().name());
@@ -131,7 +156,7 @@ private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe(
root.put("acceptedAttestationDigest", request.acceptedAttestationDigest());
root.put("observationNonce", request.nonce());
root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis());
- root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis());
+ root.put("observationObservedAtEpochMillis", observedAt);
root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis());
root.put("owner", owner);
root.put("target", target);
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
index 7312cf40c3..9243c616a9 100644
--- 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
@@ -10,6 +10,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
import tools.jackson.databind.json.JsonMapper;
@@ -26,6 +27,8 @@ final class CanonicalGameplayControlledRegionTransferObservationFixture {
private final KeyPair keys;
private final Clock clock;
private final Duration observationTtl;
+ private final Duration observationLatency;
+ private final AtomicInteger observationCount = new AtomicInteger();
CanonicalGameplayControlledRegionTransferObservationFixture() throws Exception {
this(Clock.systemUTC());
@@ -37,13 +40,24 @@ final class CanonicalGameplayControlledRegionTransferObservationFixture {
CanonicalGameplayControlledRegionTransferObservationFixture(Clock clock, Duration observationTtl)
throws Exception {
+ this(clock, observationTtl, Duration.ZERO);
+ }
+
+ CanonicalGameplayControlledRegionTransferObservationFixture(
+ Clock clock, Duration observationTtl, Duration observationLatency) throws Exception {
this.clock = Objects.requireNonNull(clock, "clock");
this.observationTtl = Objects.requireNonNull(observationTtl, "observationTtl");
+ this.observationLatency = Objects.requireNonNull(observationLatency, "observationLatency");
+ if (observationLatency.isNegative()) throw new IllegalArgumentException();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
keys = generator.generateKeyPair();
}
+ int observationCount() {
+ return observationCount.get();
+ }
+
CanonicalGameplayProtectedIncarnationReceiver receiver(
CanonicalGameplayRegionOwnerTransferObservationSource source,
CanonicalGameplayTenantGameplayTagRepository tags) {
@@ -89,6 +103,17 @@ private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe(
!= CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.REGION_OWNER_TRANSFER) {
throw new IllegalArgumentException("Controlled channel is limited to transfer observations");
}
+ long observedAt = request.issuedAtEpochMillis();
+ if (!observationLatency.isZero()) {
+ try {
+ Thread.sleep(observationLatency);
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Controlled transfer observation interrupted", interrupted);
+ }
+ observedAt = clock.millis();
+ }
+ observationCount.incrementAndGet();
var transfer = context.regionOwnerTransferContext();
Map owner = new LinkedHashMap<>();
owner.put("ownerKind", context.ownerKind().name());
@@ -134,7 +159,7 @@ private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe(
root.put("acceptedAttestationDigest", request.acceptedAttestationDigest());
root.put("observationNonce", request.nonce());
root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis());
- root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis());
+ root.put("observationObservedAtEpochMillis", observedAt);
root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis());
root.put("owner", owner);
root.put("target", target);
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java
index 90e8a48e23..9e359645a1 100644
--- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCapacityRetentionOwnerIntegrationTest.java
@@ -3,8 +3,11 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import io.lettuce.core.ScriptOutputType;
+import java.util.List;
import java.util.Map;
import java.util.UUID;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog;
import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot;
import net.firedevops.firemud.test.TestContainerImages;
import org.junit.jupiter.api.Test;
@@ -777,4 +780,129 @@ void actualFinalBeforeAccountFenceRetainsPhysicalPositiveButRecoveryRemainsIndet
.isEqualTo("AUTHORIZED");
}
}
+
+ @Test
+ void admittedLogoutIntentRequiresActualFinalAndReplaysAfterServingStateDisappears()
+ throws Exception {
+ repairAccountMember();
+ bridge();
+ var provisional = inventory.readOriginalNewFinalAdmissionSource(decision);
+ var intents = new CanonicalGameplayOriginalNewAdmittedLogoutIntentRepository(fixture.dsl());
+ var logout = UUID.randomUUID();
+ assertThatThrownBy(
+ () -> intents.prepare(logout, provisional, controlledCapacity, new byte[] {1}))
+ .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class);
+ try (var credential =
+ new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(
+ provisional.candidate(), CLOCK);
+ var template = credential.template();
+ var actual =
+ finalOwner()
+ .finalizeOriginalNewOnce(
+ provisional,
+ template,
+ controlledAccountOpen(),
+ issuerOpen(),
+ controlledCapacity,
+ deadline())) {
+ inventory.commitOriginalNewFinalAdmission(actual);
+ }
+ var admitted = inventory.readOriginalNewFinalAdmissionSource(decision);
+ var assignment = tags.assignmentForTransition(fixture.transitionId());
+ var sessionKey =
+ CanonicalGameplaySessionRedisKeys.session(
+ assignment, admitted.candidate().bindingIdentity().bindingRef());
+ var execution = controlledCapacity;
+ var physical = physicalImage();
+ byte[] observed = admin.get(ascii(sessionKey));
+ var retained = intents.prepare(logout, admitted, execution, observed);
+ assertThat(retained.originalFinalSessionSha256())
+ .isEqualTo(admitted.finalReceipt().orElseThrow().finalSessionSha256());
+ assertThat(intents.prepare(logout, admitted, execution, observed)).isEqualTo(retained);
+ assertThatThrownBy(() -> intents.prepare(UUID.randomUUID(), admitted, execution, observed))
+ .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class);
+ assertThatThrownBy(() -> intents.prepare(logout, admitted, execution, new byte[] {1}))
+ .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class);
+ assertThatThrownBy(
+ () -> capacityOwner().requireAdmittedLogoutFence(logout, execution, deadline()))
+ .isInstanceOf(IllegalStateException.class);
+ assertThat(physicalImage()).isEqualTo(physical);
+ assertThatThrownBy(
+ () ->
+ fixture
+ .dsl()
+ .execute(
+ "DELETE FROM game_session_original_new_admitted_logout_intent WHERE"
+ + " logout_id = ?",
+ logout))
+ .isInstanceOf(org.jooq.exception.DataAccessException.class);
+ var binding = admitted.candidate().bindingIdentity();
+ var ref = binding.bindingRef();
+ try (var script =
+ getClass()
+ .getResourceAsStream("/redis/lua/game-session-original-new-admitted-logout.lua")) {
+ assertThat(script).isNotNull();
+ assertThat(
+ admin.eval(
+ java.util.Objects.requireNonNull(script).readAllBytes(),
+ ScriptOutputType.INTEGER,
+ new byte[][] {
+ ascii(sessionKey),
+ ascii(CanonicalGameplaySessionRedisKeys.characterIndex(assignment, ref)),
+ ascii(CanonicalGameplaySessionRedisKeys.accountTenantIndex(assignment, ref)),
+ ascii(CanonicalGameplaySessionRedisKeys.tenantIndex(assignment, ref)),
+ ascii(capacityKey(assignment))
+ },
+ ascii(binding.tenantId().toString()),
+ ascii(binding.accountId().toString()),
+ ascii(binding.playableStateNamespaceId().toString()),
+ ascii(binding.characterId().toString()),
+ ascii(binding.gameInstanceId().toString()),
+ ascii(binding.sessionId()),
+ ascii(retained.bindingGeneration().toString()),
+ ascii(assignment.tenantGameplayTag()),
+ ascii(retained.executionDigest()),
+ ascii(logout.toString()),
+ ascii(Long.toString(deadline())),
+ execution.canonicalBytes(),
+ ascii(retained.originalSessionSha1()),
+ ascii("DISPATCH")))
+ .isEqualTo(1L);
+ }
+ var fenced = physicalImage();
+ var sql = sqlImage();
+ capacityOwner().requireAdmittedLogoutFence(logout, execution, deadline());
+ var ownerWithoutLogoutDescriptor =
+ new CanonicalGameplayOriginalNewCapacityExecutionOwner(
+ fixture.dsl(),
+ ownerClient,
+ RedisScriptCatalog.fromContributions(List.of()),
+ CLOCK,
+ tags);
+ assertThatThrownBy(
+ () ->
+ ownerWithoutLogoutDescriptor.requireAdmittedLogoutFence(
+ logout, execution, deadline()))
+ .isInstanceOf(IllegalStateException.class);
+ assertThatThrownBy(
+ () ->
+ capacityOwner()
+ .requireAdmittedLogoutFence(UUID.randomUUID(), execution, deadline()))
+ .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class);
+ assertThat(physicalImage()).isEqualTo(fenced);
+ assertThat(sqlImage()).isEqualTo(sql);
+ controlledRemoveServingKeys(admitted, assignment);
+ assertThatThrownBy(
+ () -> capacityOwner().requireAdmittedLogoutFence(logout, execution, deadline()))
+ .isInstanceOf(IllegalStateException.class);
+ assertThat(
+ new CanonicalGameplayOriginalNewAdmittedLogoutIntentRepository(fixture.dsl())
+ .readExact(execution.digest(), logout))
+ .isEqualTo(retained);
+ assertThat(
+ capacityOwner()
+ .readExact(controlledCapacity.request(), controlledCapacity.reservation())
+ .disposition())
+ .isEqualTo("COMMITTED");
+ }
}
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 50a97409eb..61680aa072 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
@@ -22,6 +22,7 @@
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
@@ -54,6 +55,7 @@
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
+import org.jooq.impl.DefaultExecuteListener;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
@@ -663,6 +665,62 @@ public Receipt complete(
net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient capacityClient,
net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request
capacityRequest) {
+ return complete(
+ binding.dsl(), account, jwks, originalLoginJwt, deadline, capacityClient, capacityRequest);
+ }
+
+ /**
+ * Runs the real coordinator and physical FINAL, then loses the original admission SQL commit
+ * reply after its transition update has executed. PostgreSQL rolls back the update while Redis
+ * retains the independently committed FINAL.
+ */
+ public void completeWithLostOriginalAdmissionCommit(
+ AccountGameplayAdmissionLeaseClient account,
+ AccountPublicJwksCache jwks,
+ String originalLoginJwt,
+ long deadline,
+ net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient capacityClient,
+ net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request
+ capacityRequest) {
+ var injected = new AtomicBoolean();
+ DSLContext faultDsl =
+ DSL.using(
+ binding
+ .dsl()
+ .configuration()
+ .deriveAppending(
+ new DefaultExecuteListener() {
+ @Override
+ public void executeEnd(org.jooq.ExecuteContext context) {
+ String query = context.sql();
+ if (query != null
+ && query
+ .toLowerCase(java.util.Locale.ROOT)
+ .replaceAll("\\s+", " ")
+ .contains(
+ "update game_session_canonical_binding_transition set status = 'committed'")) {
+ if (!injected.compareAndSet(false, true)) return;
+ throw new IllegalStateException(
+ "Controlled loss of original admission SQL commit reply");
+ }
+ }
+ }));
+ complete(faultDsl, account, jwks, originalLoginJwt, deadline, capacityClient, capacityRequest);
+ throw new IllegalStateException(
+ injected.get()
+ ? "Controlled loss of original admission SQL commit reply"
+ : "Original admission SQL commit fault was not reached");
+ }
+
+ private Receipt complete(
+ DSLContext inventoryDsl,
+ AccountGameplayAdmissionLeaseClient account,
+ AccountPublicJwksCache jwks,
+ String originalLoginJwt,
+ long deadline,
+ net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient capacityClient,
+ net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request
+ capacityRequest) {
// Recreate the coordinator and its SQL/INITIAL/issuer/final owners on every invocation.
var issuerSource = binding.currentIssuerSource();
var issuer =
@@ -674,7 +732,7 @@ public Receipt complete(
issuerSource);
var coordinator =
new CanonicalGameplayOriginalNewFinalAdmissionCoordinator(
- new CanonicalGameplayBindingInventoryRepository(binding.dsl()),
+ new CanonicalGameplayBindingInventoryRepository(inventoryDsl),
account,
initialOwner(),
issuer,
@@ -698,6 +756,25 @@ public Receipt complete(
result.finalSessionSha256());
}
+ /** Performs the real Account fence acquisition, retaining any exact physical pre-intent FINAL. */
+ public UUID acquireAccountFenceAndCaptureFinal(
+ net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request,
+ net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result reservation,
+ long deadline) {
+ if (!(request.context()
+ instanceof
+ net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext
+ player))
+ throw new IllegalArgumentException("Original NEW player capacity request is required");
+ var owner =
+ new CanonicalGameplayOriginalNewCapacityExecutionOwner(
+ binding.dsl(), coordination, scripts, CLOCK, tags);
+ return new CanonicalGameplayAccountAdmissionBarrierRepository(binding.dsl(), CLOCK)
+ .beginFenceIntentWithFinalObservation(
+ player.accountId(), UUID.randomUUID(), owner, request, reservation, deadline)
+ .operationId();
+ }
+
/** Compose the origin recovery scripts for the controlled receiver. */
public void enableOriginReceiving() {
scripts =
@@ -759,7 +836,7 @@ public java.util.Map originBudgetImage() {
binding
.dsl()
.fetchSingle(
- "SELECT recovery_deadline,recovery_max_observations,recovery_observations,last_observation_deadline,reservation_policy_applied,custody_owner_id,custody_owner_fence,state FROM game_session_original_new_capacity_origin");
+ "SELECT recovery_deadline,recovery_max_observations,recovery_observations,last_observation_deadline,last_observation_custody_fence,reservation_policy_applied,custody_owner_id,custody_owner_fence,state FROM game_session_original_new_capacity_origin");
return new java.util.LinkedHashMap<>(row.intoMap());
}
@@ -769,11 +846,22 @@ public java.util.Map originPhysicalImage() {
.dsl()
.fetchSingle(
"SELECT tenant_gameplay_tag,admission_attempt_id FROM game_session_original_new_capacity_origin");
- String key =
+ return redisHashImage(
"session:game:capacity-origin:{"
+ row.get("tenant_gameplay_tag", String.class)
+ "}:"
- + row.get("admission_attempt_id", java.util.UUID.class);
+ + row.get("admission_attempt_id", UUID.class));
+ }
+
+ public java.util.Map capacityExecutionPhysicalImage(UUID attemptId) {
+ return redisHashImage(
+ "session:game:capacity-execution:{"
+ + tags.assignmentForTransition(decisionId()).tenantGameplayTag()
+ + "}:"
+ + attemptId);
+ }
+
+ private java.util.Map redisHashImage(String key) {
var result = new java.util.LinkedHashMap();
administration
.sync()
@@ -1115,6 +1203,33 @@ public java.util.Map capacityStateImage() {
return java.util.Map.copyOf(result);
}
+ /** Read-only image of the frozen Account admission fence and its captured FINAL witness. */
+ public java.util.Map accountAdmissionFenceImage() {
+ var result = new java.util.TreeMap();
+ for (String table :
+ java.util.List.of(
+ "game_session_canonical_account_coverage_control",
+ "game_session_canonical_account_admission_fence_intent",
+ "game_session_canonical_account_admission_fence_intent_cohort_row",
+ "game_session_canonical_account_admission_fence_intent_barrier_target",
+ "game_session_account_fence_final_observation")) {
+ 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)));
+ }
+ 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();
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 0e930e8690..4dff13e8d9 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
@@ -57,6 +57,7 @@ class CanonicalGameplayOriginalNewFinalAdmissionLuaIntegrationTest {
private static final String GENERATION = "1";
private static final String TRANSITION = "99999999-9999-4999-8999-999999999999";
private static final String ATTEMPT = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
+ private static final String LOGOUT = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
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();
@@ -154,6 +155,7 @@ void setUp() throws Exception {
.addCommand(CommandType.ACL, CommandKeyword.WHOAMI)
.addCommand(CommandType.SCRIPT, CommandKeyword.LOAD)
.addCommand(CommandType.EVALSHA)
+ .addCommand(CommandType.EVALSHA_RO)
.addCommand(CommandType.TYPE)
.addCommand(CommandType.PTTL)
.addCommand(CommandType.GET)
@@ -649,6 +651,151 @@ private static Map capacityPhysicalFields(ScriptCase original, S
"state", ascii(state));
}
+ @Test
+ void admittedLogoutRetainsTheOriginalFinalAndReplaysWithoutChangingANewerController()
+ throws Exception {
+ ScriptCase original = seed();
+ assertThat(eval(original)).isEqualTo(1);
+ var admittedImage = physicalImage(original);
+ String logoutScript = loadLogoutScript();
+ var logout = logoutCase(original, LOGOUT, System.currentTimeMillis() + 15_000);
+ admin.aclSetuser(
+ PRINCIPAL, new AclSetuserArgs().addCommand(CommandType.DEL).addCommand(CommandType.SREM));
+
+ assertThat(eval(logoutScript, logout)).isEqualTo(1);
+ byte[] sessionKey = ascii(original.keys()[0]);
+ byte[] characterKey = ascii(original.keys()[1]);
+ assertThat(admin.pttl(sessionKey)).isEqualTo(-1);
+ assertThat(admin.get(sessionKey))
+ .isEqualTo(
+ ascii(
+ "{\"purpose\":\"original-new-admitted-logout/v1\",\"bindingGeneration\":\""
+ + GENERATION
+ + "\",\"capacityExecutionDigest\":\""
+ + new String(original.arguments()[18], StandardCharsets.US_ASCII)
+ + "\",\"logoutId\":\""
+ + LOGOUT
+ + "\",\"originalSessionSha1\":\""
+ + new String(logout.arguments()[12], StandardCharsets.US_ASCII)
+ + "\"}"));
+ assertThat(admin.get(characterKey)).isNull();
+ assertThat(admin.sismember(ascii(original.keys()[2]), ascii(SESSION))).isFalse();
+ assertThat(admin.sismember(ascii(original.keys()[3]), ascii(SESSION))).isFalse();
+ var closedImage = physicalImage(original);
+ for (int index = 4; index < original.keys().length; index++) {
+ String key = original.keys()[index];
+ assertThat(closedImage.get(key)).containsExactly(admittedImage.get(key));
+ }
+ assertThat(eval(original)).isEqualTo(-1);
+
+ String successor = "77777777-7777-4777-8777-777777777777";
+ admin.set(
+ characterKey,
+ ascii(
+ "{\"sessionId\":\""
+ + successor
+ + "\",\"gameInstanceId\":\""
+ + INSTANCE
+ + "\",\"bindingGeneration\":\"2\"}"));
+ admin.sadd(ascii(original.keys()[2]), ascii(successor));
+ admin.sadd(ascii(original.keys()[3]), ascii(successor));
+ var successorImage = physicalImage(original);
+ assertThat(eval(logoutScript, logoutCase(original, LOGOUT, 1))).isEqualTo(2);
+ assertThat(eval(logoutScript, logoutCase(original, TRANSITION, 1))).isEqualTo(-1);
+ assertPhysicalImage(original, successorImage, 7);
+ }
+
+ @Test
+ void admittedLogoutRefusesStaleGenerationExpiryMissingOriginalAndDeniedMutationWithoutWrites()
+ throws Exception {
+ ScriptCase original = seed();
+ assertThat(eval(original)).isEqualTo(1);
+ String logoutScript = loadLogoutScript();
+ var logout = logoutCase(original, LOGOUT, System.currentTimeMillis() + 15_000);
+ var before = physicalImage(original);
+ assertThat(eval(logoutScript, logout)).isEqualTo(-1);
+ assertPhysicalImage(original, before, 7);
+ admin.aclSetuser(
+ PRINCIPAL, new AclSetuserArgs().addCommand(CommandType.DEL).addCommand(CommandType.SREM));
+ assertThat(eval(logoutScript, logoutCase(original, LOGOUT, 1))).isEqualTo(-1);
+ byte[][] staleArguments = logout.arguments().clone();
+ staleArguments[6] = ascii("2");
+ assertThat(eval(logoutScript, new ScriptCase(logout.keys(), staleArguments))).isEqualTo(-1);
+ assertPhysicalImage(original, before, 7);
+
+ admin.del(ascii(original.keys()[6]));
+ var missing = physicalImage(original);
+ assertThat(eval(logoutScript, logout)).isEqualTo(-1);
+ assertPhysicalImage(original, missing, 7);
+ }
+
+ @Test
+ void admittedLogoutReadbackNeverDispatchesAndRequiresAnExactPersistentFence() throws Exception {
+ ScriptCase original = seed();
+ assertThat(eval(original)).isEqualTo(1);
+ String logoutScript = loadLogoutScript();
+ var dispatch = logoutCase(original, LOGOUT, System.currentTimeMillis() + 15_000);
+ var observed = logoutCase(original, LOGOUT, 1);
+ observed.arguments()[13] = ascii("OBSERVE");
+ byte[][] keys =
+ java.util.Arrays.stream(observed.keys()).map(key -> ascii(key)).toArray(byte[][]::new);
+ var liveImage = physicalImage(original);
+ assertThat(observeLogout(logoutScript, keys, observed)).isEqualTo(-1);
+ assertPhysicalImage(original, liveImage, 7);
+
+ admin.aclSetuser(
+ PRINCIPAL, new AclSetuserArgs().addCommand(CommandType.DEL).addCommand(CommandType.SREM));
+ assertThat(eval(logoutScript, dispatch)).isEqualTo(1);
+ admin.aclSetuser(
+ PRINCIPAL,
+ new AclSetuserArgs()
+ .removeCommand(CommandType.SET)
+ .removeCommand(CommandType.DEL)
+ .removeCommand(CommandType.SREM));
+ var fencedImage = physicalImage(original);
+ assertThat(observeLogout(logoutScript, keys, observed)).isEqualTo(2);
+ assertPhysicalImage(original, fencedImage, 7);
+
+ admin.set(ascii(original.keys()[1]), ascii("{}"));
+ var malformedImage = physicalImage(original);
+ assertThat(observeLogout(logoutScript, keys, observed)).isEqualTo(-1);
+ assertPhysicalImage(original, malformedImage, 7);
+
+ admin.del(ascii(original.keys()[1]), ascii(original.keys()[0]));
+ var missingImage = physicalImage(original);
+ assertThat(observeLogout(logoutScript, keys, observed)).isEqualTo(-1);
+ assertPhysicalImage(original, missingImage, 7);
+ }
+
+ private long observeLogout(String sha, byte[][] keys, ScriptCase testCase) {
+ return owner.evalshaReadOnly(sha, ScriptOutputType.INTEGER, keys, testCase.arguments());
+ }
+
+ private String loadLogoutScript() throws Exception {
+ try (InputStream input =
+ getClass()
+ .getClassLoader()
+ .getResourceAsStream("redis/lua/game-session-original-new-admitted-logout.lua")) {
+ if (input == null) {
+ throw new IllegalStateException("Admitted logout script resource is absent");
+ }
+ return owner.scriptLoad(input.readAllBytes());
+ }
+ }
+
+ private ScriptCase logoutCase(ScriptCase original, String logoutId, long deadline) {
+ String[] keys = java.util.Arrays.copyOf(original.keys(), 5);
+ keys[4] = original.keys()[6];
+ byte[][] arguments = java.util.Arrays.copyOf(original.arguments(), 14);
+ arguments[8] = original.arguments()[18];
+ arguments[9] = ascii(logoutId);
+ arguments[10] = ascii(Long.toString(deadline));
+ arguments[11] = original.arguments()[16];
+ arguments[12] = admin.hget(ascii(keys[4]), ascii("sessionSha1"));
+ arguments[13] = ascii("DISPATCH");
+ return new ScriptCase(keys, arguments);
+ }
+
private static ScriptCase expired(ScriptCase original) {
byte[][] arguments = original.arguments().clone();
arguments[14] = ascii("1");
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java
index 2d71a6f17b..c4170b14a1 100644
--- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTestSupport.java
@@ -82,6 +82,7 @@ void setUp() throws Exception {
.addCommand(CommandType.ACL, CommandKeyword.WHOAMI)
.addCommand(CommandType.SCRIPT, CommandKeyword.LOAD)
.addCommand(CommandType.EVALSHA)
+ .addCommand(CommandType.EVALSHA_RO)
.addCommand(CommandType.TYPE)
.addCommand(CommandType.PTTL)
.addCommand(CommandType.GET)
@@ -117,6 +118,8 @@ void setUp() throws Exception {
new net.firedevops.firemud.gamesession.service
.CanonicalGameplayOriginalNewOriginFinalAdmissionRedisScriptContribution(),
new CanonicalGameplayCapacityOriginCustodyRedisScriptContribution(),
+ new net.firedevops.firemud.gamesession.service
+ .CanonicalGameplayOriginalNewAdmittedLogoutRedisScriptContribution(),
new net.firedevops.firemud.gamesession.service
.CanonicalGameplayAccountMemberRepairRedisScriptContribution(),
new net.firedevops.firemud.gamesession.service
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java
index 41c00e3d85..5d143c4189 100644
--- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java
@@ -287,15 +287,72 @@ enum WorldRead {
lifecycle;
private final io.grpc.Server worldServer;
private final io.grpc.Server entityServer;
+ private final Map<
+ UUID, net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest>
+ requestsByTransition;
ControlledRegionSources(
org.jooq.DSLContext dsl,
net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision decision,
java.nio.file.Path directory)
throws Exception {
+ this(dsl, List.of(decision), directory);
+ }
+
+ ControlledRegionSources(
+ org.jooq.DSLContext dsl,
+ net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision first,
+ net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision second,
+ java.nio.file.Path directory)
+ throws Exception {
+ this(dsl, List.of(first, second), directory);
+ }
+
+ private ControlledRegionSources(
+ org.jooq.DSLContext dsl,
+ List
+ decisions,
+ java.nio.file.Path directory)
+ throws Exception {
+ if (decisions.isEmpty() || decisions.size() > 2) {
+ throw new IllegalArgumentException(
+ "Controlled region sources support one or two candidates");
+ }
+ var decision = decisions.getFirst();
var target = decision.targetEvidence();
var identity = decision.candidate();
String namespace = target.targetNamespace();
+ for (var candidateDecision : decisions) {
+ var candidate = candidateDecision.candidate();
+ var candidateTarget = candidateDecision.targetEvidence();
+ if (!candidateDecision.targetEvidence().targetNamespace().equals(namespace)
+ || !candidate.tenantId().equals(identity.tenantId())
+ || !candidate.gameInstanceId().equals(identity.gameInstanceId())
+ || !candidate.regionId().equals(identity.regionId())
+ || !candidate.playableStateNamespaceId().equals(identity.playableStateNamespaceId())
+ || !candidateTarget.realmId().equals(target.realmId())
+ || !candidateTarget.canonicalVersionId().equals(target.canonicalVersionId())) {
+ throw new IllegalArgumentException(
+ "Controlled region candidates must share one exact tenant/game/region target");
+ }
+ }
+ if (decisions.size() == 2
+ && (decisions
+ .get(0)
+ .candidate()
+ .characterId()
+ .equals(decisions.get(1).candidate().characterId())
+ || decisions
+ .get(0)
+ .candidate()
+ .sessionId()
+ .equals(decisions.get(1).candidate().sessionId())
+ || decisions
+ .get(0)
+ .bindingDecisionId()
+ .equals(decisions.get(1).bindingDecisionId()))) {
+ throw new IllegalArgumentException("Controlled region candidates must be independent");
+ }
String caller = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service";
var pki =
net.firedevops.firemud.test.LoopbackMtlsTestPki.create(
@@ -384,14 +441,9 @@ enum WorldRead {
publishedRelease.commandDefinitions(),
descriptor.generationConfigRevision(),
worldSelector);
- var binding =
- new net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence(
- descriptor, release);
var selector =
net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence.fromStored(
worldSelector.selectorReceiptBytes());
- UUID placementId = UUID.randomUUID();
- UUID assignment = UUID.randomUUID();
var wireTarget =
net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget
.newBuilder()
@@ -409,33 +461,11 @@ enum WorldRead {
net.firedevops.firemud.entitymanagement.v1.PlayableStateScope
.PLAYABLE_STATE_SCOPE_SHARED)
.build();
- request =
- net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest
- .newBuilder()
- .setSchemaVersion(1)
- .setPlacementOperationUuid(placementId.toString())
- .setExpectedTarget(wireTarget)
- .setCanonicalAccountUuid(identity.accountId().toString())
- .setCharacterUuid(identity.characterId().toString())
- .setAssignmentUuid(assignment.toString())
- .setAssignmentIntentDigest("b".repeat(64))
- .setInitialAdmissionHoldUuid(target.holdId().toString())
- .setInitialAdmissionHoldFence(target.holdFence().toString())
- .setInitialAdmissionRequestId(target.initialAdmissionRequestId())
- .setInitialAdmissionRequestDigest(target.initialAdmissionRequestDigest())
- .setActiveLifecycleEpoch(target.activeWorldEpoch())
- .setTerminalProofDigest(target.ownerProofDigest())
- .setCommittedPointerVersion(target.pointerVersion())
- .setAuditEventId(target.auditEventId())
- .build();
- UUID lifecycleReadId =
- UUID.nameUUIDFromBytes(
- ("firemud-world-initial-location-lifecycle-read/v1/" + placementId)
- .getBytes(StandardCharsets.US_ASCII));
- var lifecycleRequest =
+ UUID canonicalRegion = UUID.randomUUID();
+ var lifecycleRequestTemplate =
new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request(
1,
- lifecycleReadId,
+ UUID.randomUUID(),
namespace,
identity.tenantId(),
target.worldSlug(),
@@ -448,10 +478,12 @@ enum WorldRead {
descriptor.requestDigest(),
descriptor.resultDigest(),
release.evidenceDigest());
- UUID canonicalRegion = UUID.randomUUID();
- var evidence =
+ var binding =
+ new net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence(
+ descriptor, release);
+ var lifecycleEvidenceTemplate =
new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence(
- lifecycleRequest,
+ lifecycleRequestTemplate,
binding,
selector.startLocation(),
1042L,
@@ -462,52 +494,39 @@ enum WorldRead {
selector.graphDigest().substring(7),
"sha256:" + "e".repeat(64),
Map.of(canonicalRegion, identity.regionId()));
- var room = selector.startLocation();
- var placementResult =
- net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse
- .newBuilder()
- .setSchemaVersion(1)
- .setPlacementOperationUuid(placementId.toString())
- .setRequestDigest("sha256:" + "d".repeat(64))
- .setCanonicalAccountUuid(request.getCanonicalAccountUuid())
- .setCharacterUuid(request.getCharacterUuid())
- .setAssignmentUuid(request.getAssignmentUuid())
- .setAssignmentIntentDigest(request.getAssignmentIntentDigest())
- .setResultDigest("sha256:" + "f".repeat(64))
- .setOutcome(
- net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome
- .CANONICAL_INITIAL_PLAYER_LOCATION_OUTCOME_APPLIED)
- .setStartLocation(
- net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRoom
- .newBuilder()
- .setCanonicalTenantUuid(room.tenantId().toString())
- .setCanonicalVersionUuid(room.versionId().toString())
- .setRoomTemplateUuid(room.roomTemplateId().toString()))
- .setPrivateRuntimeRoomKey("1042")
- .build();
- var observation =
- net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse
- .newBuilder()
- .setSchemaVersion(1)
- .setPlacementResult(placementResult)
- .setExpectedTarget(wireTarget)
- .setCanonicalRegionInstanceUuid(canonicalRegion.toString())
- .setOperationalRegionUuid(identity.regionId().toString())
- .setPrivateWorldInstanceKey(7L)
- .setObservedRuntimeRoomKey(1042L)
- .setLifecycle(
- net.firedevops.firemud.worldmanagement.v1
- .CanonicalInitialPlayerLocationLifecycleConsequence.newBuilder()
- .setCanonicalRequestBytes(
- com.google.protobuf.ByteString.copyFrom(
- lifecycleRequest.canonicalBytes()))
- .setLifecycleStatus("ACTIVE")
- .setLifecycleEpoch(evidence.lifecycleEpoch())
- .setRowVersion(evidence.rowVersion())
- .setCaptureUuid(evidence.captureId().toString())
- .setGraphSha256(evidence.graphSha256())
- .setPreparationInputDigest(evidence.preparationInputDigest()))
- .build();
+ var bindings =
+ java.util.stream.IntStream.range(0, decisions.size())
+ .mapToObj(
+ index ->
+ controlledBinding(
+ decisions.get(index),
+ selector,
+ wireTarget,
+ canonicalRegion,
+ lifecycleRequestTemplate,
+ lifecycleEvidenceTemplate,
+ 7301L + index))
+ .toList();
+ var bindingByRequest =
+ new java.util.HashMap<
+ net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest,
+ ControlledBinding>();
+ for (var controlledBinding : bindings) {
+ bindingByRequest.put(controlledBinding.request(), controlledBinding);
+ }
+ var bindingByLifecycleRequest =
+ new java.util.HashMap<
+ net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request,
+ ControlledBinding>();
+ for (var controlledBinding : bindings) {
+ bindingByLifecycleRequest.put(controlledBinding.lifecycleRequest(), controlledBinding);
+ }
+ request = bindings.getFirst().request();
+ requestsByTransition =
+ bindings.stream()
+ .collect(
+ java.util.stream.Collectors.toUnmodifiableMap(
+ item -> item.decision().bindingDecisionId(), ControlledBinding::request));
var worldPlacementService =
new net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationServiceGrpc
.CanonicalInitialPlayerLocationServiceImplBase() {
@@ -519,7 +538,8 @@ public void readInitialPlayerLocationRegion(
net.firedevops.firemud.worldmanagement.v1
.CanonicalInitialPlayerLocationRegionResponse>
response) {
- if (!request.equals(incoming) || !isPeer(caller)) {
+ var controlled = bindingByRequest.get(incoming);
+ if (controlled == null || !isPeer(caller)) {
response.onError(io.grpc.Status.PERMISSION_DENIED.asRuntimeException());
return;
}
@@ -527,7 +547,7 @@ public void readInitialPlayerLocationRegion(
withheldReadEntered.countDown();
return;
}
- response.onNext(observation);
+ response.onNext(controlled.observation());
response.onCompleted();
}
};
@@ -543,10 +563,11 @@ public void readWorldCanonicalInstanceLifecycle(
net.firedevops.firemud.worldmanagement.v1
.ReadWorldCanonicalInstanceLifecycleResponse>
response) {
- if (!isPeer(caller)
- || !lifecycleRequest.equals(
- net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec
- .fromRequest(incoming))) {
+ var incomingRequest =
+ net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec
+ .fromRequest(incoming);
+ var controlled = bindingByLifecycleRequest.get(incomingRequest);
+ if (!isPeer(caller) || controlled == null) {
response.onError(io.grpc.Status.PERMISSION_DENIED.asRuntimeException());
return;
}
@@ -556,7 +577,7 @@ public void readWorldCanonicalInstanceLifecycle(
}
response.onNext(
net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec
- .toResponse(lifecycleRequest, evidence));
+ .toResponse(incomingRequest, controlled.lifecycleEvidence()));
response.onCompleted();
}
};
@@ -572,12 +593,12 @@ public void readPreseededActorRuntimeReference(
net.firedevops.firemud.entitymanagement.v1
.ReadPreseededActorRuntimeReferenceResponse>
response) {
- if (!isPeer(caller)
- || !incoming.getExpectedTarget().equals(wireTarget)
- || !incoming.getAssignmentUuid().equals(assignment.toString())
- || !incoming.getCanonicalAccountUuid().equals(identity.accountId().toString())
- || !incoming.getCharacterUuid().equals(identity.characterId().toString())
- || !incoming.getIntentDigest().equals(request.getAssignmentIntentDigest())) {
+ var controlled =
+ bindings.stream()
+ .filter(item -> item.matchesEntityRequest(incoming))
+ .findFirst()
+ .orElse(null);
+ if (!isPeer(caller) || controlled == null) {
response.onError(io.grpc.Status.PERMISSION_DENIED.asRuntimeException());
return;
}
@@ -585,13 +606,14 @@ public void readPreseededActorRuntimeReference(
net.firedevops.firemud.entitymanagement.v1
.ReadPreseededActorRuntimeReferenceResponse.newBuilder()
.setSchemaVersion(1)
- .setExpectedTarget(wireTarget)
+ .setExpectedTarget(controlled.wireTarget())
.setAssignmentUuid(incoming.getAssignmentUuid())
.setCanonicalAccountUuid(incoming.getCanonicalAccountUuid())
.setCharacterUuid(incoming.getCharacterUuid())
.setIntentDigest(incoming.getIntentDigest())
- .setPublishedOwnerProofDigest(target.ownerProofDigest().substring(7))
- .setRuntimeEntityId(7301L)
+ .setPublishedOwnerProofDigest(
+ controlled.decision().targetEvidence().ownerProofDigest().substring(7))
+ .setRuntimeEntityId(controlled.runtimeEntityId())
.setProjectionGeneration(1L)
.setProjectionFence(1L)
.setCorePayload(
@@ -633,6 +655,159 @@ public void readPreseededActorRuntimeReference(
.CanonicalRegionBootstrapAssignmentResolver(lifecycle));
}
+ net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request(
+ UUID transitionId) {
+ var result = requestsByTransition.get(transitionId);
+ if (result == null) throw new IllegalArgumentException("Unknown controlled transition");
+ return result;
+ }
+
+ private static ControlledBinding controlledBinding(
+ net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision decision,
+ net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence selector,
+ net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget
+ wireTarget,
+ UUID canonicalRegion,
+ net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request
+ lifecycleRequestTemplate,
+ net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence
+ lifecycleEvidenceTemplate,
+ long runtimeEntityId) {
+ var target = decision.targetEvidence();
+ var identity = decision.candidate();
+ UUID placementId = UUID.randomUUID();
+ UUID assignment = UUID.randomUUID();
+ var request =
+ net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest
+ .newBuilder()
+ .setSchemaVersion(1)
+ .setPlacementOperationUuid(placementId.toString())
+ .setExpectedTarget(wireTarget)
+ .setCanonicalAccountUuid(identity.accountId().toString())
+ .setCharacterUuid(identity.characterId().toString())
+ .setAssignmentUuid(assignment.toString())
+ .setAssignmentIntentDigest("b".repeat(64))
+ .setInitialAdmissionHoldUuid(target.holdId().toString())
+ .setInitialAdmissionHoldFence(target.holdFence().toString())
+ .setInitialAdmissionRequestId(target.initialAdmissionRequestId())
+ .setInitialAdmissionRequestDigest(target.initialAdmissionRequestDigest())
+ .setActiveLifecycleEpoch(target.activeWorldEpoch())
+ .setTerminalProofDigest(target.ownerProofDigest())
+ .setCommittedPointerVersion(target.pointerVersion())
+ .setAuditEventId(target.auditEventId())
+ .build();
+ var lifecycleRequest =
+ new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request(
+ lifecycleRequestTemplate.schemaVersion(),
+ net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence
+ .initialLocationReadRequestId(placementId),
+ lifecycleRequestTemplate.targetNamespace(),
+ lifecycleRequestTemplate.canonicalTenantId(),
+ lifecycleRequestTemplate.worldSlug(),
+ lifecycleRequestTemplate.canonicalGameInstanceId(),
+ lifecycleRequestTemplate.playableStateNamespaceId(),
+ lifecycleRequestTemplate.playableStateScope(),
+ lifecycleRequestTemplate.publicProduction(),
+ lifecycleRequestTemplate.controlPlaneRequestId(),
+ lifecycleRequestTemplate.canonicalVersionId(),
+ lifecycleRequestTemplate.expectedDescriptorRequestDigest(),
+ lifecycleRequestTemplate.expectedDescriptorResultDigest(),
+ lifecycleRequestTemplate.expectedReleaseAttestationDigest());
+ var lifecycleEvidence =
+ new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence(
+ lifecycleRequest,
+ lifecycleEvidenceTemplate.launchBinding(),
+ lifecycleEvidenceTemplate.startLocation(),
+ lifecycleEvidenceTemplate.runtimeRoomInstanceId(),
+ lifecycleEvidenceTemplate.lifecycleStatus(),
+ lifecycleEvidenceTemplate.lifecycleEpoch(),
+ lifecycleEvidenceTemplate.rowVersion(),
+ lifecycleEvidenceTemplate.captureId(),
+ lifecycleEvidenceTemplate.graphSha256(),
+ lifecycleEvidenceTemplate.preparationInputDigest(),
+ lifecycleEvidenceTemplate.operationalRegionAssignments());
+ var room = selector.startLocation();
+ var placementResult =
+ net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse
+ .newBuilder()
+ .setSchemaVersion(1)
+ .setPlacementOperationUuid(placementId.toString())
+ .setRequestDigest("sha256:" + "d".repeat(64))
+ .setCanonicalAccountUuid(request.getCanonicalAccountUuid())
+ .setCharacterUuid(request.getCharacterUuid())
+ .setAssignmentUuid(request.getAssignmentUuid())
+ .setAssignmentIntentDigest(request.getAssignmentIntentDigest())
+ .setResultDigest("sha256:" + "f".repeat(64))
+ .setOutcome(
+ net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome
+ .CANONICAL_INITIAL_PLAYER_LOCATION_OUTCOME_APPLIED)
+ .setStartLocation(
+ net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRoom
+ .newBuilder()
+ .setCanonicalTenantUuid(room.tenantId().toString())
+ .setCanonicalVersionUuid(room.versionId().toString())
+ .setRoomTemplateUuid(room.roomTemplateId().toString()))
+ .setPrivateRuntimeRoomKey("1042")
+ .build();
+ var observation =
+ net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse
+ .newBuilder()
+ .setSchemaVersion(1)
+ .setPlacementResult(placementResult)
+ .setExpectedTarget(wireTarget)
+ .setCanonicalRegionInstanceUuid(canonicalRegion.toString())
+ .setOperationalRegionUuid(identity.regionId().toString())
+ .setPrivateWorldInstanceKey(7L)
+ .setObservedRuntimeRoomKey(1042L)
+ .setLifecycle(
+ net.firedevops.firemud.worldmanagement.v1
+ .CanonicalInitialPlayerLocationLifecycleConsequence.newBuilder()
+ .setCanonicalRequestBytes(
+ com.google.protobuf.ByteString.copyFrom(
+ lifecycleRequest.canonicalBytes()))
+ .setLifecycleStatus("ACTIVE")
+ .setLifecycleEpoch(lifecycleEvidence.lifecycleEpoch())
+ .setRowVersion(lifecycleEvidence.rowVersion())
+ .setCaptureUuid(lifecycleEvidence.captureId().toString())
+ .setGraphSha256(lifecycleEvidence.graphSha256())
+ .setPreparationInputDigest(lifecycleEvidence.preparationInputDigest()))
+ .build();
+ return new ControlledBinding(
+ decision,
+ request,
+ lifecycleRequest,
+ lifecycleEvidence,
+ observation,
+ wireTarget,
+ assignment,
+ runtimeEntityId);
+ }
+
+ private record ControlledBinding(
+ net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision decision,
+ net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request,
+ net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request
+ lifecycleRequest,
+ net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence
+ lifecycleEvidence,
+ net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse
+ observation,
+ net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget
+ wireTarget,
+ UUID assignment,
+ long runtimeEntityId) {
+ boolean matchesEntityRequest(
+ net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest
+ incoming) {
+ var identity = decision.candidate();
+ return incoming.getExpectedTarget().equals(wireTarget)
+ && incoming.getAssignmentUuid().equals(assignment.toString())
+ && incoming.getCanonicalAccountUuid().equals(identity.accountId().toString())
+ && incoming.getCharacterUuid().equals(identity.characterId().toString())
+ && incoming.getIntentDigest().equals(request.getAssignmentIntentDigest());
+ }
+ }
+
private static boolean isPeer(String expected) {
var peer = net.firedevops.firemud.common.grpc.GrpcPeerIdentity.current();
return peer != null && expected.equals(peer.uri());
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffHistoricalFinalIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffHistoricalFinalIntegrationTest.java
index 30ac03fdc6..158ee40d77 100644
--- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffHistoricalFinalIntegrationTest.java
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewRegionHandoffHistoricalFinalIntegrationTest.java
@@ -64,6 +64,10 @@ void accountSqlFenceBeforeDelayedFinalCannotEstablishPreIntentCommitOrdering() t
deadline());
assertThat(intent.state().name()).isEqualTo("ACQUISITION_INTENT");
assertThat(barrier.readFinalObservation(intent.operationId())).isEmpty();
+ assertThat(
+ barrier.readHistoricalFinalReceipt(
+ controlledCapacity.request(), controlledCapacity.reservation()))
+ .isEmpty();
assertThat(intent.cohortRows())
.filteredOn(
row ->
@@ -117,6 +121,10 @@ source, template, accountOpen, issuerOpen, controlledCapacity, deadline())) {
.operationId())
.isEqualTo(intent.operationId());
assertThat(barrier.readFinalObservation(intent.operationId())).isEmpty();
+ assertThat(
+ barrier.readHistoricalFinalReceipt(
+ controlledCapacity.request(), controlledCapacity.reservation()))
+ .isEmpty();
}
}
}
@@ -308,6 +316,57 @@ void fenceOwnerRetainsObservedFinalWithoutPromotingFrozenInventory() throws Exce
assertThat(receipt.inventorySnapshotRevision()).isEqualTo(revision);
assertThat(receipt.cohortDigest()).isEqualTo(intent.cohortDigest());
assertThat(receipt.barrierTargetDigest()).isEqualTo(intent.barrierTargetDigest());
+ var historical =
+ recreated
+ .readHistoricalFinalReceipt(
+ controlledCapacity.request(), controlledCapacity.reservation())
+ .orElseThrow();
+ assertThat(historical.accountId()).isEqualTo(accountId);
+ assertThat(historical.tenantId())
+ .isEqualTo(controlledCapacity.request().identity().tenantId());
+ assertThat(historical.operationId()).isEqualTo(intent.operationId());
+ assertThat(historical.observation()).isEqualTo(receipt);
+ assertThat(historical.execution().transitionId()).isEqualTo(fixture.transitionId());
+ assertThat(historical.execution().request().mutationDigest())
+ .isEqualTo(controlledCapacity.request().mutationDigest());
+ assertThat(historical.execution().reservation().reservationId())
+ .isEqualTo(controlledCapacity.reservation().reservationId());
+ assertThat(historical.execution().reservation().reservationFence())
+ .isEqualTo(controlledCapacity.reservation().reservationFence());
+ var wrongReservationFence = controlledCapacity.reservation();
+ var mismatchedFence =
+ new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result(
+ wrongReservationFence.identity(),
+ wrongReservationFence.admissionAttemptId(),
+ wrongReservationFence.capacityRearmFence(),
+ wrongReservationFence.mutationDigest(),
+ wrongReservationFence.reservationId(),
+ wrongReservationFence.reservationFence() + 1,
+ wrongReservationFence.expiresAt(),
+ wrongReservationFence.state(),
+ wrongReservationFence.snapshotIdentity(),
+ wrongReservationFence.evaluationIdentity());
+ assertThat(
+ recreated.readHistoricalFinalReceipt(controlledCapacity.request(), mismatchedFence))
+ .isEmpty();
+ var request = controlledCapacity.request();
+ var wrongAttempt =
+ new net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request(
+ request.identity(),
+ UUID.randomUUID(),
+ request.capacityRearmFence(),
+ request.targetNamespace(),
+ request.context(),
+ request.operation(),
+ request.priorShape(),
+ request.requestedShape(),
+ request.evidence(),
+ request.capacityDelta(),
+ null)
+ .withDigest();
+ assertThat(
+ recreated.readHistoricalFinalReceipt(wrongAttempt, controlledCapacity.reservation()))
+ .isEmpty();
for (String mutation :
java.util.List.of(
"UPDATE game_session_account_fence_final_observation"
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java
index db4e5551c5..ef0eba4cdb 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
@@ -115,6 +115,17 @@ static ExistingBinding installExistingOriginalCandidate(
return new ExistingBinding(owner, installation, acknowledgement);
}
+ /** Installs another retained candidate through the exact existing region grant and owner. */
+ static ExistingBinding installAdditionalOriginalCandidate(
+ ExistingBinding existing,
+ UUID transitionId,
+ CanonicalInitialPlayerLocationRequest worldRequest) {
+ var installation =
+ existing.owner().installForTransition(existing.installation(), transitionId, worldRequest);
+ var acknowledgement = existing.owner().bridge(installation);
+ return new ExistingBinding(existing.owner(), installation, acknowledgement);
+ }
+
record ExistingBinding(
CanonicalGameplayRegionBindingBridgeOwner owner,
CanonicalGameplayRegionLeaseOwner.Installation installation,
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java
index 6ef7623c09..c1b5213c49 100644
--- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java
@@ -303,15 +303,26 @@ final class TransferSqlProof implements AutoCloseable {
final CanonicalGameplayRegionRuntimeStatus prior;
final OriginalNewCapacityExecution execution;
final CanonicalGameplayRegionOwnerCompositionFixture.ExistingBinding region;
+ final net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision
+ otherDecision;
+ final CanonicalGameplayRegionOwnerCompositionFixture.ExistingBinding otherRegion;
+ final CanonicalGameplayBindingInventoryRepository.OriginalNewFinalAdmissionSource
+ otherAdmission;
CanonicalGameplayRegionOwnerTransferRepository transfers;
CanonicalGameplayProtectedIncarnationReceiver receiver;
CanonicalGameplayRegionOwnerTransferCoordinator coordinator;
TransferSqlProof() throws Exception {
+ this(false);
+ }
+
+ TransferSqlProof(boolean withOtherCandidate) throws Exception {
this(
new DefaultExecuteListener(),
TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS,
- TEST_CAPACITY_EVIDENCE_MAXIMUM_BINDING_BYTES);
+ TEST_CAPACITY_EVIDENCE_MAXIMUM_BINDING_BYTES,
+ TEST_CAPACITY_EVIDENCE_MAXIMUM_RECORDS,
+ withOtherCandidate);
}
TransferSqlProof(int maximumRecords, long maximumBindingBytes) throws Exception {
@@ -345,7 +356,24 @@ final class TransferSqlProof implements AutoCloseable {
long maximumBindingBytes,
int maximumRetainedRecords)
throws Exception {
- this(listener, maximumRecords, maximumBindingBytes, maximumRetainedRecords, 256, 1024);
+ this(listener, maximumRecords, maximumBindingBytes, maximumRetainedRecords, false);
+ }
+
+ TransferSqlProof(
+ DefaultExecuteListener listener,
+ int maximumRecords,
+ long maximumBindingBytes,
+ int maximumRetainedRecords,
+ boolean withOtherCandidate)
+ throws Exception {
+ this(
+ listener,
+ maximumRecords,
+ maximumBindingBytes,
+ maximumRetainedRecords,
+ 256,
+ 1024,
+ withOtherCandidate);
}
TransferSqlProof(
@@ -356,6 +384,25 @@ final class TransferSqlProof implements AutoCloseable {
int maximumTransfers,
int maximumItems)
throws Exception {
+ this(
+ listener,
+ maximumRecords,
+ maximumBindingBytes,
+ maximumRetainedRecords,
+ maximumTransfers,
+ maximumItems,
+ false);
+ }
+
+ TransferSqlProof(
+ DefaultExecuteListener listener,
+ int maximumRecords,
+ long maximumBindingBytes,
+ int maximumRetainedRecords,
+ int maximumTransfers,
+ int maximumItems,
+ boolean withOtherCandidate)
+ throws Exception {
String password = UUID.randomUUID().toString();
try (var administrator =
RedisClient.create(
@@ -460,17 +507,34 @@ public void resultEnd(ExecuteContext context) {
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();
+ .CanonicalGameplayRegionLeaseRedisScriptContribution(),
+ new net.firedevops.firemud.gamesession.service
+ .CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution(),
+ new net.firedevops.firemud.gamesession.service
+ .CanonicalGameplayCapacityOriginCustodyRedisScriptContribution(),
+ new net.firedevops.firemud.gamesession.service
+ .CanonicalGameplayOriginalNewOriginFinalAdmissionRedisScriptContribution()));
+ var decision = fixture.originalPreparedDecisionWithControlledAccountLease(withOtherCandidate);
var inventory = new CanonicalGameplayBindingInventoryRepository(sql);
CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create(redis, scripts, inventory, tags)
.installOnce(decision);
fixture.acknowledgeOriginalIssuer();
new CanonicalGameplayAccountMemberRepairOwner(sql, redis, scripts)
.repair(fixture.transitionId());
+
+ String otherSeed = "two-origin-transfer";
+ if (withOtherCandidate) {
+ fixture.prepareOtherControllerNew(otherSeed);
+ otherDecision = fixture.otherControllerDecision(otherSeed, true);
+ } else {
+ otherDecision = null;
+ }
+ upstream =
+ withOtherCandidate
+ ? new CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources(
+ sql, decision, otherDecision, directory)
+ : new CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources(
+ sql, decision, directory);
region =
CanonicalGameplayRegionOwnerCompositionFixture.installExistingOriginalCandidate(
sql,
@@ -480,6 +544,24 @@ public void resultEnd(ExecuteContext context) {
upstream.request,
upstream.resolver,
upstream.entity);
+ if (withOtherCandidate) {
+ fixture.projectOtherControllerNew(otherSeed);
+ CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create(
+ redis, scripts, inventory, tags)
+ .installOnce(otherDecision);
+ fixture.acknowledgeOtherControllerNew(otherSeed);
+ new CanonicalGameplayAccountMemberRepairOwner(sql, redis, scripts)
+ .repair(otherDecision.bindingDecisionId());
+ otherRegion =
+ CanonicalGameplayRegionOwnerCompositionFixture.installAdditionalOriginalCandidate(
+ region,
+ otherDecision.bindingDecisionId(),
+ upstream.request(otherDecision.bindingDecisionId()));
+ otherAdmission = inventory.readOriginalNewFinalAdmissionSource(otherDecision);
+ } else {
+ otherRegion = null;
+ otherAdmission = null;
+ }
admission = inventory.readOriginalNewFinalAdmissionSource(decision);
scope = region.installation().source;
prior = new CanonicalGameplayRegionRuntimeStatusRepository(sql).find(scope).orElseThrow();
@@ -509,6 +591,37 @@ void replayBridge() {
assertThat(replayed.obligation()).isEqualTo(region.acknowledgement().obligation());
}
+ void freezeWithCommittedOriginExecution(CanonicalGameplayCapacityOrigin origin)
+ throws Exception {
+ try (var credential =
+ new CanonicalGameplayOriginalNewFinalAdmissionTestFixture(
+ admission.candidate(), clock);
+ var raw = credential.template();
+ var template = raw.bindCapacityExecution(execution)) {
+ var account = controlledAccountOpen();
+ var issuer = issuerOpen();
+ capacity(sql)
+ .authorizeWithOrigin(
+ admission, template, account, issuer, execution, transferDeadline(), origin);
+ var custody = new CanonicalGameplayCapacityOriginRepository(sql).read(origin);
+ var finalOwner =
+ new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner(redis, scripts, clock, tags)
+ .forOrigin(origin, custody);
+ try (var finalReadback =
+ finalOwner.finalizeOriginalNewOnce(
+ admission, template, account, issuer, execution, transferDeadline())) {
+ UUID id = begin();
+ var captured = transfers.within(transferDeadline(), ignored -> transfers.capture(id));
+ assertThat(captured)
+ .extracting(item -> item.execution().digest())
+ .containsExactly(execution.digest());
+ new CanonicalGameplayBindingInventoryRepository(sql)
+ .commitOriginalNewFinalAdmission(finalReadback);
+ }
+ assertThat(executionState(execution)).isEqualTo("COMMITTED");
+ }
+ }
+
OriginalNewCapacityExecution newControlledExecution() {
var controlled =
CanonicalGameplayOriginalNewFinalAdmissionTestFixture.controlledCapacity(
@@ -740,6 +853,21 @@ CanonicalGameplayRegionRuntimeStatus install(UUID id) {
transferDeadline());
}
+ CanonicalGameplayRegionRuntimeStatus installCalibrationTransfer(
+ CanonicalGameplayRegionOwnerTransferCoordinator transfer,
+ UUID transferId,
+ CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant,
+ long deadline) {
+ return transfer.install(
+ transferId,
+ scope,
+ prior,
+ grant.tokenCorrelation(),
+ grant.ownerService(),
+ grant.ownerInstanceId(),
+ deadline);
+ }
+
CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback issuerOpen() {
var repository =
new CanonicalGameplayIssuerAdmissionBarrierRepository(
@@ -825,34 +953,37 @@ boolean physicalExecutionExists(OriginalNewCapacityExecution original) {
boolean physicalExecutionExists(OriginalNewCapacityExecution original, String tag) {
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(physicalExecutionKey(original, tag)) != 0;
+ }
+ }
+
+ String physicalExecutionState(OriginalNewCapacityExecution original) {
+ try (var connection = redis.connect(ByteArrayCodec.INSTANCE)) {
+ return new String(
+ connection.sync().hget(physicalExecutionKey(original), ascii("state")),
+ StandardCharsets.US_ASCII);
}
}
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);
+ assertThat(connection.sync().del(physicalExecutionKey(original))).isEqualTo(1L);
}
}
+ byte[] physicalExecutionKey(OriginalNewCapacityExecution original) {
+ String tag = tags.assignmentForTransition(original.transitionId()).tenantGameplayTag();
+ return physicalExecutionKey(original, tag);
+ }
+
+ byte[] physicalExecutionKey(OriginalNewCapacityExecution original, String tag) {
+ return ascii(
+ "session:game:capacity-execution:{"
+ + tag
+ + "}:"
+ + original.request().admissionAttemptId());
+ }
+
void rawReplaceOwner(String owner, String correlation) {
rawReplaceOwner(sql, owner, correlation);
}
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java
index cda3f34a47..8c6b868719 100644
--- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferCapacityCustodyIntegrationTest.java
@@ -614,14 +614,58 @@ void capturedOriginalThatBecomesTerminalStillRequiresQualifiedTransferCompletion
proof.transfers.within(
transferDeadline(), ignored -> proof.transfers.finishVerification(id));
assertThat(verified).isTrue();
- assertThat(
- proof
- .rawCompleteAndInstall(id, "sql-proof-successor", "e".repeat(64))
- .ownerInstanceId())
- .isEqualTo("sql-proof-successor");
+ var installed = proof.install(id);
+ assertThat(installed.ownerInstanceId()).isEqualTo("sql-proof-successor");
assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED");
- assertThat(proof.transfers.readCurrent(id, captured.getFirst().ordinal()).controlState())
+ var item = captured.getFirst();
+ assertThat(proof.transfers.readCurrent(id, item.ordinal()).controlState())
.isEqualTo("COMPLETED");
+ String completed = proof.transferImage(id);
+ String receipt = proof.itemImage(id);
+ String original = proof.originalImage();
+ for (String lifecycle : List.of("TERMINAL_UNRESOLVED", "TERMINAL")) {
+ // Model only the inventory state left by a future admitted teardown owner.
+ assertThat(
+ proof.sql.execute(
+ "UPDATE game_session_canonical_gameplay_binding_inventory"
+ + " SET lifecycle=? WHERE transition_id=?",
+ lifecycle,
+ proof.execution.transitionId()))
+ .isEqualTo(1);
+ assertThatThrownBy(
+ () -> proof.tags.assignmentForTransition(proof.execution.transitionId()))
+ .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class);
+ 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);
+ String tag = item.assignment().tenantGameplayTag();
+ try (var connection = proof.redis.connect(ByteArrayCodec.INSTANCE)) {
+ assertThat(connection.sync().del(proof.physicalExecutionKey(proof.execution, tag)))
+ .isEqualTo(1L);
+ }
+ assertThatThrownBy(
+ () ->
+ proof.coordinator.recoverCompleted(
+ id,
+ installed.ownerInstanceId(),
+ installed.leaseTokenCorrelation(),
+ transferDeadline()))
+ .isInstanceOf(IllegalStateException.class);
+ assertThat(proof.physicalExecutionExists(proof.execution, tag)).isFalse();
+ assertThat(proof.currentOwner()).isEqualTo(installed);
+ assertThat(proof.transferImage(id)).isEqualTo(completed);
+ assertThat(proof.itemImage(id)).isEqualTo(receipt);
+ assertThat(proof.originalImage()).isEqualTo(original);
}
}
}
diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java
new file mode 100644
index 0000000000..cb1b76a32a
--- /dev/null
+++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java
@@ -0,0 +1,483 @@
+package net.firedevops.firemud.gamesession.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import io.lettuce.core.codec.ByteArrayCodec;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution;
+import net.firedevops.firemud.common.runtime.RuntimeIdentity;
+import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus;
+import net.firedevops.firemud.test.TestContainerImages;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+@Testcontainers(disabledWithoutDocker = true)
+@SuppressWarnings("resource")
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class CanonicalGameplayRegionTransferMixedInventoryIntegrationTest
+ extends CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport {
+ @Container
+ static final PostgreSQLContainer> POSTGRES =
+ new PostgreSQLContainer<>(TestContainerImages.postgres());
+
+ @Container
+ static final GenericContainer> REDIS =
+ new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379);
+
+ @Override
+ PostgreSQLContainer> postgresContainer() {
+ return POSTGRES;
+ }
+
+ @Override
+ GenericContainer> redisContainer() {
+ return REDIS;
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void calibratesMixedRetainedExecutionHandoffAndRefusesLastMarkerLoss(boolean loseLastMarker)
+ throws Exception {
+ calibrateMixedRetainedExecutionHandoff(loseLastMarker, 3);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void transfersTwoIndependentOriginsWithOptionalCapturedExecution(boolean captureExecution)
+ throws Exception {
+ try (var proof = new TransferSqlProof(true)) {
+ var otherDecision = proof.otherDecision;
+ assertThat(otherDecision.bindingDecisionId()).isNotEqualTo(proof.execution.transitionId());
+ assertThat(otherDecision.candidate().characterId())
+ .isNotEqualTo(proof.admission.candidate().bindingIdentity().characterId());
+ assertThat(otherDecision.candidate().sessionId())
+ .isNotEqualTo(proof.admission.candidate().bindingIdentity().sessionId());
+ var otherRegion = proof.otherRegion;
+ assertThat(
+ CanonicalGameplayRegionRuntimeStatusRepository.sameRegionSource(
+ otherRegion.installation().source, proof.scope))
+ .isTrue();
+ assertThat(otherRegion.installation().source.lifecycleRequest().readRequestId())
+ .isNotEqualTo(proof.scope.lifecycleRequest().readRequestId());
+ assertThat(otherRegion.installation().grant.tokenCorrelation())
+ .isEqualTo(proof.region.installation().grant.tokenCorrelation());
+ assertThat(otherRegion.installation().status.executorFence())
+ .isEqualTo(proof.prior.executorFence());
+
+ var otherAdmission = proof.otherAdmission;
+ var otherCapacity =
+ CanonicalGameplayOriginalNewFinalAdmissionTestFixture.controlledCapacity(
+ otherAdmission, proof.clock);
+ var firstOrigin =
+ proof
+ .capacity(proof.sql)
+ .prepareOrigin(proof.admission, proof.execution.request(), transferDeadline());
+ var secondOrigin =
+ proof
+ .capacity(proof.sql)
+ .prepareOrigin(otherAdmission, otherCapacity.request(), transferDeadline());
+ assertThat(firstOrigin.transitionId()).isNotEqualTo(secondOrigin.transitionId());
+ assertThat(firstOrigin.digest()).isNotEqualTo(secondOrigin.digest());
+ assertThat(firstOrigin.candidateDigest()).isNotEqualTo(secondOrigin.candidateDigest());
+ assertThat(firstOrigin.candidate().bindingIdentity().tenantId())
+ .isEqualTo(secondOrigin.candidate().bindingIdentity().tenantId());
+ assertThat(firstOrigin.candidate().bindingIdentity().gameInstanceId())
+ .isEqualTo(secondOrigin.candidate().bindingIdentity().gameInstanceId());
+ assertThat(firstOrigin.candidate().bindingIdentity().regionId())
+ .isEqualTo(secondOrigin.candidate().bindingIdentity().regionId());
+ assertThat(
+ proof
+ .sql
+ .fetchSingle("SELECT count(*) FROM game_session_original_new_capacity_origin")
+ .get(0, Long.class))
+ .isEqualTo(2L);
+ if (captureExecution) proof.freezeWithCommittedOriginExecution(firstOrigin);
+ var observationLatency = Duration.ofMillis(5);
+ var regionAttestor =
+ new CanonicalGameplayControlledRegionTransferObservationFixture(
+ proof.clock, Duration.ofSeconds(30), observationLatency);
+ var originAttestor =
+ new CanonicalGameplayControlledOriginTransferObservationFixture(
+ proof.clock, observationLatency);
+ var originTransfers = new CanonicalGameplayCapacityOriginTransferRepository(proof.transfers);
+ var transfer =
+ new CanonicalGameplayRegionOwnerTransferCoordinator(
+ proof.sql,
+ proof.clock,
+ proof.transfers,
+ proof.capacity(proof.sql),
+ regionAttestor.receiver(proof.transfers, proof.tags),
+ originAttestor.receiver(originTransfers, proof.tags));
+
+ try (var connection = proof.redis.connect(ByteArrayCodec.INSTANCE)) {
+ assertThat(connection.sync().pexpire(ascii(proof.region.installation().grant.key()), 0L))
+ .isTrue();
+ }
+ long deadline = transferDeadline();
+ long start = System.nanoTime();
+ var installed =
+ CanonicalGameplayRegionOwnerCompositionFixture.handoffExistingOriginal(
+ proof.sql,
+ proof.redis,
+ proof.coordinationUri,
+ proof.scripts,
+ proof.region.installation(),
+ proof.upstream.resolver,
+ transfer,
+ deadline);
+ Duration elapsed = Duration.ofNanos(System.nanoTime() - start);
+ int observationCount = regionAttestor.observationCount() + originAttestor.observationCount();
+ int signedOriginObservationCount = originAttestor.observationCount();
+ if (captureExecution) {
+ assertThat(regionAttestor.observationCount()).isPositive();
+ } else {
+ assertThat(regionAttestor.observationCount()).isZero();
+ }
+ assertThat(signedOriginObservationCount).isPositive();
+ assertThat(elapsed).isGreaterThanOrEqualTo(observationLatency.multipliedBy(observationCount));
+ assertThat(elapsed).isLessThan(Duration.ofSeconds(5));
+ LOGGER.info(
+ "Two-origin transfer (captured execution={}) completed in {} ms with {} signed origin"
+ + " observations and {} total signed observations",
+ captureExecution,
+ elapsed.toMillis(),
+ signedOriginObservationCount,
+ observationCount);
+ assertThat(proof.clock.millis()).isLessThan(deadline);
+ assertThat(installed.status.executorFence()).isGreaterThan(proof.prior.executorFence());
+ assertThat(proof.currentOwner()).isEqualTo(installed.status);
+
+ UUID transferId =
+ proof
+ .sql
+ .fetchSingle(
+ "SELECT transfer_id FROM game_session_region_owner_transfer WHERE tenant_id=? AND"
+ + " game_instance_id=? AND region_id=? AND state='COMPLETED'",
+ proof.scope.tenantId(),
+ proof.scope.gameInstanceId(),
+ proof.scope.regionId())
+ .get(0, UUID.class);
+ var transferRows =
+ proof.sql.fetch(
+ "SELECT origin_digest,captured_state,fence_readback,incarnation_digest,verified_round"
+ + " FROM game_session_capacity_origin_transfer_item WHERE transfer_id=?",
+ transferId);
+ assertThat(transferRows).hasSize(2);
+ assertThat(transferRows.getValues("origin_digest", String.class))
+ .containsExactlyInAnyOrder(firstOrigin.digest(), secondOrigin.digest());
+ assertThat(transferRows.getValues("captured_state", String.class))
+ .containsExactlyInAnyOrder(captureExecution ? "DISPATCH_CLAIMED" : "OPEN", "OPEN");
+ assertThat(transferRows.getValues("fence_readback", byte[].class))
+ .allSatisfy(value -> assertThat(value).isNotNull().isNotEmpty());
+ assertThat(transferRows.getValues("incarnation_digest", String.class))
+ .allSatisfy(value -> assertThat(value).isNotNull());
+ assertThat(transferRows.getValues("verified_round", UUID.class))
+ .allSatisfy(value -> assertThat(value).isNotNull());
+
+ var retainedOrigins =
+ proof.sql.fetch(
+ "SELECT * FROM game_session_original_new_capacity_origin ORDER BY origin_digest");
+ assertThat(retainedOrigins).hasSize(2);
+ assertThat(retainedOrigins.getValues("custody_owner_id", String.class))
+ .containsOnly(installed.status.ownerInstanceId());
+ assertThat(retainedOrigins.getValues("custody_owner_fence", Long.class))
+ .containsOnly(installed.status.executorFence().longValueExact());
+ assertThat(retainedOrigins.getValues("custody_transfer_id", UUID.class))
+ .containsOnly(transferId);
+ if (captureExecution) {
+ assertThat(proof.transfers.readCurrent(transferId, 0).controlState())
+ .isEqualTo("COMPLETED");
+ assertThat(proof.physicalExecutionState(proof.execution)).isEqualTo("COMMITTED");
+ }
+ try (var connection = proof.redis.connect(ByteArrayCodec.INSTANCE)) {
+ for (var row : retainedOrigins) {
+ var origin = CanonicalGameplayCapacityOriginTransferRepository.decodeOrigin(row);
+ Map fields = new java.util.HashMap<>();
+ connection
+ .sync()
+ .hgetall(ascii(origin.redisKey()))
+ .forEach(
+ (key, value) ->
+ fields.put(
+ new String(key, StandardCharsets.US_ASCII),
+ new String(value, StandardCharsets.US_ASCII)));
+ assertThat(fields)
+ .containsExactlyInAnyOrderEntriesOf(
+ Map.of(
+ "origin", origin.digest(),
+ "owner", installed.status.ownerInstanceId(),
+ "fence", installed.status.executorFence().toString(),
+ "state", row.get("state", String.class)));
+ assertThat(connection.sync().pttl(ascii(origin.redisKey()))).isEqualTo(-1L);
+ }
+ }
+ }
+ }
+
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.class);
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void qualifiesMixedRetainedInventoryAcrossThreePages(boolean loseLastMarker) throws Exception {
+ calibrateMixedRetainedExecutionHandoff(
+ loseLastMarker, 2 * CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE + 1);
+ }
+
+ private void calibrateMixedRetainedExecutionHandoff(boolean loseLastMarker, int cohortSize)
+ 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());
+ // Only the real authorization above can FINAL. The extra envelopes deliberately reuse the
+ // fixture's original transition and model SQL dispatches that never reached Redis.
+ List undelivered = new ArrayList<>();
+ for (int index = 1; index < cohortSize; index++) {
+ undelivered.add(proof.newControlledExecution());
+ }
+ undelivered.forEach(proof::seedUndeliveredDispatch);
+ UUID transferId;
+ List captured;
+ try (var finalReadback =
+ new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner(
+ proof.redis, proof.scripts, proof.clock, proof.tags)
+ .finalizeOriginalNewOnce(
+ proof.admission,
+ template,
+ account,
+ issuer,
+ proof.execution,
+ transferDeadline())) {
+ transferId = proof.begin();
+ int pages =
+ (cohortSize + CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE - 1)
+ / CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE;
+ for (int page = 0; page < pages; page++) {
+ proof.transfers.within(
+ transferDeadline(), ignored -> proof.transfers.capture(transferId));
+ }
+ captured = new ArrayList<>();
+ long cursor = -1;
+ for (int page = 0; page < pages; page++) {
+ long after = cursor;
+ var items =
+ proof.transfers.within(
+ transferDeadline(), ignored -> proof.transfers.page(transferId, after));
+ assertThat(items)
+ .hasSize(
+ Math.min(
+ CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE,
+ cohortSize - captured.size()));
+ captured.addAll(items);
+ cursor = items.getLast().ordinal();
+ }
+ List expectedDigests = new ArrayList<>();
+ expectedDigests.add(proof.execution.digest());
+ expectedDigests.addAll(
+ undelivered.stream().map(OriginalNewCapacityExecution::digest).toList());
+ assertThat(captured)
+ .extracting(item -> item.execution().digest())
+ .containsExactlyInAnyOrderElementsOf(expectedDigests);
+ new CanonicalGameplayBindingInventoryRepository(proof.sql)
+ .commitOriginalNewFinalAdmission(finalReadback);
+ }
+ assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED");
+ String originalReceipts = proof.originalImage();
+
+ var observationLatency = Duration.ofMillis(5);
+ var attestor =
+ new CanonicalGameplayControlledRegionTransferObservationFixture(
+ proof.clock, Duration.ofSeconds(30), observationLatency);
+ var transfer =
+ new CanonicalGameplayRegionOwnerTransferCoordinator(
+ proof.sql,
+ proof.clock,
+ proof.transfers,
+ proof.capacity(proof.sql),
+ attestor.receiver(proof.transfers, proof.tags));
+ var identity =
+ new RuntimeIdentity(
+ "game-session-service",
+ "mixed-transfer-calibration",
+ "localhost",
+ proof.clock.instant(),
+ "test",
+ "test",
+ "controlled-test-image");
+ var original = proof.region.installation();
+ try (var connection = proof.redis.connect(ByteArrayCodec.INSTANCE)) {
+ assertThat(connection.sync().pexpire(ascii(original.grant.key()), 0L)).isTrue();
+ }
+ var leases = new CanonicalGameplayRegionLeaseRedisOwner(proof.redis, proof.scripts);
+ long initialDeadline = transferDeadline();
+ long start = System.nanoTime();
+ var grant =
+ leases.acquire(proof.scope, proof.prior.regionEpoch(), Duration.ofSeconds(30), identity);
+ leases.requireGrantScope(grant, proof.scope, proof.prior.regionEpoch(), identity);
+ leases.verifyInitializedTimeline(grant, original.preparation);
+ leases.requireCurrent(grant);
+ int pages =
+ (cohortSize + CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE - 1)
+ / CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE;
+ // Bounded calls can stop while fencing or verifying a page. Retry the same transfer
+ // and prove the predecessor and exact terminal receipts stay intact until it qualifies.
+ UUID verified = null;
+ for (int attempt = 0; attempt < 4 * pages && verified == null; attempt++) {
+ try {
+ verified =
+ transfer.advance(
+ proof.scope, proof.prior, cohortSize == 3 ? initialDeadline : transferDeadline());
+ } catch (CanonicalGameplayOriginalNewCapacityExecutionBudget.BudgetUnavailable expired) {
+ if (cohortSize == 3) throw expired;
+ } catch (IllegalStateException held) {
+ if (cohortSize == 3
+ || !List.of(
+ "Normal region handoff requires complete current transfer evidence",
+ "Normal region owner transfer is held")
+ .contains(held.getMessage())) throw held;
+ }
+ assertThat(proof.currentOwner()).isEqualTo(proof.prior);
+ assertThat(proof.originalImage()).isEqualTo(originalReceipts);
+ }
+ assertThat(verified).isEqualTo(transferId);
+
+ int advanceObservations = attestor.observationCount();
+ for (var execution : undelivered) {
+ assertThat(proof.physicalExecutionState(execution)).isEqualTo("FENCED_INDETERMINATE");
+ }
+ assertThat(proof.physicalExecutionState(proof.execution)).isEqualTo("COMMITTED");
+ String retainedItems = proof.itemImage(transferId);
+ var last = captured.getLast();
+ assertThat(last.ordinal()).isEqualTo(cohortSize - 1L);
+ if (loseLastMarker) proof.losePhysicalExecution(last.execution());
+
+ leases.requireCurrent(grant);
+ long deadline = cohortSize == 3 ? initialDeadline : transferDeadline();
+ long installStart = System.nanoTime();
+ CanonicalGameplayRegionRuntimeStatus installed = null;
+ if (loseLastMarker) {
+ assertThatThrownBy(
+ () -> proof.installCalibrationTransfer(transfer, transferId, grant, deadline))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Original NEW capacity execution is indeterminate");
+ } else {
+ installed = proof.installCalibrationTransfer(transfer, transferId, grant, deadline);
+ }
+ long finish = System.nanoTime();
+ long finishedAt = proof.clock.millis();
+ var installElapsed = Duration.ofNanos(finish - installStart);
+ var totalElapsed = Duration.ofNanos(finish - start);
+ int installObservations = attestor.observationCount() - advanceObservations;
+ LOGGER.info(
+ "Mixed retained handoff calibration: items={}, lastMarkerLost={},"
+ + " controlledObservationLatencyMs={}, advanceObservations={}, installObservations={},"
+ + " installElapsedMs={}, totalElapsedMs={}",
+ captured.size(),
+ loseLastMarker,
+ observationLatency.toMillis(),
+ advanceObservations,
+ installObservations,
+ installElapsed.toMillis(),
+ totalElapsed.toMillis());
+ assertThat(advanceObservations).isPositive();
+ assertThat(installObservations).isPositive();
+ assertThat(installElapsed)
+ .isGreaterThanOrEqualTo(observationLatency.multipliedBy(installObservations));
+ assertThat(finishedAt).isLessThan(deadline);
+ leases.requireCurrent(grant);
+ assertThat(proof.itemImage(transferId)).isEqualTo(retainedItems);
+ assertThat(proof.originalImage()).isEqualTo(originalReceipts);
+ if (loseLastMarker) {
+ assertThat(proof.currentOwner()).isEqualTo(proof.prior);
+ assertThat(proof.transfers.readCurrent(transferId, last.ordinal()).controlState())
+ .isEqualTo("FROZEN");
+ assertThat(proof.physicalExecutionExists(last.execution())).isFalse();
+ assertThatThrownBy(
+ () ->
+ proof.installCalibrationTransfer(
+ transfer, transferId, grant, transferDeadline()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Original NEW capacity execution is indeterminate");
+ assertThat(proof.currentOwner()).isEqualTo(proof.prior);
+ assertThat(proof.itemImage(transferId)).isEqualTo(retainedItems);
+ assertThat(proof.physicalExecutionExists(last.execution())).isFalse();
+ } else {
+ assertThat(installed).isNotNull();
+ assertThat(installed.ownerInstanceId()).isEqualTo(identity.serviceInstanceId());
+ assertThat(installed.leaseTokenCorrelation()).isEqualTo(grant.tokenCorrelation());
+ assertThat(installed.executorFence()).isGreaterThan(proof.prior.executorFence());
+ assertThat(proof.currentOwner()).isEqualTo(installed);
+ assertThat(proof.transfers.readCurrent(transferId, last.ordinal()).controlState())
+ .isEqualTo("COMPLETED");
+ }
+ }
+ }
+
+ @Test
+ void refusesExecutionBeyondActualConfiguredEvidenceBoundWithoutChangingRetainedCustody()
+ throws Exception {
+ try (var proof = new TransferSqlProof()) {
+ var limits =
+ proof.sql.fetchSingle(
+ "SELECT maximum_records, maximum_binding_bytes, maximum_retained_records"
+ + " FROM game_session_capacity_evidence_budget WHERE tenant_id=?",
+ proof.admission.candidate().bindingIdentity().tenantId());
+ int bound =
+ (int)
+ Math.min(
+ limits.get("maximum_records", Integer.class),
+ limits.get("maximum_binding_bytes", Long.class) / 1_048_576L);
+ assertThat(bound).isGreaterThan(CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE);
+ proof.seedUndeliveredDispatch(proof.execution);
+ for (int index = 1; index < bound; index++) {
+ proof.seedUndeliveredDispatch(proof.newControlledExecution());
+ }
+ String originalReceipts = proof.originalImage();
+ var overflow = proof.newControlledExecution();
+ assertThatThrownBy(() -> proof.seedUndeliveredDispatch(overflow))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Original NEW capacity evidence budget is unavailable");
+ assertThat(proof.executionState(overflow)).isNull();
+ assertThat(proof.physicalExecutionExists(overflow)).isFalse();
+ assertThat(proof.originalImage()).isEqualTo(originalReceipts);
+ assertThat(proof.currentOwner()).isEqualTo(proof.prior);
+ assertThat(
+ proof
+ .sql
+ .fetchSingle(
+ "SELECT count(*) FROM game_session_capacity_evidence_charge WHERE tenant_id=?",
+ proof.admission.candidate().bindingIdentity().tenantId())
+ .get(0, Long.class))
+ .isEqualTo((long) bound);
+ assertThat(
+ proof.sql.fetchSingle(
+ "SELECT maximum_records, maximum_binding_bytes, maximum_retained_records"
+ + " FROM game_session_capacity_evidence_budget WHERE tenant_id=?",
+ proof.admission.candidate().bindingIdentity().tenantId()))
+ .isEqualTo(limits);
+ }
+ }
+}
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 47016ca666..c16a5b38cd 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
@@ -97,7 +97,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB
Map before = f.rows(f.tables());
var evidence = f.owner().capture(request());
var catalog = evidence.catalog();
- assertThat(catalog.catalogEpoch()).isEqualTo(21);
+ assertThat(catalog.catalogEpoch()).isEqualTo(23);
assertThat(
catalog.schemaFacts().stream()
.filter(fact -> fact.kind() == FactKind.TABLE)
@@ -163,7 +163,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB
"game_session_canonical_binding_transition.admission_request_id",
"game_session_canonical_realm_catalog.private_preparation_request_id",
"game_session_private_catalog_revision_history",
- "game_session_current_private_catalog_revisions")) {
+ "game_session_current_private_catalog_revisions",
+ "game_session_original_new_admitted_logout_intent")) {
assertThat(catalog.families()).anyMatch(family -> family.familyId().equals(name));
}
assertPrivateRevisionClassifications(catalog);
@@ -221,7 +222,9 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB
"catalog-installation:1065.0.9",
"catalog-installation:1065.0.10",
"catalog-installation:1065.1",
- "catalog-installation:1065.2")
+ "catalog-installation:1065.2",
+ "catalog-installation:1066",
+ "catalog-installation:1066.1")
.noneMatch(
identity ->
identity.contains(":1057:")
@@ -244,7 +247,9 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB
|| identity.contains(":1065.0.9:")
|| identity.contains(":1065.0.10:")
|| identity.contains(":1065.1:")
- || identity.contains(":1065.2:"));
+ || identity.contains(":1065.2:")
+ || identity.contains(":1066:")
+ || identity.contains(":1066.1:"));
assertThat(
f.dsl
.fetchSingle(
@@ -787,7 +792,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(21);
+ assertThat(original.catalog().catalogEpoch()).isEqualTo(23);
assertThat(original.catalog().schemaFacts())
.anyMatch(
fact ->
@@ -943,7 +948,9 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks(
"1065.0.9",
"1065.0.10",
"1065.1",
- "1065.2")) {
+ "1065.2",
+ "1066",
+ "1066.1")) {
for (String change :
List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) {
try (Fixture f = fixture(null)) {
@@ -966,7 +973,7 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks(
"INSERT INTO "
+ f.history
+ "(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)"
- + " VALUES(10000,'1066','controlled later migration','SQL','V1066__probe.sql',1,current_user,0,true)");
+ + " VALUES(10000,'1067','controlled later migration','SQL','V1067__probe.sql',1,current_user,0,true)");
assertThatThrownBy(() -> f.owner().readExact(original.request()))
.isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class);
}
@@ -992,7 +999,9 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks(
"1065.0.9",
"1065.0.10",
"1065.1",
- "1065.2")) {
+ "1065.2",
+ "1066",
+ "1066.1")) {
try (Fixture f = fixture(null)) {
f.dsl.execute(
"INSERT INTO "
@@ -1765,6 +1774,90 @@ void originCustodyUpgradeSealsNewFamiliesWithoutInventingPriorOriginEvidence() {
}
}
+ @Test
+ void admittedLogoutUpgradeRetainsPriorCatalogAndSealsTheNewIntentFamily() {
+ try (Fixture f = fixture("1065.2")) {
+ f.populatePredecessor();
+ var original = f.owner().capture(request());
+ assertThat(original.catalog().catalogEpoch()).isEqualTo(21);
+ var before = f.rows(f.tables());
+ before.remove(f.history);
+ before.remove(CLASSIFICATIONS);
+ before.remove(EPOCHS);
+ var history = f.historyRows(false);
+ var classifications = f.classificationRows();
+ String priorEpochs =
+ "SELECT to_jsonb(e)::text||':'||xmin::text FROM "
+ + EPOCHS
+ + " e WHERE catalog_epoch<=21 ORDER BY catalog_epoch";
+ var epochs = f.dsl.fetch(priorEpochs).getValues(0, String.class);
+
+ migration(f.source, f.schema, f.history, "1066").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.classificationRows())
+ .containsAllEntriesOf(classifications)
+ .hasSize(classifications.size() + 1);
+ assertThat(f.dsl.fetch(priorEpochs).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(22);
+ assertThat(current.catalog().families())
+ .anyMatch(
+ item -> item.familyId().equals("game_session_original_new_admitted_logout_intent"));
+ assertThat(f.count("game_session_original_new_admitted_logout_intent")).isZero();
+ assertThat(f.owner().readExact(current.request())).isEqualTo(current);
+ migration(f.source, f.schema, f.history, "1066").validate();
+ }
+ }
+
+ @Test
+ void transferredOriginRecoveryUpgradeRetainsPopulatedCatalogAndSealsIssuingFence() {
+ try (Fixture f = fixture("1066")) {
+ f.populatePredecessor();
+ var original = f.owner().capture(request());
+ assertThat(original.catalog().catalogEpoch()).isEqualTo(22);
+ var before = f.rows(f.tables());
+ before.remove(f.history);
+ before.remove(EPOCHS);
+ var history = f.historyRows(false);
+ String priorEpochs =
+ "SELECT to_jsonb(e)::text||':'||xmin::text FROM "
+ + EPOCHS
+ + " e WHERE catalog_epoch<=22 ORDER BY catalog_epoch";
+ var epochs = f.dsl.fetch(priorEpochs).getValues(0, String.class);
+
+ migration(f.source, f.schema, f.history, "1066.1").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(priorEpochs).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(23);
+ assertThat(current.catalog().schemaFacts())
+ .anyMatch(
+ fact ->
+ fact.kind() == FactKind.COLUMN
+ && fact.identity()
+ .equals(
+ "game_session_original_new_capacity_origin.last_observation_custody_fence"));
+ assertThat(f.owner().readExact(current.request())).isEqualTo(current);
+ migration(f.source, f.schema, f.history, "1066.1").validate();
+ }
+ }
+
@Test
void historicalFinalObservationUpgradePreservesPopulatedV1065Point1AndSealsEpoch18() {
try (Fixture f = fixture("1065.1")) {
diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepositoryTest.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepositoryTest.java
index c5bdaee886..7368b0813e 100644
--- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepositoryTest.java
+++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepositoryTest.java
@@ -8,6 +8,7 @@
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
+import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest;
import org.junit.jupiter.api.Test;
/** Pure source contracts only. Controlled objects do not prove SQL/Redis custody or a handoff. */
@@ -197,16 +198,11 @@ void requestDecoderRefusesMissingAndNoncanonicalFrames() {
new byte[0],
"mutationDigest/v1".getBytes(StandardCharsets.US_ASCII),
"0:trailing".getBytes(StandardCharsets.US_ASCII))) {
- assertThatThrownBy(
- () ->
- CanonicalGameplayRegionOwnerTransferRepository.decodeRequest(
- bytes, "a".repeat(64)))
- .isInstanceOf(IllegalStateException.class);
+ assertThatThrownBy(() -> CapacityAdmissionDigest.decodeCommittable(bytes, "a".repeat(64)))
+ .isInstanceOf(IllegalArgumentException.class);
}
- assertThatThrownBy(
- () ->
- CanonicalGameplayRegionOwnerTransferRepository.decodeRequest(null, "a".repeat(64)))
- .isInstanceOf(IllegalStateException.class);
+ assertThatThrownBy(() -> CapacityAdmissionDigest.decodeCommittable(null, "a".repeat(64)))
+ .isInstanceOf(IllegalArgumentException.class);
}
private static CanonicalGameplayCapacityOriginTransferRepository.Item item(
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 a0c10d3070..d22eeabaa8 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
@@ -51,6 +51,21 @@ void acceptsOnlyTheExactSameNamespaceAccountMethod() {
invoke(wrongMethod, peer(NAMESPACE, "account-service")), Status.Code.PERMISSION_DENIED);
}
+ @Test
+ void historicalFinalUsesTheSameExactAccountWorkloadBoundary() {
+ var method =
+ OriginalNewCapacityExecutionReadServiceGrpc
+ .getReadHistoricalOriginalNewCapacityFinalMethod();
+ Invocation accepted = invoke(method, peer(NAMESPACE, "account-service"));
+ assertThat(accepted.nextStarts()).isEqualTo(1);
+ assertThat(accepted.status()).isNull();
+ assertDenied(invoke(method, null), Status.Code.UNAUTHENTICATED);
+ assertDenied(
+ invoke(method, peer("other-namespace", "account-service")), Status.Code.PERMISSION_DENIED);
+ assertDenied(
+ invoke(method, peer(NAMESPACE, "world-management-service")), Status.Code.PERMISSION_DENIED);
+ }
+
@Test
void refusesMissingForeignAndPlayerOrSyntheticCallerContexts() {
var method =
diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java
index 49a04ab100..a259f47621 100644
--- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java
+++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java
@@ -133,12 +133,21 @@ void authenticatedAccountInvalidArgumentMapsToSafeBadRequest() {
+ "\"email\":\"owner@example.test\",\"secret\":\""
+ secret
+ "\"}";
+ // Direct Account login trusts only the raw socket peer of the native Reactor Netty request.
+ var socketPeer = new java.net.InetSocketAddress("192.0.2.10", 443);
+ var nativeConnection = mock(reactor.netty.Connection.class);
+ var channel = mock(io.netty.channel.Channel.class);
+ when(nativeConnection.channel()).thenReturn(channel);
+ when(channel.remoteAddress()).thenReturn(socketPeer);
+ var headers = new HttpHeaders();
+ headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
var request =
- MockServerHttpRequest.post("https://localhost/api/account/auth/login")
- .sslInfo(mock(SslInfo.class))
- .remoteAddress(new java.net.InetSocketAddress("192.0.2.10", 443))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
- .body(body);
+ new NativeSocketLoginRequest(
+ URI.create("https://localhost/api/account/auth/login"),
+ headers,
+ socketPeer,
+ nativeConnection,
+ body.getBytes(StandardCharsets.UTF_8));
var headerProperties = new GatewayHeaderTrustProperties();
var trust =
@@ -153,7 +162,12 @@ void authenticatedAccountInvalidArgumentMapsToSafeBadRequest() {
var responseHolder = new AtomicReference>();
trust
.filter(
- MockServerWebExchange.from(request),
+ new org.springframework.web.server.adapter.DefaultServerWebExchange(
+ request,
+ new org.springframework.mock.http.server.reactive.MockServerHttpResponse(),
+ new org.springframework.web.server.session.DefaultWebSessionManager(),
+ org.springframework.http.codec.ServerCodecConfigurer.create(),
+ new org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver()),
exchange -> controller.login(exchange).doOnNext(responseHolder::set).then())
.block();
var response = responseHolder.get();
@@ -308,6 +322,55 @@ public Object newConfig() {
};
}
+ /** A login request whose native request is the Reactor Netty connection carrying the peer. */
+ private static final class NativeSocketLoginRequest
+ extends org.springframework.http.server.reactive.AbstractServerHttpRequest {
+ private final java.net.InetSocketAddress remoteAddress;
+ private final Object nativeRequest;
+ private final byte[] body;
+
+ private NativeSocketLoginRequest(
+ URI uri,
+ HttpHeaders headers,
+ java.net.InetSocketAddress remoteAddress,
+ Object nativeRequest,
+ byte[] body) {
+ super(HttpMethod.POST, uri, "", headers);
+ this.remoteAddress = remoteAddress;
+ this.nativeRequest = nativeRequest;
+ this.body = body.clone();
+ }
+
+ @Override
+ public java.net.InetSocketAddress getRemoteAddress() {
+ return remoteAddress;
+ }
+
+ @Override
+ protected SslInfo initSslInfo() {
+ return mock(SslInfo.class);
+ }
+
+ @Override
+ protected org.springframework.util.MultiValueMap
+ initCookies() {
+ return new org.springframework.util.LinkedMultiValueMap<>();
+ }
+
+ @Override
+ public reactor.core.publisher.Flux getBody() {
+ return reactor.core.publisher.Flux.just(
+ org.springframework.core.io.buffer.DefaultDataBufferFactory.sharedInstance.wrap(
+ body.clone()));
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public T getNativeRequest() {
+ return (T) nativeRequest;
+ }
+ }
+
@FunctionalInterface
private interface RateLimitObservation {
void record(String routeId, String key);