From 2d5c2f931d86960425cad51c60b52e65099d40f4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:28:36 +1300 Subject: [PATCH 1/9] fix: bound issuer turnover reads to current SQL membership --- .../game-session-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 2 + ...IssuerBindingLocalOperationRepository.java | 12 +- ...ssuerBindingLocalProjectionRepository.java | 141 +++--- ...ingLocalRetirementOperationRepository.java | 36 +- ...playIssuerPartitionMutationRepository.java | 23 +- ...rent_issuer_local_operation_membership.sql | 446 ++++++++++++++++++ ...calOperationRepositoryIntegrationTest.java | 50 +- ...suerPhysicalRetirementIntegrationTest.java | 260 ++++++++-- 9 files changed, 836 insertions(+), 136 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1038.5__current_issuer_local_operation_membership.sql diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index ee5a6d6660..f89d173cf0 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection and issuer-local release, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The bounded foundation does not execute physical retirement; retained storage and fail-closed accounting remain prerequisites for the separate settlement owner. The settlement stage now supplies that separate executable owner and exact retirement readback while retaining the same original-source and currentness requirements. The focused component proofs do not establish operational source or incarnation custody. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS, and admission remain absent. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. +- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection and issuer-local release, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The bounded foundation does not execute physical retirement; retained storage and fail-closed accounting remain prerequisites for the separate settlement owner. The settlement stage now supplies that separate executable owner and exact retirement readback while retaining the same original-source and currentness requirements. Its bounded current-membership correction maintains `game_session_canonical_issuer_current_local_operation` as references to immutable local operations: registration adds a reference, pending cleanup retains it, and only an exactly proven completed retirement removes it. Ordinary projection reads use that current set while original operations, reservations and completion receipts remain retained provenance; this adds no inventory or admission authority. The current-versus-retained boundary remains owned by the [Redis issuer-index contract](../../system-architecture-redis.md#issuer-active-binding-index). The focused component proofs do not establish operational source or incarnation custody. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS, and admission remain absent. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index ce0dcf0f3c..2a5769cae6 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components +The current-membership correction prepares forward V1038.5 and SQL-maintained references to original unretired local operations. Projection, capacity, slot registration, ADD-mutation reads and retirement conflict checks use current ownership rather than enumerating lifetime immutable history; pending-retirement validation starts from the bounded partition heads. Existing immutable provenance and exact owner checks remain required. The native retirement proof now checks current membership through pending/lost-reply/completion rollback/exact retry and more than 256 lifetime cycles. Its migration fixture adapts only the historical pre-membership slot-count read, retaining actual old-schema guards and post-upgrade backfill/current reads; it does not qualify a new gate before its schema exists. R974 is running on the six runtime/proof postimages; the separate historical-migration case and final receiving checks remain unrun at this preparation checkpoint. This does not establish registration, live issuer custody, activation or production admission. + The next protected-settlement correction versions both sides of the closed response and aligns the SQL `EXPECT_CLOSED` negative terminal with the existing immutable-origin contract through forward V1040.3. R970 passes 31 focused codec/client/verifier/service unit cases and one actual World–Game Session–Account acquisition composition, with enabled affected analysis, formatting and migration-frontier checks. Its aggregate fails the new later-request extension because that fixture reuses the same original owner attempt, which V1006 correctly permits only once. After removing that invalid extension, R971 passes the focused native protected-abort case and integration analysis/formatting. The native case proves actual competing-intent refusal while the first request is pending, original terminal/read/replay and unchanged pointer/audit. Its positive current-origin refusal remains controlled: neither result proves independent pointer advancement before abort or later-OPEN recovery. The separate current-inventory/retained-history turnover correction remains unfinished. The bounded issuer foundation in #3310 owns bootstrap, ordinary local projection and proof-backed release after a known first-NEW Account abort. The executable original-operation physical-retirement owner and its turnover proof belong with #2973 settlement. The foundation retains the V1038/V1038.4 storage and history guards required by ordinary projection; it retains terminal capacity and refuses fresh allocation at the existing 256-unretired-operation bound until the successor supplies physical retirement. This separates executable capability without weakening the canonical retirement contract or claiming unknown-decision orphan-cleanup delivery. Earlier combined proof below retains its original source attribution. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index b112ecaf1e..a7b7680682 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -280,14 +280,14 @@ private static void requirePhysicalOperationSlotAvailable( Record countRow = Objects.requireNonNull( transaction.fetchOne( - "SELECT count(*) FROM " + "SELECT count(*) FROM game_session_canonical_issuer_current_local_operation membership" + + " JOIN " + OPERATION - + " operation WHERE operation.issuer_id = ? AND operation.partition_id = ?" - + " AND NOT EXISTS (SELECT 1 FROM" - + " game_session_canonical_issuer_binding_local_retirement retirement" - + " WHERE retirement.original_local_operation_id = operation.operation_id" - + " AND retirement.status = 'RETIRED')", + + " operation ON operation.operation_id = membership.operation_id" + + " WHERE membership.issuer_id = ? AND membership.anchor_bootstrap_operation_id = ?" + + " AND membership.partition_id = ?", ISSUER, + anchor.bootstrapOperationId(), decimal(partitionId)), "Expected local issuer operation count row"); long operationCount = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index c89d416491..36a084d641 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -29,6 +29,8 @@ final class CanonicalGameplayIssuerBindingLocalProjectionRepository { "game_session_canonical_issuer_binding_local_operation"; private static final String BOOTSTRAP_OPERATION = "game_session_canonical_issuer_bootstrap_member_operation"; + private static final String CURRENT_LOCAL_OPERATION = + "game_session_canonical_issuer_current_local_operation"; private static final String RESERVATION = "game_session_canonical_issuer_partition_reservation"; private static final String INVENTORY = "game_session_canonical_gameplay_binding_inventory"; private static final String TRANSITION = "game_session_canonical_binding_transition"; @@ -156,13 +158,15 @@ private PreparedPartitionWork prepareInTransaction( List operationRows = transaction.fetch( "SELECT operation.* FROM " + + CURRENT_LOCAL_OPERATION + + " membership JOIN " + LOCAL_OPERATION - + " operation WHERE operation.issuer_id = ? AND operation.partition_id = ? AND NOT EXISTS (SELECT 1 FROM " - + "game_session_canonical_issuer_binding_local_retirement retirement" - + " WHERE retirement.original_local_operation_id = operation.operation_id" - + " AND retirement.status = 'RETIRED')" + + " operation ON operation.operation_id = membership.operation_id" + + " WHERE membership.issuer_id = ? AND membership.anchor_bootstrap_operation_id = ?" + + " AND membership.partition_id = ?" + " ORDER BY operation.operation_fence, operation.operation_id", ISSUER, + anchor.bootstrapOperationId(), targetPartition); PartitionSources sources = readPartitionSources(transaction, operationRows, anchor, targetPartition); @@ -177,7 +181,7 @@ private PreparedPartitionWork prepareInTransaction( proofsByPartition.put(targetPartition, targetBaseline); int partitionLocalOperationCount = 0; - BigInteger localAggregateCapacity = readIssuerLocalCapacity(transaction); + BigInteger localAggregateCapacity = readIssuerLocalCapacity(transaction, anchor); BigInteger localPartitionCapacity = BigInteger.ZERO; boolean foundTarget = false; for (Record row : operationRows) { @@ -241,8 +245,8 @@ private PreparedPartitionWork prepareInTransaction( "A post-baseline issuer operation reuses an installed reservation identity"); } } - verifyCurrentReservationAccounting(transaction, anchor, baselineReservationIds.size()); - verifyRetirementAccounting(transaction); + verifyCurrentReservationAccounting(transaction, anchor); + verifyRetirementAccounting(transaction, anchor); BigInteger aggregateCapacity = anchor.aggregateCountedCapacity().add(localAggregateCapacity); BigInteger aggregateBound = anchor.partitionCount().multiply(anchor.partitionCapacity()); @@ -380,19 +384,22 @@ private PreparedPartitionWork prepareInTransaction( return baseline; } - private static BigInteger readIssuerLocalCapacity(DSLContext transaction) { + private static BigInteger readIssuerLocalCapacity( + DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor) { Record row = transaction.fetchOne( "SELECT COUNT(*) AS count FROM " + + CURRENT_LOCAL_OPERATION + + " membership JOIN " + LOCAL_OPERATION - + " operation JOIN " + + " operation ON operation.operation_id = membership.operation_id JOIN " + RESERVATION + " reservation ON reservation.reservation_id = operation.reservation_id" + " AND reservation.issuer_id = operation.issuer_id" - + " WHERE operation.issuer_id = ? AND reservation.lifecycle <> 'RELEASED'" - + " AND NOT EXISTS (SELECT 1 FROM game_session_canonical_issuer_binding_local_retirement retirement" - + " WHERE retirement.original_local_operation_id = operation.operation_id AND retirement.status = 'RETIRED')", - ISSUER); + + " WHERE membership.issuer_id = ? AND membership.anchor_bootstrap_operation_id = ?" + + " AND reservation.lifecycle <> 'RELEASED'", + ISSUER, + anchor.bootstrapOperationId()); if (row == null) throw unavailable("The issuer-wide local capacity count is unavailable"); return number(row, "count"); } @@ -868,68 +875,83 @@ private static Set readAndVerifyBootstrapReservationIds( return reservationIds; } - private static BigInteger verifyCurrentReservationAccounting( - DSLContext transaction, - CanonicalGameplayIssuerInstalledAnchor anchor, - int baselineReservationCount) { - Record localCountRow = - transaction.fetchOne( - "SELECT COUNT(*) AS count FROM " + LOCAL_OPERATION + " WHERE issuer_id = ?", ISSUER); - Record reservationCountRow = + private static void verifyCurrentReservationAccounting( + DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor) { + // SQL write-boundary guards maintain this complete current set. Retained original operations + // and completed retirements remain immutable provenance, not an ordinary projection inventory. + Record invalidMembership = transaction.fetchOne( - "SELECT COUNT(*) AS count FROM " + RESERVATION + " WHERE issuer_id = ?", ISSUER); - Record orphanCountRow = + "SELECT COUNT(*) AS count FROM " + + CURRENT_LOCAL_OPERATION + + " membership LEFT JOIN " + + LOCAL_OPERATION + + " operation ON operation.operation_id = membership.operation_id LEFT JOIN " + + RESERVATION + + " reservation ON reservation.reservation_id = operation.reservation_id" + + " WHERE membership.issuer_id = ? AND (operation.operation_id IS NULL" + + " OR reservation.reservation_id IS NULL OR operation.issuer_id <> membership.issuer_id" + + " OR operation.anchor_bootstrap_operation_id <> membership.anchor_bootstrap_operation_id" + + " OR membership.anchor_bootstrap_operation_id <> ?" + + " OR operation.partition_id <> membership.partition_id" + + " OR reservation.issuer_id <> membership.issuer_id" + + " OR reservation.partition_id <> membership.partition_id" + + " OR reservation.transition_id <> operation.transition_id" + + " OR reservation.binding_ref <> operation.binding_ref" + + " OR EXISTS (SELECT 1 FROM " + + BOOTSTRAP_OPERATION + + " bootstrap WHERE bootstrap.bootstrap_operation_id = ?" + + " AND bootstrap.reservation_id = reservation.reservation_id))", + ISSUER, + anchor.bootstrapOperationId(), + anchor.bootstrapOperationId()); + Record orphanReservations = transaction.fetchOne( "SELECT COUNT(*) AS count FROM " + RESERVATION - + " reservation WHERE reservation.issuer_id = ? AND NOT EXISTS (SELECT 1 FROM " + + " reservation WHERE reservation.issuer_id = ? AND reservation.lifecycle <> 'RELEASED'" + + " AND NOT EXISTS (SELECT 1 FROM " + BOOTSTRAP_OPERATION + " bootstrap WHERE bootstrap.bootstrap_operation_id = ?" + + " AND bootstrap.issuer_id = reservation.issuer_id" + " AND bootstrap.reservation_id = reservation.reservation_id)" + " AND NOT EXISTS (SELECT 1 FROM " + LOCAL_OPERATION - + " operation WHERE operation.issuer_id = reservation.issuer_id" - + " AND operation.reservation_id = reservation.reservation_id)", + + " operation JOIN " + + CURRENT_LOCAL_OPERATION + + " membership ON membership.operation_id = operation.operation_id" + + " WHERE operation.reservation_id = reservation.reservation_id" + + " AND membership.issuer_id = reservation.issuer_id" + + " AND membership.anchor_bootstrap_operation_id = ?)", ISSUER, + anchor.bootstrapOperationId(), anchor.bootstrapOperationId()); - Record missingCountRow = - transaction.fetchOne( - "SELECT COUNT(*) AS count FROM " - + LOCAL_OPERATION - + " operation WHERE operation.issuer_id = ? AND NOT EXISTS (SELECT 1 FROM " - + RESERVATION - + " reservation WHERE reservation.issuer_id = operation.issuer_id" - + " AND reservation.reservation_id = operation.reservation_id)", - ISSUER); - if (localCountRow == null - || reservationCountRow == null - || orphanCountRow == null - || missingCountRow == null) { - throw unavailable("The complete retained issuer reservation accounting is unavailable"); - } - BigInteger localCount = number(localCountRow, "count"); - BigInteger reservationCount = number(reservationCountRow, "count"); - if (number(orphanCountRow, "count").signum() != 0 - || number(missingCountRow, "count").signum() != 0 - || !reservationCount.equals(localCount.add(BigInteger.valueOf(baselineReservationCount)))) { + if (invalidMembership == null + || orphanReservations == null + || number(invalidMembership, "count").signum() != 0 + || number(orphanReservations, "count").signum() != 0) { throw unavailable( - "Durable issuer reservations differ from full bootstrap and local SQL history"); + "Current issuer reservations differ from their exact bootstrap or local owners"); } - return reservationCount; } - private static void verifyRetirementAccounting(DSLContext transaction) { + private static void verifyRetirementAccounting( + DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor) { Record invalidRows = transaction.fetchOne( - "SELECT COUNT(*) AS count FROM game_session_canonical_issuer_binding_local_retirement retirement" + "SELECT COUNT(*) AS count FROM game_session_canonical_issuer_partition_mutation_head head" + + " JOIN game_session_canonical_issuer_partition_mutation mutation" + + " ON mutation.mutation_id = head.pending_mutation_id" + + " AND mutation.issuer_id = head.issuer_id" + + " AND mutation.bootstrap_operation_id = head.bootstrap_operation_id" + + " AND mutation.partition_id = head.partition_id" + + " LEFT JOIN game_session_canonical_issuer_binding_local_retirement retirement" + + " ON retirement.retirement_operation_id = mutation.owner_operation_id" + " LEFT JOIN " + LOCAL_OPERATION + " original ON original.operation_id = retirement.original_local_operation_id" + " LEFT JOIN " + ISSUER_LOCAL_RELEASE + " release ON release.operation_id = retirement.release_operation_id" - + " LEFT JOIN game_session_canonical_issuer_partition_mutation mutation" - + " ON mutation.mutation_id = retirement.physical_mutation_id" + " LEFT JOIN " + RESERVATION + " reservation ON reservation.reservation_id = retirement.reservation_id" @@ -950,7 +972,13 @@ private static void verifyRetirementAccounting(DSLContext transaction) { + " LEFT JOIN " + REGION_OBLIGATION + " region_obligation ON region_obligation.transition_id = retirement.transition_id" - + " WHERE retirement.issuer_id = ? AND (original.operation_id IS NULL OR release.operation_id IS NULL" + + " WHERE head.issuer_id = ? AND head.bootstrap_operation_id = ?" + + " AND mutation.mutation_kind = 'RETIRE' AND (retirement.retirement_operation_id IS NULL" + + " OR retirement.issuer_id <> head.issuer_id OR retirement.partition_id <> head.partition_id" + + " OR retirement.physical_mutation_id <> mutation.mutation_id" + + " OR retirement.status <> 'PENDING_PHYSICAL_PROOF'" + + " OR head.current_revision <> mutation.expected_revision" + + " OR original.operation_id IS NULL OR release.operation_id IS NULL" + " OR mutation.mutation_id IS NULL OR original.reservation_id <> retirement.reservation_id" + " OR original.binding_ref <> retirement.binding_ref" + " OR release.status <> 'RELEASED' OR release.original_local_operation_id <> retirement.original_local_operation_id" @@ -966,8 +994,6 @@ private static void verifyRetirementAccounting(DSLContext transaction) { + " OR mutation.successor_revision <> retirement.successor_revision" + " OR mutation.exact_intended_change_bytes <> retirement.exact_intended_change_bytes" + " OR mutation.exact_intended_change_digest <> retirement.exact_intended_change_digest" - + " OR (retirement.status = 'RETIRED' AND (mutation.status <> 'COMMITTED'" - + " OR mutation.exact_readback_field_set_bytes <> retirement.exact_absence_readback_field_set_bytes))" + " OR (retirement.status = 'PENDING_PHYSICAL_PROOF' AND (mutation.status <> 'PENDING_PHYSICAL_PROOF'" + " OR reservation.reservation_id IS NULL OR reservation.lifecycle <> 'RELEASED'" + " OR reservation.inventory_revision <> retirement.release_completion_inventory_revision" @@ -986,10 +1012,11 @@ private static void verifyRetirementAccounting(DSLContext transaction) { + " OR account_obligation.inventory_revision <> retirement.release_completion_inventory_revision" + " OR region_obligation.transition_id IS NULL" + " OR region_obligation.inventory_revision <> retirement.release_completion_inventory_revision)))", - ISSUER); + ISSUER, + anchor.bootstrapOperationId()); if (invalidRows == null || number(invalidRows, "count").signum() != 0) { throw unavailable( - "A retained physical retirement does not match its exact SQL release and mutation history"); + "A pending physical retirement does not match its exact SQL release and mutation history"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java index 8a414f064b..381a6f61d4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java @@ -482,16 +482,14 @@ private static void protectCurrentReferences( UUID operationId = original.operationId(); if (count( transaction, - "SELECT COUNT(*) FROM " + "SELECT COUNT(*) FROM game_session_canonical_issuer_current_local_operation membership" + + " JOIN " + LOCAL_OPERATION - + " operation WHERE operation.issuer_id = ?" - + " AND operation.binding_ref = ? AND operation.operation_id <> ?" - + " AND NOT EXISTS (SELECT 1 FROM " - + RETIREMENT - + " retired" - + " WHERE retired.original_local_operation_id = operation.operation_id" - + " AND retired.status = 'RETIRED')", + + " operation ON operation.operation_id = membership.operation_id" + + " WHERE membership.issuer_id = ? AND membership.anchor_bootstrap_operation_id = ?" + + " AND operation.binding_ref = ? AND operation.operation_id <> ?", ISSUER, + original.anchor().bootstrapOperationId(), bindingRef, operationId) != 0 @@ -499,14 +497,22 @@ private static void protectCurrentReferences( transaction, "SELECT COUNT(*) FROM " + RESERVATION - + " reservation WHERE reservation.issuer_id = ?" - + " AND reservation.binding_ref = ? AND reservation.reservation_id <> ?" - + " AND NOT EXISTS (SELECT 1 FROM " - + RETIREMENT - + " retired" - + " WHERE retired.reservation_id = reservation.reservation_id" - + " AND retired.status = 'RETIRED')", + + " reservation WHERE reservation.issuer_id = ? AND reservation.lifecycle <> 'RELEASED'" + + " AND reservation.binding_ref = ? AND reservation.reservation_id <> ?", + ISSUER, + bindingRef, + reservationId) + != 0 + || count( + transaction, + "SELECT COUNT(*) FROM game_session_canonical_issuer_bootstrap_member_operation bootstrap" + + " JOIN " + + RESERVATION + + " reservation ON reservation.reservation_id = bootstrap.reservation_id" + + " WHERE bootstrap.issuer_id = ? AND bootstrap.bootstrap_operation_id = ?" + + " AND reservation.binding_ref = ? AND reservation.reservation_id <> ?", ISSUER, + original.anchor().bootstrapOperationId(), bindingRef, reservationId) != 0) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java index b10ad47936..5ce7ec701a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionMutationRepository.java @@ -415,21 +415,20 @@ static List readPartitionInTransaction List mutations = new ArrayList<>(); for (Record row : transaction.fetch( - "SELECT * FROM " + "SELECT mutation.* FROM game_session_canonical_issuer_current_local_operation membership" + + " JOIN game_session_canonical_issuer_binding_local_operation operation" + + " ON operation.operation_id = membership.operation_id JOIN " + MUTATION - + " WHERE issuer_id = ? AND bootstrap_operation_id = ? AND partition_id = ?" - + " AND mutation_kind IN ('ADD_CAPACITY', 'ADD_BINDING')" - + " AND owner_operation_id IN (SELECT operation.operation_id" - + " FROM game_session_canonical_issuer_binding_local_operation operation" - + " WHERE operation.issuer_id = ? AND operation.partition_id = ?" - + " AND NOT EXISTS (SELECT 1 FROM game_session_canonical_issuer_binding_local_retirement retirement" - + " WHERE retirement.original_local_operation_id = operation.operation_id" - + " AND retirement.status = 'RETIRED'))" - + " ORDER BY mutation_id", + + " mutation ON mutation.owner_operation_id = operation.operation_id" + + " AND mutation.issuer_id = membership.issuer_id" + + " AND mutation.bootstrap_operation_id = membership.anchor_bootstrap_operation_id" + + " AND mutation.partition_id = membership.partition_id" + + " WHERE membership.issuer_id = ? AND membership.anchor_bootstrap_operation_id = ?" + + " AND membership.partition_id = ?" + + " AND mutation.mutation_kind IN ('ADD_CAPACITY', 'ADD_BINDING')" + + " ORDER BY mutation.mutation_id", ISSUER, bootstrapOperationId, - partitionId, - ISSUER, partitionId)) { mutations.add(readMutation(row)); } diff --git a/services/game-session-service/src/main/resources/db/migration/V1038.5__current_issuer_local_operation_membership.sql b/services/game-session-service/src/main/resources/db/migration/V1038.5__current_issuer_local_operation_membership.sql new file mode 100644 index 0000000000..070fce39a6 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1038.5__current_issuer_local_operation_membership.sql @@ -0,0 +1,446 @@ +-- Positive references to original local operations whose physical capacity has not retired. +-- This is a bounded current projection over the existing inventory, not a new inventory authority. +-- Immutable operations, releases, mutations, retirement receipts and original bytes stay intact. +CREATE TABLE game_session_canonical_issuer_current_local_operation ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + anchor_bootstrap_operation_id uuid NOT NULL, + partition_id numeric NOT NULL, + CONSTRAINT pk_gs_issuer_current_local_operation PRIMARY KEY (operation_id), + CONSTRAINT fk_gs_issuer_current_local_operation_original + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_issuer_binding_local_operation (operation_id), + CONSTRAINT chk_gs_issuer_current_local_operation CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND anchor_bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND partition_id >= 0 AND partition_id = floor(partition_id)) +); +CREATE INDEX ix_gs_issuer_current_local_operation_partition + ON game_session_canonical_issuer_current_local_operation + (issuer_id, anchor_bootstrap_operation_id, partition_id); + +-- All point checks below start at an existing primary/unique key. In particular, retirement +-- lookup starts at the unique release.original_local_operation_id and retirement.release_operation_id; +-- it never searches the accumulated retirement history by status. +-- [jooq ignore start] +CREATE FUNCTION gs_issuer_local_operation_has_exact_retirement(original_id uuid) +RETURNS boolean +LANGUAGE sql +AS $$ + SELECT EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_binding_local_operation original + JOIN game_session_canonical_issuer_binding_local_release_operation release + ON release.original_local_operation_id = original.operation_id + JOIN game_session_canonical_issuer_binding_local_retirement retirement + ON retirement.release_operation_id = release.operation_id + JOIN game_session_canonical_issuer_partition_mutation mutation + ON mutation.mutation_id = retirement.physical_mutation_id + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = original.reservation_id + WHERE original.operation_id = original_id + AND release.status = 'RELEASED' + AND retirement.status = 'RETIRED' + AND mutation.status = 'COMMITTED' + AND reservation.lifecycle = 'RELEASED' + AND ROW(retirement.issuer_id, retirement.partition_id, + retirement.original_local_operation_id, retirement.transition_id, + retirement.reservation_id, retirement.binding_ref, + retirement.original_reservation_fence, + retirement.original_issuer_coverage_operation_id, + retirement.original_issuer_coverage_operation_fence, + retirement.original_coverage_fence, + retirement.original_inventory_snapshot_revision, + retirement.original_reservation_inventory_revision, + retirement.anchor_issuer_coverage_operation_id, + retirement.anchor_operation_fence, retirement.anchor_coverage_fence, + retirement.anchor_inventory_snapshot_revision, + retirement.original_member_value_bytes, retirement.original_member_value_digest) + IS NOT DISTINCT FROM + ROW(original.issuer_id, original.partition_id, original.operation_id, + original.transition_id, original.reservation_id, original.binding_ref, + original.reservation_fence, original.original_issuer_coverage_operation_id, + original.original_issuer_coverage_operation_fence, + original.original_coverage_fence, original.original_inventory_snapshot_revision, + original.local_inventory_snapshot_revision, original.anchor_issuer_coverage_operation_id, + original.anchor_operation_fence, original.anchor_coverage_fence, + original.anchor_issuer_inventory_snapshot_revision, + original.member_value_bytes, original.member_value_digest) + AND ROW(release.issuer_id, release.partition_id, release.original_local_operation_id, + release.transition_id, release.reservation_id, release.binding_ref, + release.original_reservation_fence, release.original_issuer_coverage_operation_id, + release.original_issuer_coverage_operation_fence, release.original_coverage_fence, + release.original_inventory_snapshot_revision, + release.original_reservation_inventory_revision, + release.anchor_issuer_coverage_operation_id, release.anchor_operation_fence, + release.anchor_coverage_fence, release.anchor_inventory_snapshot_revision, + release.source_inventory_revision, release.completion_inventory_revision, + release.original_member_value_bytes, release.original_member_value_digest, + release.released_member_value_bytes, release.released_member_value_digest) + IS NOT DISTINCT FROM + ROW(retirement.issuer_id, retirement.partition_id, retirement.original_local_operation_id, + retirement.transition_id, retirement.reservation_id, retirement.binding_ref, + retirement.original_reservation_fence, retirement.original_issuer_coverage_operation_id, + retirement.original_issuer_coverage_operation_fence, retirement.original_coverage_fence, + retirement.original_inventory_snapshot_revision, + retirement.original_reservation_inventory_revision, + retirement.anchor_issuer_coverage_operation_id, retirement.anchor_operation_fence, + retirement.anchor_coverage_fence, retirement.anchor_inventory_snapshot_revision, + retirement.release_source_inventory_revision, + retirement.release_completion_inventory_revision, + retirement.original_member_value_bytes, retirement.original_member_value_digest, + retirement.released_member_value_bytes, retirement.released_member_value_digest) + AND reservation.inventory_revision = release.completion_inventory_revision + AND mutation.issuer_id = original.issuer_id + AND mutation.bootstrap_operation_id = original.anchor_bootstrap_operation_id + AND mutation.partition_id = original.partition_id + AND mutation.mutation_kind = 'RETIRE' + AND mutation.owner_operation_id = retirement.retirement_operation_id + AND mutation.expected_revision = retirement.expected_revision + AND mutation.successor_revision = retirement.successor_revision + AND mutation.exact_intended_change_bytes = retirement.exact_intended_change_bytes + AND mutation.exact_intended_change_digest = retirement.exact_intended_change_digest + AND mutation.exact_readback_field_set_bytes = retirement.exact_absence_readback_field_set_bytes + AND mutation.exact_readback_field_set_digest = retirement.exact_absence_readback_field_set_digest + AND retirement.completed_at IS NOT NULL + AND retirement.exact_absence_readback_field_set_bytes IS NOT NULL + AND retirement.exact_absence_readback_field_set_digest IS NOT NULL); +$$; + +CREATE FUNCTION gs_issuer_local_operation_has_exact_source(original_id uuid) +RETURNS boolean +LANGUAGE sql +AS $$ + SELECT EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_binding_local_operation original + JOIN game_session_canonical_issuer_installed_anchor anchor + ON anchor.issuer_id = original.issuer_id + AND anchor.bootstrap_operation_id = original.anchor_bootstrap_operation_id + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = original.reservation_id + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = original.binding_ref + WHERE original.operation_id = original_id + AND ROW(original.anchor_bootstrap_request_id, original.anchor_build_operation_id, + original.anchor_build_plan_digest, original.anchor_control_epoch, + original.anchor_issuer_coverage_operation_id, original.anchor_operation_fence, + original.anchor_coverage_fence, original.anchor_issuer_inventory_snapshot_revision, + original.anchor_layout_version, original.anchor_partition_count, + original.anchor_partition_capacity, original.anchor_mapping_identity, + original.anchor_layout_descriptor_bytes, original.anchor_layout_descriptor_digest, + original.anchor_issuer_auth_generation, original.anchor_source_checkpoint_bytes, + original.anchor_source_checkpoint_digest, original.anchor_source_event_bytes, + original.anchor_source_event_digest, original.anchor_incarnation_bytes, + original.anchor_incarnation_digest, original.exact_anchor_bytes, original.exact_anchor_digest) + IS NOT DISTINCT FROM + ROW(anchor.bootstrap_request_id, anchor.build_operation_id, anchor.build_plan_digest, + anchor.control_epoch, anchor.issuer_coverage_operation_id, anchor.operation_fence, + anchor.coverage_fence, anchor.issuer_inventory_snapshot_revision, + anchor.layout_version, anchor.partition_count, anchor.partition_capacity, + anchor.mapping_identity, anchor.layout_descriptor_bytes, anchor.layout_descriptor_digest, + anchor.issuer_auth_generation, anchor.source_checkpoint_bytes, + anchor.source_checkpoint_digest, anchor.source_event_bytes, + anchor.source_event_digest, anchor.incarnation_bytes, + anchor.incarnation_digest, anchor.exact_anchor_bytes, anchor.exact_anchor_digest) + AND ROW(reservation.issuer_id, reservation.transition_id, reservation.binding_ref, + reservation.binding_generation, reservation.reservation_fence, + reservation.partition_id, reservation.issuer_index_layout_version, + reservation.issuer_index_partition_count, reservation.issuer_index_partition_capacity, + reservation.issuer_auth_generation, reservation.issuer_coverage_operation_id, + reservation.issuer_coverage_operation_fence, reservation.coverage_fence, + reservation.inventory_snapshot_revision) + IS NOT DISTINCT FROM + ROW(original.issuer_id, original.transition_id, original.binding_ref, + original.binding_generation, original.reservation_fence, original.partition_id, + original.anchor_layout_version, original.anchor_partition_count, + original.anchor_partition_capacity, original.anchor_issuer_auth_generation, + original.original_issuer_coverage_operation_id, + original.original_issuer_coverage_operation_fence, original.original_coverage_fence, + original.original_inventory_snapshot_revision) + AND ROW(reservation.account_id, reservation.tenant_id, reservation.playable_state_namespace_id, + reservation.character_id, reservation.playable_state_scope, reservation.game_instance_id, + reservation.runtime_game_instance_id, reservation.session_id, + reservation.region_id, reservation.region_epoch) + IS NOT DISTINCT FROM + ROW(candidate.account_id, candidate.tenant_id, candidate.playable_state_namespace_id, + candidate.character_id, candidate.playable_state_scope, candidate.game_instance_id, + candidate.runtime_game_instance_id, candidate.session_id, + candidate.region_id, candidate.region_epoch) + AND candidate.issuer_reservation_id = original.reservation_id + AND candidate.transition_id = original.transition_id + AND candidate.binding_generation = original.binding_generation + AND candidate.account_index_fence = original.candidate_account_index_fence + -- The original revision is frozen. Abort/release advance the mutable reservation revision; + -- equating it to the original here would reject legitimate cleanup and retained upgrades. + AND reservation.inventory_revision >= original.local_inventory_snapshot_revision); +$$; + +-- Use the owner's existing inventory -> issuer -> account serialization. Statement triggers take +-- the clock before a new row lock; they neither advance the clock nor allocate another fence. +CREATE FUNCTION gs_lock_issuer_current_membership_clock() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM singleton_id FROM game_session_canonical_binding_inventory_clock + WHERE singleton_id = 1 FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Issuer current membership requires the existing inventory clock' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION gs_require_issuer_reservation_current_membership(reservation_identity uuid) +RETURNS void +LANGUAGE plpgsql +AS $$ +DECLARE + reservation game_session_canonical_issuer_partition_reservation%ROWTYPE; + anchor game_session_canonical_issuer_installed_anchor%ROWTYPE; + original game_session_canonical_issuer_binding_local_operation%ROWTYPE; +BEGIN + SELECT * INTO STRICT reservation + FROM game_session_canonical_issuer_partition_reservation + WHERE reservation_id = reservation_identity; + SELECT * INTO anchor FROM game_session_canonical_issuer_installed_anchor + WHERE issuer_id = reservation.issuer_id; + IF NOT FOUND THEN + -- Genuine initial inventory preparation precedes the first positive installed anchor. + RETURN; + END IF; + SELECT * INTO original FROM game_session_canonical_issuer_binding_local_operation + WHERE reservation_id = reservation_identity; + IF FOUND THEN + IF original.anchor_bootstrap_operation_id <> anchor.bootstrap_operation_id + OR NOT gs_issuer_local_operation_has_exact_source(original.operation_id) THEN + RAISE EXCEPTION 'Issuer reservation differs from its exact installed local-operation source' + USING ERRCODE = '23514'; + END IF; + IF gs_issuer_local_operation_has_exact_retirement(original.operation_id) THEN + IF EXISTS (SELECT 1 FROM game_session_canonical_issuer_current_local_operation current + WHERE current.operation_id = original.operation_id) THEN + RAISE EXCEPTION 'Retired issuer operation cannot remain in current membership' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_current_local_operation current + WHERE current.operation_id = original.operation_id + AND current.issuer_id = original.issuer_id + AND current.anchor_bootstrap_operation_id = anchor.bootstrap_operation_id + AND current.partition_id = original.partition_id) THEN + RAISE EXCEPTION 'Unretired issuer reservation requires its exact current local operation' + USING ERRCODE = '23514'; + END IF; + RETURN; + END IF; + -- Bootstrap source keys are reservation UUID text, unique within the exact installed build. + -- Preserve the complete original identity, owner, fences, layout and creation timestamp. + -- Lifecycle and inventory revision are mutable under their existing owner guards; a qualified + -- release must not lose baseline membership merely because it advances those two columns. + IF EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_build_cohort_row cohort + WHERE cohort.build_operation_id = anchor.build_operation_id + AND cohort.source_operation_id = anchor.bootstrap_operation_id + AND cohort.issuer_id = anchor.issuer_id + AND cohort.source_kind = 'RESERVATION' + AND cohort.source_key = reservation_identity::text + AND cohort.source_inventory_revision <= reservation.inventory_revision + AND (cohort.source_row_json::jsonb - 'lifecycle' - 'inventory_revision') + = (to_jsonb(reservation) - 'lifecycle' - 'inventory_revision')) THEN + RETURN; + END IF; + RAISE EXCEPTION 'Installed issuer reservation requires exact bootstrap or current local-operation membership' + USING ERRCODE = '23514'; +END; +$$; + +-- One-time populated upgrade: inspect retained provenance before enabling ongoing guards, without +-- modifying any original row or temporarily disabling an existing retention trigger. +DO $$ +DECLARE + original record; + retained record; +BEGIN + PERFORM singleton_id FROM game_session_canonical_binding_inventory_clock + WHERE singleton_id = 1 FOR UPDATE; + FOR original IN SELECT operation_id FROM game_session_canonical_issuer_binding_local_operation LOOP + IF NOT gs_issuer_local_operation_has_exact_source(original.operation_id) THEN + RAISE EXCEPTION 'Retained issuer local operation has ambiguous original source: %', original.operation_id + USING ERRCODE = '23514'; + END IF; + END LOOP; + FOR retained IN + SELECT retirement.original_local_operation_id + FROM game_session_canonical_issuer_binding_local_retirement retirement + WHERE retirement.status = 'RETIRED' + LOOP + IF NOT gs_issuer_local_operation_has_exact_retirement(retained.original_local_operation_id) THEN + RAISE EXCEPTION 'Retained issuer retirement lacks exact committed original proof: %', retained.original_local_operation_id + USING ERRCODE = '23514'; + END IF; + END LOOP; +END; +$$; + +INSERT INTO game_session_canonical_issuer_current_local_operation + (operation_id, issuer_id, anchor_bootstrap_operation_id, partition_id) +SELECT original.operation_id, original.issuer_id, original.anchor_bootstrap_operation_id, original.partition_id + FROM game_session_canonical_issuer_binding_local_operation original + WHERE NOT gs_issuer_local_operation_has_exact_retirement(original.operation_id); + +DO $$ +DECLARE + retained record; +BEGIN + FOR retained IN SELECT reservation_id FROM game_session_canonical_issuer_partition_reservation LOOP + PERFORM gs_require_issuer_reservation_current_membership(retained.reservation_id); + END LOOP; +END; +$$; + +CREATE FUNCTION gs_guard_issuer_current_local_operation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP IN ('UPDATE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Issuer current membership identity cannot be updated or truncated' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_binding_local_operation original + WHERE original.operation_id = NEW.operation_id + AND original.issuer_id = NEW.issuer_id + AND original.anchor_bootstrap_operation_id = NEW.anchor_bootstrap_operation_id + AND original.partition_id = NEW.partition_id) + OR NOT gs_issuer_local_operation_has_exact_source(NEW.operation_id) + OR gs_issuer_local_operation_has_exact_retirement(NEW.operation_id) THEN + RAISE EXCEPTION 'Issuer current membership requires its exact unretired immutable source' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF NOT gs_issuer_local_operation_has_exact_retirement(OLD.operation_id) THEN + RAISE EXCEPTION 'Issuer current membership deletion requires exact committed original retirement' + USING ERRCODE = '23514'; + END IF; + RETURN OLD; +END; +$$; + +CREATE FUNCTION gs_register_issuer_current_local_operation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + INSERT INTO game_session_canonical_issuer_current_local_operation + (operation_id, issuer_id, anchor_bootstrap_operation_id, partition_id) + VALUES (NEW.operation_id, NEW.issuer_id, NEW.anchor_bootstrap_operation_id, NEW.partition_id); + RETURN NEW; +END; +$$; + +CREATE FUNCTION gs_retire_issuer_current_local_operation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + -- The existing BEFORE guard has already required this exact original mutation/absence proof. + IF OLD.status = 'PENDING_PHYSICAL_PROOF' AND NEW.status = 'RETIRED' THEN + DELETE FROM game_session_canonical_issuer_current_local_operation current + USING game_session_canonical_issuer_binding_local_operation original + WHERE original.operation_id = NEW.original_local_operation_id + AND original.anchor_issuer_coverage_operation_id = NEW.anchor_issuer_coverage_operation_id + AND current.operation_id = original.operation_id + AND current.issuer_id = NEW.issuer_id + AND current.anchor_bootstrap_operation_id = original.anchor_bootstrap_operation_id + AND current.partition_id = NEW.partition_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Completed issuer retirement lost its exact current original membership' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION gs_check_issuer_reservation_current_membership() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF EXISTS (SELECT 1 FROM game_session_canonical_issuer_installed_anchor + WHERE issuer_id = OLD.issuer_id) THEN + RAISE EXCEPTION 'Installed issuer reservation history must be retained' + USING ERRCODE = '23514'; + END IF; + ELSE + PERFORM gs_require_issuer_reservation_current_membership(NEW.reservation_id); + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION gs_check_installed_issuer_reservation_membership() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + reservation record; +BEGIN + -- First installation alone qualifies the complete baseline. Ordinary writes use point checks. + FOR reservation IN + SELECT reservation_id FROM game_session_canonical_issuer_partition_reservation + WHERE issuer_id = NEW.issuer_id + LOOP + PERFORM gs_require_issuer_reservation_current_membership(reservation.reservation_id); + END LOOP; + RETURN NULL; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_current_local_operation_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_issuer_current_local_operation + FOR EACH ROW EXECUTE FUNCTION gs_guard_issuer_current_local_operation(); +CREATE TRIGGER trg_gs_issuer_current_local_operation_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_current_local_operation + FOR EACH STATEMENT EXECUTE FUNCTION gs_guard_issuer_current_local_operation(); +CREATE TRIGGER trg_gs_issuer_current_local_operation_register + AFTER INSERT ON game_session_canonical_issuer_binding_local_operation + FOR EACH ROW EXECUTE FUNCTION gs_register_issuer_current_local_operation(); +CREATE TRIGGER trg_gs_issuer_current_local_operation_retire + AFTER UPDATE ON game_session_canonical_issuer_binding_local_retirement + FOR EACH ROW EXECUTE FUNCTION gs_retire_issuer_current_local_operation(); +CREATE CONSTRAINT TRIGGER trg_gs_issuer_reservation_current_membership + AFTER INSERT OR UPDATE OR DELETE ON game_session_canonical_issuer_partition_reservation + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION gs_check_issuer_reservation_current_membership(); +CREATE CONSTRAINT TRIGGER trg_gs_installed_issuer_reservation_membership + AFTER INSERT ON game_session_canonical_issuer_installed_anchor + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION gs_check_installed_issuer_reservation_membership(); + +CREATE TRIGGER trg_gs_issuer_reservation_membership_clock + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_issuer_partition_reservation + FOR EACH STATEMENT EXECUTE FUNCTION gs_lock_issuer_current_membership_clock(); +CREATE TRIGGER trg_gs_issuer_local_operation_membership_clock + BEFORE INSERT ON game_session_canonical_issuer_binding_local_operation + FOR EACH STATEMENT EXECUTE FUNCTION gs_lock_issuer_current_membership_clock(); +CREATE TRIGGER trg_gs_issuer_retirement_membership_clock + BEFORE UPDATE ON game_session_canonical_issuer_binding_local_retirement + FOR EACH STATEMENT EXECUTE FUNCTION gs_lock_issuer_current_membership_clock(); +CREATE TRIGGER trg_gs_installed_issuer_membership_clock + BEFORE INSERT ON game_session_canonical_issuer_installed_anchor + FOR EACH STATEMENT EXECUTE FUNCTION gs_lock_issuer_current_membership_clock(); +CREATE TRIGGER trg_gs_issuer_current_membership_clock + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_issuer_current_local_operation + FOR EACH STATEMENT EXECUTE FUNCTION gs_lock_issuer_current_membership_clock(); +-- [jooq ignore stop] + +COMMENT ON TABLE game_session_canonical_issuer_current_local_operation IS + 'Positive bounded current references maintained at immutable local-operation insertion and exact original physical retirement; immutable history and existing inventory remain authoritative.'; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java index 092c886ee6..61af829daa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -32,9 +32,12 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.ExecuteContext; import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -562,10 +565,16 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { var anchor = initialCoverageOwner(dsl, () -> state) .completeInitialBootstrap(intent.operationId(), intent.requestId()); + // This historical phase has no V1038.5 membership table. Adapt only its slot-count read; + // registration still uses the actual owner and all enabled old-schema guards. This does not + // qualify the new membership gate before that schema exists. + AtomicInteger oldPhaseSlotCountSubstitutions = new AtomicInteger(); var local = - new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> state) + new CanonicalGameplayIssuerBindingLocalOperationRepository( + preMembershipLocalProducer(dsl, oldPhaseSlotCountSubstitutions), () -> state) .beginOrResumeOrdinaryNew( request("migration-request", "migration-transition", identity("migration"))); + assertThat(oldPhaseSlotCountSubstitutions.get()).isEqualTo(1); UUID committedId = UUID.randomUUID(); UUID pendingId = UUID.randomUUID(); UUID successor = UUID.randomUUID(); @@ -637,6 +646,11 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { String beforeAnchor = anchorImage(dsl); String beforeProof = proofImage(dsl); migrateRemaining(schema); + assertThat( + dsl.fetch( + "SELECT operation_id FROM game_session_canonical_issuer_current_local_operation") + .getValues(0, UUID.class)) + .containsExactly(local.operationId()); assertThat( dsl.fetch( "SELECT (to_jsonb(mutation) - 'bootstrap_operation_id')::text" @@ -697,6 +711,40 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { .allSatisfy(definition -> assertThat(definition).contains("bootstrap_operation_id")); } + private static DSLContext preMembershipLocalProducer( + DSLContext dsl, AtomicInteger substitutions) { + String currentSlotCount = + "SELECT count(*) FROM game_session_canonical_issuer_current_local_operation membership" + + " JOIN game_session_canonical_issuer_binding_local_operation operation" + + " ON operation.operation_id = membership.operation_id" + + " WHERE membership.issuer_id = ? AND membership.anchor_bootstrap_operation_id = ?" + + " AND membership.partition_id = ?"; + String oldSlotCount = + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_operation operation" + + " WHERE operation.issuer_id = ? AND operation.anchor_bootstrap_operation_id = ?" + + " AND operation.partition_id = ?" + + " AND NOT EXISTS (SELECT 1 FROM game_session_canonical_issuer_binding_local_retirement retirement" + + " WHERE retirement.original_local_operation_id = operation.operation_id" + + " AND retirement.status = 'RETIRED')"; + var configuration = dsl.configuration().derive(); + configuration.set( + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void renderEnd(ExecuteContext context) { + String sql = context.sql(); + if (currentSlotCount.equals(sql)) { + substitutions.incrementAndGet(); + context.sql(oldSlotCount); + } else if (sql != null + && sql.contains("game_session_canonical_issuer_current_local_operation")) { + throw new AssertionError("Unexpected membership read in the pre-V1038.5 producer"); + } + } + })); + return DSL.using(configuration); + } + private static void insertPreLineageMutation( DSLContext transaction, UUID mutationId, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index f81d726d53..31156f1e82 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; +import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @@ -55,6 +56,7 @@ protected GenericContainer redis() { @Test void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exception { try (var fixture = newFixture()) { + assertThat(currentOperationIds(fixture.dsl())).containsExactly(fixture.originalOperationId()); byte[] partitionKey = fixture.issuerPartitionKey(); byte[] initialFields = physicalFieldSet(partitionKey); int baselineFieldCount = @@ -114,6 +116,7 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc assertThat(retirementCount(fixture.dsl())).isZero(); var originalRelease = completeReleaseAfterLostReply(fixture, null); + assertThat(currentOperationIds(fixture.dsl())).containsExactly(fixture.originalOperationId()); String newerSeed = lifetimeSeed(2); UUID newerOperationId = fixture.prepareOtherControllerNew(newerSeed); @@ -121,6 +124,9 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc UUID neverProjectedOperationId = fixture.prepareOtherControllerNew(neverProjectedSeed); var neverProjectedOperation = fixture.otherOperation(neverProjectedSeed); var newerOperation = fixture.otherOperation(newerSeed); + assertThat(currentOperationIds(fixture.dsl())) + .containsExactlyInAnyOrder( + fixture.originalOperationId(), newerOperationId, neverProjectedOperationId); assertThat(neverProjectedOperationId).isEqualTo(neverProjectedOperation.operationId()); assertThat(neverProjectedOperation.reservation().partitionId()) .isEqualTo(newerOperation.reservation().partitionId()); @@ -237,6 +243,10 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc LuaInvocation oldestRetirementInvocation = retirementInvocation(fixture, pendingOldestRetirement); + List membershipBeforeRetirement = currentOperationIds(fixture.dsl()); + assertThat(membershipBeforeRetirement) + .containsExactlyInAnyOrder( + fixture.originalOperationId(), newerOperationId, neverProjectedOperationId); long operationCountBeforeBlockedAdmission = localOperationCount(fixture.dsl()); assertThatThrownBy(() -> fixture.prepareOtherControllerNew("pending-retirement-blocked")) .isInstanceOf(IllegalStateException.class) @@ -269,6 +279,49 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc beforeOldestRetirement, afterUncommittedRetirement, pendingOldestRetirement); assertThat(retirementStatus(fixture.dsl(), pendingOldestRetirement.operationId())) .isEqualTo("PENDING_PHYSICAL_PROOF"); + assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBeforeRetirement); + + // Exercise the actual SQL completion and automatic membership removal, then abort the + // transaction. Physical absence alone must not make the original cease to be current. + assertThatThrownBy( + () -> + fixture + .dsl() + .transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision( + transaction); + CanonicalGameplayIssuerPartitionMutationRepository + .completeInTransaction( + transaction, + pendingOldestRetirement.physicalMutation(), + afterUncommittedRetirement); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_binding_local_retirement" + + " SET status = 'RETIRED'," + + " exact_absence_readback_field_set_bytes = ?," + + " exact_absence_readback_field_set_digest = ?," + + " completed_at = CURRENT_TIMESTAMP" + + " WHERE retirement_operation_id = ?", + afterUncommittedRetirement, + CanonicalGameplayIssuerMemberV2Codec.sha256( + afterUncommittedRetirement), + pendingOldestRetirement.operationId())) + .isOne(); + assertThat(currentOperationIds(transaction)) + .containsExactlyInAnyOrder( + newerOperationId, neverProjectedOperationId); + throw new IllegalStateException( + "controlled retirement completion rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("controlled retirement completion rollback"); + assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBeforeRetirement); + assertThat(retirementStatus(fixture.dsl(), pendingOldestRetirement.operationId())) + .isEqualTo("PENDING_PHYSICAL_PROOF"); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(afterUncommittedRetirement); var resumedOldestRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); assertThat(resumedOldestRetirement.operationId()) @@ -278,6 +331,8 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc assertThat(resumedOldestRetirement.physicalMutation().successorRevision()) .isEqualTo(pendingOldestRetirement.physicalMutation().successorRevision()); var recoveredOldestProof = fixture.retireIssuerCapacity(resumedOldestRetirement); + assertThat(currentOperationIds(fixture.dsl())) + .containsExactlyInAnyOrder(newerOperationId, neverProjectedOperationId); assertThat(recoveredOldestProof.scriptOutcome()).isEqualTo(2L); assertThat(recoveredOldestProof.exactAbsenceReadbackFieldSetBytes()) .isEqualTo(afterUncommittedRetirement); @@ -293,6 +348,8 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc assertThat(completedOldestRetirement.status()) .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); var completedOldestRetryProof = fixture.retireIssuerCapacity(completedOldestRetirement); + assertThat(currentOperationIds(fixture.dsl())) + .containsExactlyInAnyOrder(newerOperationId, neverProjectedOperationId); assertThat(completedOldestRetryProof.scriptOutcome()).isEqualTo(2L); assertThat(completedOldestRetryProof.exactAbsenceReadbackFieldSetBytes()) .isEqualTo(beforeCompletedRetirementRetry); @@ -323,9 +380,12 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc .isEqualTo(beforeNewerRetirementRetry); assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeNewerRetirementRetry); + assertThat(currentOperationIds(fixture.dsl())).containsExactly(neverProjectedOperationId); for (int index = 3; index <= 256; index++) { String seed = lifetimeSeed(index); - fixture.prepareOtherControllerNew(seed); + UUID cycleOperationId = fixture.prepareOtherControllerNew(seed); + assertThat(currentOperationIds(fixture.dsl())) + .containsExactlyInAnyOrder(neverProjectedOperationId, cycleOperationId); assertThat(fixture.projectOtherControllerNew(seed).scriptOutcome()).isEqualTo(1L); fixture.publishOtherControllerNew(seed); assertThat(fixture.recordOtherAccountAbort(seed).isAccountAborted()).isTrue(); @@ -341,6 +401,7 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc var pendingCycleRetirement = fixture.prepareIssuerRetirement(transitionId); byte[] beforeCycleRetirement = physicalFieldSet(partitionKey); var cycleRetirement = fixture.retireIssuerCapacity(pendingCycleRetirement); + assertThat(currentOperationIds(fixture.dsl())).containsExactly(neverProjectedOperationId); byte[] afterCycleRetirement = physicalFieldSet(partitionKey); assertThat(cycleRetirement.scriptOutcome()).isEqualTo(1L); assertThat(cycleRetirement.exactAbsenceReadbackFieldSetBytes()) @@ -351,6 +412,7 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc assertThat(decodeFields(afterCycleRetirement).size()).isEqualTo(baselineFieldCount + 2); } + assertThat(currentOperationIds(fixture.dsl())).containsExactly(neverProjectedOperationId); assertThat(localOperationCount(fixture.dsl())).isEqualTo(257L); assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(256L); assertThat(releaseProofCount(fixture.dsl())).isEqualTo(256L); @@ -360,6 +422,8 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc String newSeed = lifetimeSeed(257); UUID newOperationId = fixture.prepareOtherControllerNew(newSeed); + assertThat(currentOperationIds(fixture.dsl())) + .containsExactlyInAnyOrder(neverProjectedOperationId, newOperationId); var finalPendingAdd = fixture.prepareOtherAddMutation(newSeed); LuaInvocation staleFinalAddInvocation = addInvocation(fixture, finalPendingAdd); var finalAddReadback = fixture.projectOtherControllerNew(newSeed); @@ -409,6 +473,7 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc .isEqualTo(beforeFinalRetirementRetry); assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeFinalRetirementRetry); + assertThat(currentOperationIds(fixture.dsl())).containsExactly(neverProjectedOperationId); assertThat(localOperationCount(fixture.dsl())).isEqualTo(258L); assertThat(releaseCount(fixture.dsl(), "RELEASED")).isEqualTo(257L); assertThat(releaseProofCount(fixture.dsl())).isEqualTo(257L); @@ -540,8 +605,7 @@ void retirementRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws E } @Test - void postRetirementProjectionRejectsUnaccountedCurrentReservationInAnotherPartition() - throws Exception { + void postRetirementSqlRejectsUnaccountedCurrentReservationInAnotherPartition() throws Exception { try (var fixture = newFixture(BigInteger.valueOf(7), BigInteger.TWO, 0)) { fixture.publishOriginalWithControlledAccountLease(); assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); @@ -550,63 +614,171 @@ void postRetirementProjectionRejectsUnaccountedCurrentReservationInAnotherPartit assertThat(fixture.completeIssuerRelease(release, releaseReadback).status()) .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); var pendingRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); - var retired = fixture.retireIssuerCapacity(pendingRetirement); - assertThat(retired.scriptOutcome()).isEqualTo(1L); + assertThat(fixture.retireIssuerCapacity(pendingRetirement).scriptOutcome()).isEqualTo(1L); BigInteger retiredPartition = fixture.originalPartitionId(); BigInteger otherPartition = retiredPartition.equals(BigInteger.ZERO) ? BigInteger.ONE : BigInteger.ZERO; String otherPartitionSeed = "cross-partition-current"; - fixture.prepareOtherControllerNewInPartition(otherPartitionSeed, otherPartition); + UUID otherOperationId = + fixture.prepareOtherControllerNewInPartition(otherPartitionSeed, otherPartition); assertThat(fixture.projectOtherControllerNew(otherPartitionSeed).scriptOutcome()) .isEqualTo(1L); - String pendingTargetSeed = "cross-partition-drift-target"; UUID pendingTargetOperationId = fixture.prepareOtherControllerNew(pendingTargetSeed); - var pendingTarget = fixture.otherOperation(pendingTargetSeed); - byte[] retiredPartitionKey = fixture.issuerPartitionKey(); - byte[] otherPartitionKey = fixture.issuerPartitionKey(otherPartitionSeed); - byte[] retiredPartitionBefore = physicalFieldSet(retiredPartitionKey); - byte[] otherPartitionBefore = physicalFieldSet(otherPartitionKey); - String pendingTargetBefore = localOperationImage(fixture.dsl(), pendingTargetOperationId); - String otherPartitionHeadBefore = partitionHeadImage(fixture.dsl(), otherPartition); - UUID unaccountedReservationId = - insertUnaccountedCurrentReservation(fixture, otherPartitionSeed, otherPartition); - String unaccountedReservationBefore = - reservationImage(fixture.dsl(), unaccountedReservationId); + byte[] retiredPartitionBefore = physicalFieldSet(fixture.issuerPartitionKey()); + byte[] otherPartitionBefore = + physicalFieldSet(fixture.issuerPartitionKey(otherPartitionSeed)); + String historyBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); + List membershipBefore = currentOperationIds(fixture.dsl()); String retiredAuditBefore = retirementImage(fixture.dsl(), fixture.transitionId()); + long reservationsBefore = reservationCount(fixture.dsl()); - assertThatThrownBy(() -> fixture.projectOtherControllerNew(pendingTargetSeed)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Durable issuer reservations differ"); - - assertThat(physicalFieldSet(retiredPartitionKey)).isEqualTo(retiredPartitionBefore); - assertThat(physicalFieldSet(otherPartitionKey)).isEqualTo(otherPartitionBefore); - assertThat(localOperationImage(fixture.dsl(), pendingTargetOperationId)) - .isEqualTo(pendingTargetBefore); - assertThat(partitionHeadImage(fixture.dsl(), otherPartition)) - .isEqualTo(otherPartitionHeadBefore); - assertThat(reservationImage(fixture.dsl(), unaccountedReservationId)) - .isEqualTo(unaccountedReservationBefore); + assertThatThrownBy( + () -> + insertUnaccountedCurrentReservation(fixture, otherPartitionSeed, otherPartition)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining( + "Installed issuer reservation requires exact bootstrap or current local-operation membership"); + + assertThat(reservationCount(fixture.dsl())).isEqualTo(reservationsBefore); + assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBefore); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(historyBefore); assertThat(retirementImage(fixture.dsl(), fixture.transitionId())) .isEqualTo(retiredAuditBefore); - assertThat(retirementStatus(fixture.dsl(), pendingRetirement.operationId())) - .isEqualTo("RETIRED"); - assertThat(retirementCount(fixture.dsl())).isEqualTo(1L); - assertThat(releaseProofCount(fixture.dsl())).isEqualTo(1L); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT count(*) FROM game_session_canonical_issuer_partition_mutation" - + " WHERE owner_operation_id = ? AND mutation_kind = 'ADD_CAPACITY'", - pendingTargetOperationId) - .get(0, Long.class)) - .isZero(); - assertThat(pendingTarget.reservation().partitionId()).isEqualTo(retiredPartition); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(retiredPartitionBefore); + assertThat(physicalFieldSet(fixture.issuerPartitionKey(otherPartitionSeed))) + .isEqualTo(otherPartitionBefore); + assertThat(currentOperationIds(fixture.dsl())) + .containsExactlyInAnyOrder(otherOperationId, pendingTargetOperationId); + // A refused orphan transaction cannot poison the next legitimate same-anchor operation. + assertThat(fixture.projectOtherControllerNew(pendingTargetSeed).scriptOutcome()) + .isEqualTo(1L); } } + @Test + void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceMismatch() { + try (var fixture = newFixture(BigInteger.valueOf(3), BigInteger.ONE, 1)) { + UUID originalId = fixture.originalOperationId(); + List membershipBefore = currentOperationIds(fixture.dsl()); + String originalBefore = localOperationImage(fixture.dsl(), originalId); + String historyBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_current_local_operation WHERE operation_id = ?", + originalId)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("exact committed original retirement"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_current_local_operation" + + " SET partition_id = partition_id WHERE operation_id = ?", + originalId)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("cannot be updated or truncated"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("TRUNCATE game_session_canonical_issuer_current_local_operation")) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("cannot be updated or truncated"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_current_local_operation" + + " (operation_id, issuer_id, anchor_bootstrap_operation_id, partition_id)" + + " SELECT operation_id, issuer_id, anchor_bootstrap_operation_id, partition_id + 1" + + " FROM game_session_canonical_issuer_binding_local_operation WHERE operation_id = ?", + originalId)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("exact unretired immutable source"); + assertThatThrownBy( + () -> + fixture + .dsl() + .transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + // The write itself succeeds; the reverse guard checks the committed + // postimage. + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation reservation" + + " SET coverage_fence = coverage_fence + 1" + + " FROM game_session_canonical_issuer_binding_local_operation original" + + " WHERE original.operation_id = ?" + + " AND reservation.reservation_id = original.reservation_id", + originalId)) + .isOne(); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("exact installed local-operation source"); + assertThatThrownBy( + () -> + fixture + .dsl() + .transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + // A seeded bootstrap reservation is also bound to its complete frozen + // owner + // and coverage tuple, rather than being admitted by reservation + // identity alone. + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation reservation" + + " SET coverage_fence = coverage_fence + 1" + + " FROM game_session_canonical_issuer_installed_anchor anchor" + + " JOIN game_session_canonical_issuer_partition_build_cohort_row cohort" + + " ON cohort.build_operation_id = anchor.build_operation_id" + + " AND cohort.source_operation_id = anchor.bootstrap_operation_id" + + " AND cohort.issuer_id = anchor.issuer_id" + + " AND cohort.source_kind = 'RESERVATION'" + + " WHERE reservation.reservation_id::text = cohort.source_key")) + .isOne(); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining( + "Installed issuer reservation requires exact bootstrap or current local-operation membership"); + assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBefore); + assertThat(localOperationImage(fixture.dsl(), originalId)).isEqualTo(originalBefore); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(historyBefore); + } + } + + private static List currentOperationIds(DSLContext dsl) { + // Execute the positive current partition lookup used by the projection, rather than deriving + // currentness by subtracting retained RETIRED history in the test. + return dsl.fetch( + "SELECT current.operation_id FROM game_session_canonical_issuer_current_local_operation current" + + " JOIN game_session_canonical_issuer_installed_anchor anchor" + + " ON anchor.issuer_id = current.issuer_id" + + " AND anchor.bootstrap_operation_id = current.anchor_bootstrap_operation_id" + + " JOIN game_session_canonical_issuer_partition_mutation_head head" + + " ON head.issuer_id = current.issuer_id" + + " AND head.bootstrap_operation_id = current.anchor_bootstrap_operation_id" + + " AND head.partition_id = current.partition_id" + + " WHERE anchor.issuer_id = 'firemud-account-service'" + + " ORDER BY current.operation_id") + .getValues("operation_id", UUID.class); + } + + private static long reservationCount(DSLContext dsl) { + return dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_partition_reservation") + .get(0, Long.class); + } + private static String retirementImage(DSLContext dsl, UUID transitionId) { return dsl.fetchSingle( "SELECT to_jsonb(retirement)::text FROM" From e877e32f75624fa1ea2c88e5c52444d920912ae7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:19:27 +1300 Subject: [PATCH 2/9] Complete settlement successor and preserve Entity runtime source --- .../api-contracts.md | 6 + .../runtime-and-data.md | 16 +- ...system-architecture-identifier-glossary.md | 2 +- design/project-management/ai-observations.md | 6 + .../gameplay-rules-entities-and-effects.md | 3 +- .../player-access-and-session.md | 6 +- .../v1/preseeded_actor_assignment.proto | 29 ++ ...lAdmissionSettlementReadGrpcCodecTest.java | 251 +------------ ...nitialAdmissionSettlementTestFixtures.java | 240 ++++++++++++ ...ssionProtectionSettlementEvidenceTest.java | 14 +- ...tialAdmissionSettlementReadClientTest.java | 12 +- .../repository/CharacterRepository.java | 21 ++ ...eededActorRuntimeProjectionRepository.java | 70 ++++ ...eseededActorAssignmentPeerInterceptor.java | 27 +- ...reseededActorAssignmentReceiptService.java | 6 + .../PreseededActorRuntimeReference.java | 20 + .../service/RuntimeEntityId.java | 10 + ...alPreseededActorAssignmentGrpcService.java | 74 ++++ .../PreseededActorAssignmentGrpcCodec.java | 39 ++ ...22__preseeded_runtime_actor_projection.sql | 50 +++ ...eseededActorAssignmentIntegrationTest.java | 270 +++++++++++++- ...nerCompositionPostgresIntegrationTest.java | 124 +++++++ .../RetainedActorIdentityIntegrationTest.java | 16 +- ...haracterCreatePostgresIntegrationTest.java | 6 +- ...osterRetentionPostgresIntegrationTest.java | 146 ++++++-- ...ntakeMigrationPostgresIntegrationTest.java | 2 +- ...dedActorAssignmentPeerInterceptorTest.java | 39 ++ ...eseededActorAssignmentGrpcServiceTest.java | 176 +++++++++ ...lPreseededActorRuntimeReferenceClient.java | 344 ++++++++++++++++++ ...mpletion_exact_original_launch_binding.sql | 98 +++++ ...ent_issuer_local_operation_membership.sql} | 0 ...ession-issuer-binding-local-retirement.lua | 2 +- ...ssion-issuer-binding-local-retirement.json | 2 +- ...calOperationRepositoryIntegrationTest.java | 5 +- ...suerPhysicalRetirementIntegrationTest.java | 75 +++- ...rotectedWriterPostgresIntegrationTest.java | 194 ++++++++++ ...edActorRuntimeReferenceClientMtlsTest.java | 235 ++++++++++++ ...seededActorRuntimeReferenceClientTest.java | 224 ++++++++++++ ...nical_initial_hold_precondition_status.sql | 26 ++ ...ationOwnerCompositionCrossServiceTest.java | 2 +- 40 files changed, 2592 insertions(+), 296 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementTestFixtures.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorRuntimeReference.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeEntityId.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1040.4__human_completion_exact_original_launch_binding.sql rename services/game-session-service/src/main/resources/db/migration/{V1038.5__current_issuer_local_operation_membership.sql => V1040.5__current_issuer_local_operation_membership.sql} (100%) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V1044.1__canonical_initial_hold_precondition_status.sql diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 475ad882fa..fffabe5458 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -100,6 +100,12 @@ The response reports the existing persisted assignment operation UUID, intent di This read authenticates historical assignment provenance only. It does not revalidate current Account eligibility, settle a protection, grant `PLAY`, initialize location or activate a runtime. World independently owns the [initial placement boundary](../world-management-service/api-contracts.md#canonical-initial-player-location). +## Initial runtime actor reference + +`CanonicalPreseededActorAssignmentService.ReadPreseededActorRuntimeReference` is a distinct read for the exact same-namespace Game Session workload. It loads the actual Entity-owned projection for the original assignment, full expected target and character; it never allocates or backfills a missing projection. The [Entity runtime projection owner](./runtime-and-data.md#initial-runtime-actor-projection-and-reference) defines allocation, uniqueness, retained generations and nonreuse. The response carries that typed scoped numeric runtime identity, projection generation/fence and complete original assignment provenance in a closed bounded envelope. The existing assignment and World-only receipt messages retain their character-UUID semantics and immutable bytes. + +The service authenticates this method's Game Session peer before selector decoding, rejects unknown or malformed fields and mismatched scope/provenance, and bounds both request and response at its manual transport boundary. It returns no reference for missing, stale or contradictory projection state and exposes no general entity lookup. The method's narrow manual composition does not register a production handler, authorize an unsupported replacement or confer placement, region ownership, player admission or activation. Game Session independently joins its [World initial-location read](../world-management-service/api-contracts.md#canonical-initial-player-location) and current region lease before using the reference in a binding bridge. + ## Player-created roster and selected character `CanonicalGameplayRosterService.ListPlayerCreatedRoster(CanonicalPlayerCreatedRosterRequest)` and `ReadSelectedPlayerCreatedCharacter(CanonicalSelectedPlayerCreatedCharacterRequest)` are distinct non-admitting Entity owner reads. They require the exact authenticated same-namespace Game Session workload over mTLS and a closed `PlayerExecutionContext` whose operation, account, session, tenant, realm, playable namespace/scope and runtime instance agree with the request and full target. Listing has no selected actor; selected readback requires `context.character_id` to equal the requested actor. Entity independently obtains and compares the complete current published `PLAYER_CREATED` source, descriptor, policy, canonical version and `SHARED` target before local work. Missing, changed or unsupported source evidence fails closed. `ListPreseededRoster` and `ReadSelectedPreseededAssignment` remain strictly `PRESEEDED_ONLY`; `AUTO_PROVISIONED` is unsupported by these roster methods. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index b71f7c1a16..cd7dcaf053 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -362,7 +362,7 @@ Copies into an isolated playtest namespace allocate a new fork-local `characterI ### Runtime Actor Identity -Entity Management owns one persisted runtime actor for every active gameplay being. `actorId` is an opaque canonical gameplay-facing identity; services must not substitute composite reference strings such as `PLAYER:` or re-derive different player/NPC identity forms at each boundary. +Entity Management owns one persisted runtime actor for every active gameplay being. In the target runtime projection, its actor identity is the typed numeric `runtimeEntityId`, scoped by `{tenantId, gameInstanceId}` as defined by the [identifier glossary](../../system-architecture-identifier-glossary.md). It is separate from the durable character UUID scoped by `{tenantId, playableStateNamespaceId}`. An older transport's `actorId` or character UUID is not silently reinterpreted as this runtime identity; services must not substitute private character row keys, parse or hash UUIDs, invent composite references such as `PLAYER:`, or introduce another opaque alias for the same runtime actor. - The actor core carries `tenantId`, `playableStateNamespaceId`, `gameInstanceId`, the resolved `playableStateScope` when it represents durable playable state, `actorKind`, display name, and presence state. It does not persist universal targetability or visibility fields. - A `PLAYER` actor is a runtime projection of the persisted actor and is unique for the active `{tenantId, playableStateNamespaceId, gameInstanceId, characterId}` execution context; it does not replace the canonical durable actor storage key `{tenantId, playableStateNamespaceId, characterId}` or turn separately validated `playableStateScope` into an identity dimension. `gameInstanceId` remains the replaceable runtime target/fence, and this S3 projection may be recreated during replacement while preserving the namespace-backed character. Disconnect/reconnect changes presence on the projection rather than creating a replacement durable identity. @@ -381,6 +381,18 @@ For published targeting predicates whose facts it owns, Entity Management expose Character and NPC records remain the durable domain records for their respective variants. The runtime actor links those records into one gameplay subject model; it does not replace character progression, authored NPC definitions, or World Management location state. +### Initial Runtime Actor Projection and Reference + +The Entity-owned initial runtime projection is allocated only through the exact applicable authenticated assignment owner chain after its current authorization and target checks. Its complete unique association is `{tenantId, playableStateNamespaceId, gameInstanceId, characterId}`. The durable projection retains the original assignment operation, receipt and intent digest, complete target, projection fence and projection generation. Existing assignment, placement and roster character-UUID fields and immutable receipt bytes remain unchanged. For this projection boundary, the durable Entity `entity_runtime_entity_id_sequence` is the sole allocator. Adopting another canonical allocator requires an explicit migration that preserves uniqueness and nonreuse; allocator unavailability never authorizes runtime fallback to another allocator. A private database row key is never promoted into this role. + +Allocation guarantees concurrent uniqueness, stable exact retry and restart, and nonreuse throughout the required runtime and retention lifetime. Reconnect alone does not replace the projection. Runtime replacement is target state: the replacement owner allocates a new projection generation and runtime ID while retaining and fencing the previous association. A controlled source cannot authorize production allocation. Allocation alone establishes neither World placement, an active lifecycle, a Game Session region lease nor admission. + +The `entity_preseeded_actor_runtime_projections` runtime identity is S3 for instance-lifecycle partitioning. Its immutable assignment association and provenance remain recovery and nonreuse lineage subject to the canonical reference, hold, and retention rules; this classification grants no deletion permission or numeric retention horizon. V1022 currently permits initial projections only: its assignment and association uniqueness constraints and its update, delete, and truncate guards prevent replacement. Implementing the target replacement transition requires forward schema evolution and the qualified replacement-owner chain while preserving retained associations and nonreuse. Entity has not registered this family with World Management or defined its termination disposition and cleanup acknowledgement, so room-ground cleanup does not cover it and whole-instance `TERMINATED` remains blocked until lifecycle registration and retention/cleanup proof exist. See [Instance Termination Cleanup Contract](#instance-termination-cleanup-contract), [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md), [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md), and the [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#active-gaps). + +The existing assignment service exposes one separate purpose-specific runtime-reference read to the exact same-namespace Game Session workload. It selects the original assignment, complete target and character, loads the actual retained projection, and returns a closed bounded typed reference with its full owner-qualified association, original assignment provenance, projection fence and generation. The read never allocates or repairs missing projection state, and an unavailable, stale or contradictory source fails closed. The World-only immutable assignment-receipt read retains its distinct purpose and authority. + +Game Session may join this reference to a region binding only after its independent exact World-applied initial placement, current region/lifecycle and actual region lease/fence checks. It must revalidate the original assignment, projection generation and expected epoch before the decisive bridge and final admission CAS. World location, Redis possession and supplied reference fields cannot create Entity authority. This narrow producer/read boundary grants no general entity lookup, public character creation, production registration, PKI custody or runtime activation. + ### Containment and Equipment Model Entity Management's target-state containment model is container-first: @@ -405,7 +417,7 @@ Equipment is intentionally not modeled as "just another bag position": - The complete-schema and fail-closed behavior in the following contract is target state, not current implementation; current missing-schema and unknown-layout bootstrap fallback gaps are recorded in the [Entity Management README](./README.md) and [Item & Equipment Balancing Tools](../game-design-service/item-equipment-balancing.md#target-equipment-schema-requirements). - Game Design owns the complete published equipment vocabulary/body-layout schema and its digest. Entity Management consumes that exact schema for occupancy and compatibility checks; all missing, partial, or mismatched vocabulary or mapping evidence is rejected and validation fails closed. It does not provide a platform-global slot fallback. Replacement cutover remaps bindings only through the owner-validated mapping contract; profiles materialize authored equipment content rather than supplying runtime defaults. See [ADR 0127](../../decisions/adr-0127-game-authored-equipment-layouts-with-fail-closed-publication.md). -The target inventory/equipment operation context for a durable holder or binding is `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, holderRef, itemInstanceId, itemDefinitionId, equipmentBindingId?, slotKey?}`, with one typed `holderRef` for each source, destination, or equipment owner required by the operation. A holder reference is a closed tagged union: character inventory or equipment carries `CHARACTER {characterId}`; NPC, pet, or summon ownership carries `ACTOR {actorId}`; an ordinary bag, chest, corpse, bank, vendor stock, or nested holder carries `CONTAINER {containerInstanceId}`; and room-ground storage carries `ROOM_GROUND {roomInstanceId, containerInstanceId}`. `characterId` is therefore required only for character-owned inventory or equipment and must not be fabricated for another holder kind. For namespace-backed S1/S2 inventory, character, and equipment state, durable storage identity is `{tenantId, playableStateNamespaceId, ...domainObjectId}` and omits both `playableStateScope` and `gameInstanceId`; those values are validated separately as immutable routing/authorization evidence and the active-instance fence. Cross-service effect participant replay/deduplication follows the owner-declared partition: S1/S2 uses `(tenantId, playableStateNamespaceId)`, while explicitly classified S3 uses `(tenantId, gameInstanceId)`. `requestDigest` is separately exact-validated conflict metadata, not a uniqueness dimension; for S1/S2, `playableStateScope` and active `gameInstanceId` are validation evidence rather than participant uniqueness. Other service-local idempotency keys remain operation-specific. Explicitly instance-scoped S3 holders include `gameInstanceId` in durable identity. Future proto and OpenAPI surfaces must carry the same typed holder-reference union consistently, but current surfaces do not yet carry this complete operation context on every inventory/equipment read or mutation, so this is a target contract only: this ADR parcel does not add wire fields, regenerate protos, or change runtime lookup behavior. See [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) for the canonical participant-guard contract. +The target inventory/equipment operation context for a durable holder or binding is `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, holderRef, itemInstanceId, itemDefinitionId, equipmentBindingId?, slotKey?}`, with one typed `holderRef` for each source, destination, or equipment owner required by the operation. A holder reference is a closed tagged union: character inventory or equipment carries `CHARACTER {characterId}`; NPC, pet, or summon ownership carries `ACTOR {runtimeEntityId}`, validated with `tenantId` and `gameInstanceId` under the current runtime fence; an ordinary bag, chest, corpse, bank, vendor stock, or nested holder carries `CONTAINER {containerInstanceId}`; and room-ground storage carries `ROOM_GROUND {roomInstanceId, containerInstanceId}`. `characterId` is therefore required only for character-owned inventory or equipment and must not be fabricated for another holder kind. For namespace-backed S1/S2 inventory, character, and equipment state, durable storage identity is `{tenantId, playableStateNamespaceId, ...domainObjectId}` and omits both `playableStateScope` and `gameInstanceId`; those values are validated separately as immutable routing/authorization evidence and the active-instance fence. Cross-service effect participant replay/deduplication follows the owner-declared partition: S1/S2 uses `(tenantId, playableStateNamespaceId)`, while explicitly classified S3 uses `(tenantId, gameInstanceId)`. `requestDigest` is separately exact-validated conflict metadata, not a uniqueness dimension; for S1/S2, `playableStateScope` and active `gameInstanceId` are validation evidence rather than participant uniqueness. Other service-local idempotency keys remain operation-specific. Explicitly instance-scoped S3 holders include `gameInstanceId` in durable identity. Future proto and OpenAPI surfaces must carry the same typed holder-reference union consistently, but current surfaces do not yet carry this complete operation context on every inventory/equipment read or mutation, so this is a target contract only: this ADR parcel does not add wire fields, regenerate protos, or change runtime lookup behavior. See [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) for the canonical participant-guard contract. This keeps the platform compatible with games that need unusual body plans or attachment models such as horns instead of hands, asymmetric limbs, species-specific slot topologies, or non-humanoid wearable layouts. diff --git a/design/architecture/system-architecture-identifier-glossary.md b/design/architecture/system-architecture-identifier-glossary.md index 1f51496309..2f688830dd 100644 --- a/design/architecture/system-architecture-identifier-glossary.md +++ b/design/architecture/system-architecture-identifier-glossary.md @@ -74,7 +74,7 @@ World Management may use a numeric room row key as `roomInstanceId` only when it ## Entity Identifiers -- `entityId` – identifies a live runtime entity (character, NPC, or container entity) within `(tenantId, gameInstanceId)` and may be a stable scoped number. Room-presence surfaces may present an item as an entity, but that presentation identity does not replace the typed `itemInstanceId` used by containment and equipment contracts. +- `entityId` – identifies a live runtime entity (character, NPC, or container entity) within `(tenantId, gameInstanceId)` and may be a stable scoped number. Room-presence surfaces may present an item as an entity, but that presentation identity does not replace the typed `itemInstanceId` used by containment and equipment contracts. The target Entity runtime actor projection calls this typed identity `runtimeEntityId`; that name does not introduce another identity or alias. Its association to the separate durable character UUID and original assignment is owned by [Entity Runtime and Data](./microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference). - `itemInstanceId` – identifies a concrete live item instance within `(tenantId, gameInstanceId)`. It is distinct from the item's `entityTemplateId` and from any `entityId` used by a generic runtime-entity surface, and may be a stable scoped number under the same allocation, stability, and non-reuse guarantees. - `entityTemplateId` – identifies a versioned entity template (items, NPC definitions, equipment templates) scoped by `(tenantId, versionId)` and is a UUID logical identity. - Stable numeric `entityId` values may be presented to authorized players as disambiguators and accepted in gameplay commands. Resolution still enforces tenant, game-instance, location/visibility, and authorization scope. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 6d9759f6a2..5c63f636f3 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -454,3 +454,9 @@ Entry format: - Context: The split issuer capacity/retirement proof shared static Testcontainers objects in an abstract fixture across two independently managed test classes. - Observation: The first class passed, but the retirement class could not start Redis on its mapped port; no retirement cases ran. The exact timeout cause remains unproved. - Expected pattern: Each concrete test class owns its own containers while sharing connection and SQL proof mechanics. Verify both classes together and retain the original failed aggregate before claiming receiving proof. + +- `2026-10-27`: Historical migration fixtures must not invoke a newly extended fresh writer + - Context: #3315 Entity CI failed all 46 roster-retention cases in shared setup. The fixture seeded at V1011 (and a legacy V1017 path) through the current assignment writer before upgrading; that writer now requires the V1022 runtime-projection table. + - Observation: the production migration was present and executed in other schema contexts. A controlled historical SQL seed preserves the old assignment receipt, actor and snapshot without manufacturing a runtime projection or moving the test to the latest frontier. Current-schema assignments retain the production writer. Later shutdown connection noise is separate and its cause remains unproven. + - Outcome: full Entity R722 executes 584 methods, with 519 passing, 46 failing on a missing placeholder in the new historical INSERT and 19 failing on separate PostgreSQL connection setup. R723 corrects only that placeholder and passes all 65 affected native cases with no skips; the 454 unit methods and other 65 native cases retain their R722 passing attribution. Enabled affected static analysis and formatting pass. The failed full-check aggregate remains recorded; the focused recovery does not relabel it as green. + - Expected pattern: retain the exact pre-upgrade schema, source rows and history in migration proof. Use explicitly historical fixture input when current Java requires a later schema; do not add production compatibility branches or backfill authority merely to seed a test. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 2a93c70094..142c6b4b78 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -245,6 +245,7 @@ The next review correction at code checkpoint `ce02d51f608f199e531de32c1d15f63cb ## Active Gaps +- Entity has not registered `entity_preseeded_actor_runtime_projections` with the World instance-lifecycle cleanup owner or defined its termination disposition and acknowledgement. Room-ground cleanup does not cover this S3 family, so whole-instance `TERMINATED` remains blocked until owner registration and retention/cleanup proof exist; the [Entity runtime contract](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) records its lineage and deletion boundary. - Accepted TICK-03 requires command-level required/optional effect classification and invariant-sensitive routing; current gameplay families do not yet provide complete classification or terminal-outcome proof. See [ADR 0053](../../architecture/decisions/adr-0053-command-atomicity-by-invariant-class.md) and its [tick failure/operations owner](../../architecture/system-architecture-tick-failures-and-operations.md). - Accepted TICK-04 remains an implementation and proof gap: current replay paths do not establish cross-service operation/target/request-digest-bound participant guards, causal read composition, stale-precondition handling, or mixed-floor handling. The canonical mutation identity, participant-guard, and root/child lineage rules are owned by [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and the [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); accepted generated-child allocation is defined in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); its implementation and proof remain incomplete. This tracker records implementation and proof status only. - [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md) accepts a causal floor plus actual opaque World/Entity component versions; current LOOK composition still has scope-marker compatibility behavior, bounded stale-floor retry, and final read-fence error mapping gaps. This tracker does not claim the accepted presentation identity is implemented. @@ -262,7 +263,7 @@ The next review correction at code checkpoint `ce02d51f608f199e531de32c1d15f63cb - The broad authored target-resolution and structured-outcome capability remains unimplemented and unproved beyond the self-targeted v1 path: cross-actor target sets, multi-effect composition, cross-region outcomes, and the wider typed primitive catalogue remain gaps. Canonical ownership is defined by [ADR 0112](../../architecture/decisions/adr-0112-typed-bounded-gameplay-effect-extension.md), with target-plan resolution in the [Game Logic API contracts](../../architecture/microservices/game-logic-service/api-contracts.md) and validated actor/effect mutation in the [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); this tracker records the current capability and proof gap only. - Reusable DML observation, targeting, and selection policies define `SOURCE` plus keyed target sets, `EXACTLY_ONE`, bounded `UP_TO_N`, or `ALL_ELIGIBLE` cardinality, and player-selected, canonical-order, ranked, or effect-id-seeded selection. Resolution records candidates, fact snapshots, policy identity, ranking or seed, selected targets, and owner fence/version tokens. Missing or stale facts fail closed; token mismatch re-resolves under the same effect id before mutation. - Resource costs and cooldowns remain future actor-state execution work. Game Design declarations carry typed costs, cooldowns, and `ON_EXECUTION` or `ON_EFFECT_SUCCESS` commit policy; Entity Management must atomically validate and consume resources, create durable cooldown records, and apply same-region effects under one idempotent effect id. Game Session timers are reconstructible wake-up projections, concurrent actions serialize at the authoritative mutation, queue acceptance consumes nothing, and cross-region failure has no implicit refund. Capacity changes use authored preserve/shift/clamp policy, and floor transitions are explicit one-shot lifecycle events rather than implicit death or victory semantics. -- No unified persisted actor runtime, NPC runtime actors, generic actor targeting/communication, or actor-state linkage exists. The locked core is an opaque `actorId` with tenant/game-instance context, `actorKind`, display name, presence state, and disposition, linking player actors to account/character and NPC actors to runtime instances; `PLAYER` and `NPC` are first kinds, with later `PET`/`SUMMON`, and gods/admins remain player overlays. +- Unified runtime actor support remains incomplete. The current bounded preseeded `PLAYER` projection uses typed numeric `runtimeEntityId` scoped by `{tenantId, gameInstanceId}`; [Entity Management runtime actor identity](../../architecture/microservices/entity-management-service/runtime-and-data.md#runtime-actor-identity) owns that canonical identity and projection contract. NPC runtime actors, generic actor targeting/communication, and actor-state linkage remain gaps. Future `PET`/`SUMMON` kinds extend the same core, while gods/admins remain player overlays. - Damage and mitigation implementation is absent, including typed damage packets, hit/mitigation ordering, resistances, action-gated defenses, combat timing, defeat/revival, corpse/loot, respawn, and victory policy. ## To Discuss 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 2a5769cae6..3cce1d5031 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components -The current-membership correction prepares forward V1038.5 and SQL-maintained references to original unretired local operations. Projection, capacity, slot registration, ADD-mutation reads and retirement conflict checks use current ownership rather than enumerating lifetime immutable history; pending-retirement validation starts from the bounded partition heads. Existing immutable provenance and exact owner checks remain required. The native retirement proof now checks current membership through pending/lost-reply/completion rollback/exact retry and more than 256 lifetime cycles. Its migration fixture adapts only the historical pre-membership slot-count read, retaining actual old-schema guards and post-upgrade backfill/current reads; it does not qualify a new gate before its schema exists. R974 is running on the six runtime/proof postimages; the separate historical-migration case and final receiving checks remain unrun at this preparation checkpoint. This does not establish registration, live issuer custody, activation or production admission. +The initial Entity runtime-actor producer and passive Game Session reference client are separated from the later World/region bootstrap consumer. Fresh authenticated preseeded assignment allocates the retained numeric runtime projection in its existing Entity transaction; the distinct exact Game Session read never allocates or backfills historical assignments. The producer retains its original receipt semantics, V1022 SQL postimage, migration fixtures, and focused owner/security proof. This receiving extraction has not yet been validated. Production registration, runtime replacement, lifecycle cleanup registration, region ownership, protected admission and activation remain unqualified; the [Entity runtime owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) defines the bounded contract. + +The current-membership correction prepares forward V1040.5 and SQL-maintained references to original unretired local operations. Projection, capacity, slot registration, ADD-mutation reads and retirement conflict checks use current ownership rather than enumerating lifetime immutable history; pending-retirement validation starts from the bounded partition heads. Existing immutable provenance and exact owner checks remain required. The native retirement proof now checks current membership through pending/lost-reply/completion rollback/exact retry and more than 256 lifetime cycles. Its migration fixture adapts only the historical pre-membership slot-count read, retaining actual old-schema guards and post-upgrade backfill/current reads; it does not qualify a new gate before its schema exists. R974 freshly passed 14 of its 15 selected native cases, including the 257-cycle turnover case, but failed aggregate validation on shared-layout fixture setup. R975 and R977 passed the historical-frontier upgrade/backfill case; their new negative-guard proof exposed assertion and SQL-qualification defects, corrected before R978 passed that guard case. V1040.5 passes the migration-frontier check after renumbering the unapplied correction above its parent. These passing executions cover 16 distinct membership-related native cases across the retained runs; the earlier failed aggregates remain failures, and final combined receiving validation remains pending. This does not establish registration, live issuer custody, activation or production admission. The next protected-settlement correction versions both sides of the closed response and aligns the SQL `EXPECT_CLOSED` negative terminal with the existing immutable-origin contract through forward V1040.3. R970 passes 31 focused codec/client/verifier/service unit cases and one actual World–Game Session–Account acquisition composition, with enabled affected analysis, formatting and migration-frontier checks. Its aggregate fails the new later-request extension because that fixture reuses the same original owner attempt, which V1006 correctly permits only once. After removing that invalid extension, R971 passes the focused native protected-abort case and integration analysis/formatting. The native case proves actual competing-intent refusal while the first request is pending, original terminal/read/replay and unchanged pointer/audit. Its positive current-origin refusal remains controlled: neither result proves independent pointer advancement before abort or later-OPEN recovery. The separate current-inventory/retained-history turnover correction remains unfinished. @@ -476,6 +478,8 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The ## Validation and Proof +The extracted Entity runtime-reference producer retains donor-source proof attribution from #3315 at `7e75bedd293d1c0ccc3450f73e906b1a1164a0b7`; extraction is not a new receiving validation result. The combined donor R890 run freshly passed 25 selected cases, including 19 Entity runtime-reference/assignment boundary units, but its aggregate failed Entity test SpotBugs on mutable failure capture. The other six cases covered region/protected-admission boundaries and remain with that source comparison rather than qualifying this producer. R891's attempted annotation correction failed compilation because the Entity test source set lacked the annotation dependency; no cases executed. After replacing the capture with immutable status-description and cause-presence snapshots, donor R893 freshly passed all 19 cases in [CanonicalPreseededActorAssignmentGrpcServiceTest](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java), including `runtimeReferenceMapsOnlyExplicitAvailabilityFailuresWithoutDisclosingOwnerDetails`, with zero failures, errors or skips. Enabled Entity test SpotBugs, formatting and documentation checks also passed in that donor run. These results preserve the disclosure and terminal-callback assertions without relabeling R890 or R891 as successful aggregates; they do not establish receiving validation, region recovery, production registration or activation. + The evidence records focused unit, controller, gRPC, WebSocket, cross-service, and restart/rebind proofs for text parsing and Telnet parity; real Account-backed generic login and authenticated `PLAY`; takeover, resume, logout, and replay cleanup; public-production membership idempotency; session-start IP ordering; malformed claim and positive-ID rejection; replay identity/payload mismatch; current REST/gRPC error envelopes; and Gateway upstream/process restart continuity. Earlier positive first-party handshake/reconnect proofs describe the superseded HMAC-cookie path and are historical. Current focused first-party tests cover denial and unavailable readiness; envelope, owner, retained-context, and consumer proofs remain bounded as recorded above and do not qualify production ingress. It does not yet prove the owner gRPC typed-result/non-OK classification across every adopter. The Telnet cross-service harness uses a lightweight Gateway stub only as a test fixture and has a successful `TelnetGatewayGameSessionCrossServiceIntegrationTest`; the maintained runtime path is not the stub. The focused admission proofs cover fresh acceptance, same-IP replacement reservation transfer, rejection without destroying the old session, and the non-destructive operator path. Telnet proofs cover envelope parsing, event metadata, reconnect backoff, bounded connection-local ordered input buffering during edge rebind, buffer exhaustion, sensitive logging, and Telnet/WebSocket `LOOK` parity; they do not prove durable replay of client input or transport bytes. Game Session gRPC proofs cover `Ping`, `NotifyDisconnect`, session lifecycle/control-plane parsing, application-error payloads, and `grpc.app_error` classification. Earlier first-party fresh-token, bare-login, `PLAY` scope, replay/expiry/context, screen-buffer restore, and fresh-redraw proofs describe the superseded path; current first-party coverage is fail-closed and does not establish playable admission. diff --git a/protos/entity-management/v1/preseeded_actor_assignment.proto b/protos/entity-management/v1/preseeded_actor_assignment.proto index 8db5a19d57..fe59989942 100644 --- a/protos/entity-management/v1/preseeded_actor_assignment.proto +++ b/protos/entity-management/v1/preseeded_actor_assignment.proto @@ -14,6 +14,9 @@ service CanonicalPreseededActorAssignmentService { returns (AssignPreseededActorResponse); rpc ReadPreseededActorAssignmentReceipt(ReadPreseededActorAssignmentReceiptRequest) returns (ReadPreseededActorAssignmentReceiptResponse); + // Exact same-namespace Game Session purpose; never allocates a missing projection. + rpc ReadPreseededActorRuntimeReference(ReadPreseededActorRuntimeReferenceRequest) + returns (ReadPreseededActorRuntimeReferenceResponse); } // The stable assignment intent. All target values are caller preconditions and are independently @@ -94,3 +97,29 @@ enum PreseededActorAssignmentReceiptStatus { PRESEEDED_ACTOR_ASSIGNMENT_RECEIPT_STATUS_UNSPECIFIED = 0; PRESEEDED_ACTOR_ASSIGNMENT_RECEIPT_STATUS_ASSIGNED = 1; } + +// Selector for the original assignment and complete target, distinct from World receipt access. +message ReadPreseededActorRuntimeReferenceRequest { + uint32 schema_version = 1; + string assignment_uuid = 2; + string canonical_account_uuid = 3; + string character_uuid = 4; + string intent_digest = 5; + PreseededActorAssignmentExpectedTarget expected_target = 6; +} + +// Entity-owned numeric identity is scoped by the retained target's tenant and game instance. +// Receipt provenance is immutable; this projection alone grants no placement or admission. +message ReadPreseededActorRuntimeReferenceResponse { + uint32 schema_version = 1; + int64 runtime_entity_id = 2; + int64 projection_generation = 3; + int64 projection_fence = 4; + string assignment_uuid = 5; + string canonical_account_uuid = 6; + string character_uuid = 7; + string intent_digest = 8; + PreseededActorAssignmentExpectedTarget expected_target = 9; + string published_owner_proof_digest = 10; + PreseededActorAssignmentCorePayload core_payload = 11; +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementReadGrpcCodecTest.java index 424b9bb576..0eb49d77a5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementReadGrpcCodecTest.java @@ -5,43 +5,22 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; -import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; -import java.util.HexFormat; import java.util.List; -import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; -import net.firedevops.firemud.common.operator.StartSessionOperatorAction; -import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; -import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof.Outcome; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import org.junit.jupiter.api.Test; -import tools.jackson.databind.json.JsonMapper; /** Complete controlled values only; no Account issuance or Game Session custody is established. */ class AccountInitialAdmissionSettlementReadGrpcCodecTest { - private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); - private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); - private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); - private static final UUID GAME_SESSION_MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); - private static final UUID GAME_SESSION_ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); - private static final UUID ACCOUNT_PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); - private static final UUID WORLD_HOLD = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); - private static final UUID WORLD_HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); - private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-09T10:20:30.456789Z"); - private static final JsonMapper JSON = JsonMapper.builder().build(); - @Test void roundTripsExactCompleteProtectionAndBothTerminalOutcomes() { for (Outcome outcome : List.of(Outcome.COMMITTED, Outcome.ABORTED)) { @@ -245,38 +224,31 @@ void refusesNoncanonicalNestedEvidenceMalformedFramingAndPurposeOverflow() { } static AccountInitialAdmissionSettlementReadEvidence evidence(Outcome outcome, boolean large) { - var tuple = originalTuple("admission-settlement-controlled"); - byte[] reference = captureReference(tuple, "17", "23", "18446744073709551615"); + var small = AccountInitialAdmissionSettlementTestFixtures.evidence(outcome); + if (!large) return small; var sources = new ArrayList(); - if (large) { - for (int index = 0; index < 32; index++) { - sources.add( - new SourceEvidence( - SourceKind.ISSUER, - "https://issuer-" + index + ".example", - null, - "17", - null, - null, - new byte[100 * 1024])); - } - } else { - sources.add(source("controlled-source")); + for (int index = 0; index < 32; index++) { + sources.add( + new SourceEvidence( + SourceKind.ISSUER, + "https://issuer-" + index + ".example", + null, + "17", + null, + null, + new byte[100 * 1024])); } + var original = small.protection(); var protection = AccountStartSessionAdmissionProtectionEvidence.create( - request(tuple), UUID.randomUUID(), 3L, reference, sha256(reference), sources); - var terminal = - new GameSessionCanonicalInitialAdmissionOwnerProof( - protection.request().worldAdmissionHoldIdentity(), - outcome, - outcome == Outcome.COMMITTED ? 1L : null, - outcome == Outcome.COMMITTED ? 7L : null, - "sha256:" + "a".repeat(64), - outcome == Outcome.ABORTED, - Instant.parse("2026-10-24T01:02:03Z")); + original.request(), + original.accountProtectionId(), + original.accountProtectionFence(), + original.originalSourceCaptureReferenceBytes(), + original.originalSourceCaptureReferenceSha256(), + sources); return new AccountInitialAdmissionSettlementReadEvidence( - UUID.randomUUID(), protection, terminal); + small.readRequestId(), protection, small.terminal()); } private static UnknownFieldSet unknown() { @@ -284,187 +256,4 @@ private static UnknownFieldSet unknown() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build(); } - - private static AccountStartSessionAdmissionProtectionRequest request( - StartSessionPostAuthorizationExecutionTuple tuple) { - return AccountStartSessionAdmissionProtectionRequest.create( - tuple.canonicalBytes(), - StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), - GAME_SESSION_MUTATION, - GAME_SESSION_ATTEMPT, - Long.MAX_VALUE, - ORIGINAL_LEASE_EXPIRY, - ACCOUNT_PARTICIPATION, - Long.MAX_VALUE, - hold(tuple)); - } - - private static StartSessionPostAuthorizationExecutionTuple originalTuple(String requestId) { - var preTuple = - StartSessionPreAuthorizationReservationTuple.createHuman( - requestId, - ACTOR, - new StartSessionOperatorAction( - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), - new StartSessionOperatorAction.Target(91L, TARGET_OWNER), - StartSessionOperatorAction.ExpectedVersion.ABSENT, - new StartSessionOperatorAction.Mutation( - StartSessionOperatorAction.ClientIp.absent()), - "canonical original StartSession admission attempt")); - return StartSessionPostAuthorizationExecutionTuple.createHuman( - preTuple, - "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", - "arfp/v1/test-key/" + "b".repeat(64), - uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), - 19L, - authorityBundle(preTuple), - new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "17", - "23", - "18446744073709551615")); - } - - private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { - String tenant = TENANT.toString(); - Map projection = - Map.of( - "sourceType", "ACCOUNT", - "sourceEvidenceId", "sha256:" + "a".repeat(64), - "sourceEvidenceVersion", "17", - "projectionStatus", "CURRENT", - "evaluatedAt", "2026-10-09T00:00:00Z", - "expiresAt", "2026-10-09T00:05:00Z"); - Map operation = - Map.of( - "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "actionFamilyRequestIdentity", - Map.of( - "requestIdentityKind", - "controlPlaneRequestId", - "requestId", - tuple.controlPlaneRequestId()), - "mutationDigest", tuple.mutationDigest()); - Map authority = - Map.of( - "issuerAuthGeneration", 1L, - "accountAuthorityGeneration", 2L, - "tenantAuthorityGeneration", Map.of(tenant, 3L), - "membershipAuthorityGeneration", Map.of(tenant, 4L), - "privateRealmGrantVersions", List.of()); - Map issuanceEvidence = - Map.of( - "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, - "actorAccountId", ACTOR.toString(), - "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", - "role", "tenantAdmin", - "accountGeneration", "2", - "tenantGeneration", "3"); - Map bundle = - Map.of( - "bundleVersion", - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "authorityScope", - Map.of( - "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), - "actionFamily", tuple.actionFamily(), - "applicableAccountId", ACTOR.toString(), - "applicableTenantId", tenant), - "accountProjectionEvidence", - projection, - "issuanceOperationIdentity", - operation, - "issuanceKind", - "human_operator", - "authorityTuple", - authority, - "membershipVersion", - Map.of(tenant, 5L), - "issuanceFence", - "23", - "issuanceEvidence", - issuanceEvidence); - return canonical(bundle); - } - - private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( - StartSessionPostAuthorizationExecutionTuple tuple) { - return hold(tuple, TENANT, "world-runtime"); - } - - private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( - StartSessionPostAuthorizationExecutionTuple tuple, UUID tenant, String namespace) { - return new WorldCanonicalInitialAdmissionHold.HoldIdentity( - new WorldCanonicalInitialAdmissionHold.Request( - namespace, - tenant, - "earth", - uuid("3916f423-2870-426a-a8aa-5e3f97412613"), - uuid("54e6094e-11bb-4f4c-93ee-a52f715b530b"), - "SHARED", - uuid("a55b2e10-9a24-4adb-adb8-6fc66fe3b8e9"), - uuid("d7280ec0-5979-4b62-8418-e9f139415184"), - 3L, - tuple.controlPlaneRequestId(), - "c".repeat(64), - WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, - 12L, - null), - WORLD_HOLD, - WORLD_HOLD_FENCE); - } - - private static byte[] captureReference( - StartSessionPostAuthorizationExecutionTuple tuple, - String sourceVersion, - String sourceFence, - String linearization) { - return canonical( - Map.of( - "schema", - AccountStartSessionAdmissionProtectionEvidence.SOURCE_CAPTURE_REFERENCE_SCHEMA, - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "capturedAt", "2026-10-09T10:11:12.123Z", - "bundleReference", - Map.of( - "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "sourceVersion", sourceVersion, - "sourceFence", sourceFence, - "linearization", linearization), - "snapshotSha256", "d".repeat(64))); - } - - private static SourceEvidence source(String exactEvidence) { - return new SourceEvidence( - SourceKind.ACCOUNT, - TENANT.toString(), - "2", - "17", - null, - null, - exactEvidence.getBytes(StandardCharsets.UTF_8)); - } - - private static byte[] canonical(Object value) { - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); - } catch (IOException impossible) { - throw new IllegalStateException(impossible); - } - } - - private static String sha256(byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (java.security.NoSuchAlgorithmException impossible) { - throw new IllegalStateException(impossible); - } - } - - private static UUID uuid(String value) { - return UUID.fromString(value); - } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementTestFixtures.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementTestFixtures.java new file mode 100644 index 0000000000..8cda57ba6d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementTestFixtures.java @@ -0,0 +1,240 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import tools.jackson.databind.json.JsonMapper; + +/** Complete controlled values only; no Account issuance or Game Session custody is established. */ +final class AccountInitialAdmissionSettlementTestFixtures { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID GAME_SESSION_MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); + private static final UUID GAME_SESSION_ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); + private static final UUID ACCOUNT_PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); + private static final UUID WORLD_HOLD = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); + private static final UUID WORLD_HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-09T10:20:30.456789Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private AccountInitialAdmissionSettlementTestFixtures() {} + + static AccountInitialAdmissionSettlementReadEvidence evidence(Outcome outcome) { + var tuple = originalTuple("admission-settlement-controlled"); + byte[] reference = captureReference(tuple, "17", "23", "18446744073709551615"); + var sources = List.of(source("controlled-source")); + var protection = + AccountStartSessionAdmissionProtectionEvidence.create( + request(tuple), UUID.randomUUID(), 3L, reference, sha256(reference), sources); + var terminal = + new GameSessionCanonicalInitialAdmissionOwnerProof( + protection.request().worldAdmissionHoldIdentity(), + outcome, + outcome == Outcome.COMMITTED ? 1L : null, + outcome == Outcome.COMMITTED ? 7L : null, + "sha256:" + "a".repeat(64), + outcome == Outcome.ABORTED, + Instant.parse("2026-10-24T01:02:03Z")); + return new AccountInitialAdmissionSettlementReadEvidence( + UUID.randomUUID(), protection, terminal); + } + + private static AccountStartSessionAdmissionProtectionRequest request( + StartSessionPostAuthorizationExecutionTuple tuple) { + return AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + Long.MAX_VALUE, + ORIGINAL_LEASE_EXPIRY, + ACCOUNT_PARTICIPATION, + Long.MAX_VALUE, + hold(tuple)); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(String requestId) { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical original StartSession admission attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = TENANT.toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", ACTOR.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence); + return canonical(bundle); + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( + StartSessionPostAuthorizationExecutionTuple tuple) { + return hold(tuple, TENANT, "world-runtime"); + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( + StartSessionPostAuthorizationExecutionTuple tuple, UUID tenant, String namespace) { + return new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + namespace, + tenant, + "earth", + uuid("3916f423-2870-426a-a8aa-5e3f97412613"), + uuid("54e6094e-11bb-4f4c-93ee-a52f715b530b"), + "SHARED", + uuid("a55b2e10-9a24-4adb-adb8-6fc66fe3b8e9"), + uuid("d7280ec0-5979-4b62-8418-e9f139415184"), + 3L, + tuple.controlPlaneRequestId(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null), + WORLD_HOLD, + WORLD_HOLD_FENCE); + } + + private static byte[] captureReference( + StartSessionPostAuthorizationExecutionTuple tuple, + String sourceVersion, + String sourceFence, + String linearization) { + return canonical( + Map.of( + "schema", + AccountStartSessionAdmissionProtectionEvidence.SOURCE_CAPTURE_REFERENCE_SCHEMA, + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "capturedAt", "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", sourceVersion, + "sourceFence", sourceFence, + "linearization", linearization), + "snapshotSha256", "d".repeat(64))); + } + + private static SourceEvidence source(String exactEvidence) { + return new SourceEvidence( + SourceKind.ACCOUNT, + TENANT.toString(), + "2", + "17", + null, + null, + exactEvidence.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementEvidenceTest.java index 6412284e38..d68ac606d9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementEvidenceTest.java @@ -34,7 +34,7 @@ class AccountStartSessionAdmissionProtectionSettlementEvidenceTest { void committedAndDefinitiveAbortedRoundTripExactEnvelopeDigestAndDefensiveBytes() throws Exception { for (Outcome outcome : List.of(Outcome.COMMITTED, Outcome.ABORTED)) { - var fixture = AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(outcome, false); + var fixture = AccountInitialAdmissionSettlementTestFixtures.evidence(outcome); var value = AccountStartSessionAdmissionProtectionSettlementEvidence.create( fixture.protection(), fixture.terminal()); @@ -78,8 +78,7 @@ void committedAndDefinitiveAbortedRoundTripExactEnvelopeDigestAndDefensiveBytes( @Test void pendingMismatchedHoldAndWrongNextPointerCannotSettle() { - var fixture = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.COMMITTED, false); + var fixture = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED); var terminal = fixture.terminal(); var pending = new GameSessionCanonicalInitialAdmissionOwnerProof( @@ -118,8 +117,7 @@ void pendingMismatchedHoldAndWrongNextPointerCannotSettle() { @Test void expectedClosedCommitMustUseExactlyPriorPointerPlusOne() { - var fixture = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.COMMITTED, false); + var fixture = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED); var prior = fixture.terminal().holdIdentity(); var request = prior.request(); var closedHold = @@ -193,8 +191,7 @@ void expectedClosedCommitMustUseExactlyPriorPointerPlusOne() { @Test void rejectsUnknownDuplicateTrailingNoncanonicalAndUnsupportedShape() throws Exception { - var fixture = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.COMMITTED, false); + var fixture = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED); byte[] bytes = AccountStartSessionAdmissionProtectionSettlementEvidence.create( fixture.protection(), fixture.terminal()) @@ -223,8 +220,7 @@ void rejectsUnknownDuplicateTrailingNoncanonicalAndUnsupportedShape() throws Exc @Test void rejectsMalformedNoncanonicalBase64TruncatedAndOversizedProofs() throws Exception { - var fixture = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.ABORTED, false); + var fixture = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.ABORTED); byte[] bytes = AccountStartSessionAdmissionProtectionSettlementEvidence.create( fixture.protection(), fixture.terminal()) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java index e2b6e11424..4855f92d70 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java @@ -131,7 +131,7 @@ void actualMtlsPreservesLargeCompleteProtectionAndTerminalAcrossExactReplay() th @Test void actualMtlsPreservesDefinitiveAbortAndRejectsInvalidOwnerResponses() throws Exception { var evidence = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.ABORTED, false); + AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.ABORTED); var response = AccountInitialAdmissionSettlementReadGrpcCodec.toResponse(evidence); responder.set(input -> response); start("gs"); @@ -161,7 +161,7 @@ void actualMtlsPreservesDefinitiveAbortAndRejectsInvalidOwnerResponses() throws @Test void nativeTransportStatusesRemainUnchangedAndNoAutomaticRetryOccurs() throws Exception { var evidence = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.COMMITTED, false); + AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED); start("gs"); client = newClient("account", NAMESPACE); client.init(); @@ -191,7 +191,7 @@ private void assertWrongServer(String identity) throws Exception { client = newClient("account", NAMESPACE); client.init(); var input = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.COMMITTED, false) + AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED) .input(); assertThatThrownBy(() -> client.read(input)) .satisfies( @@ -207,7 +207,7 @@ void controlledReceiverRefusesNonAccountCertificateBeforeEvidenceDecode() throws client = newClient("entity", NAMESPACE); client.init(); var input = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.COMMITTED, false) + AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED) .input(); assertThatThrownBy(() -> client.read(input)) .satisfies( @@ -220,7 +220,7 @@ void controlledReceiverRefusesNonAccountCertificateBeforeEvidenceDecode() throws @Test void localNamespaceAndSqlFailBeforeAnyRpc() throws Exception { var evidence = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.COMMITTED, false); + AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED); start("gs"); client = newClient("account", "other"); assertThatThrownBy(() -> client.read(evidence.input())) @@ -271,7 +271,7 @@ void requiresFileBackedTlsAndExplicitInitializationBeforeChannelUse() throws Exc factory, NAMESPACE); var input = - AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.COMMITTED, false) + AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED) .input(); assertThatThrownBy(() -> client.read(input)) .isInstanceOf(IllegalStateException.class) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 23b2043213..36fba95a42 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -34,6 +34,7 @@ import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult.Outcome; +import net.firedevops.firemud.entitymanagement.service.PreseededActorRuntimeReference; import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; @@ -44,6 +45,7 @@ import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -347,6 +349,17 @@ public PreseededActorAssignmentResult assignPreseededActor( evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT, null, intentDigest); } completeWithActor(evidence.assignmentUuid(), characterUuid); + var receipt = + readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + request.assignmentUuid(), + request.canonicalAccountUuid(), + characterUuid, + intentDigest, + request.expectedTarget())) + .orElseThrow( + () -> new IllegalStateException("Fresh assignment receipt is unavailable")); + new PreseededActorRuntimeProjectionRepository(dsl).allocateFreshAssignment(receipt); return new PreseededActorAssignmentResult( evidence.assignmentUuid(), Outcome.ASSIGNED, characterUuid, intentDigest); } @@ -478,6 +491,14 @@ private void requireSameStoredIntent( } } + /** Exact retained projection read; missing historical projections are never allocated here. */ + @Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ) + public Optional readPreseededActorRuntimeReference( + PreseededActorAssignmentReceiptRequest request) { + return readPreseededActorAssignmentReceipt(request) + .flatMap(receipt -> new PreseededActorRuntimeProjectionRepository(dsl).read(receipt)); + } + /** Returns only an exact committed operation whose PLAYER row remains owner-resolved. */ @Transactional(readOnly = true) public Optional readPreseededActorAssignmentReceipt( diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java new file mode 100644 index 0000000000..af20c54965 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import java.util.Optional; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceipt; +import net.firedevops.firemud.entitymanagement.service.PreseededActorRuntimeReference; +import net.firedevops.firemud.entitymanagement.service.RuntimeEntityId; +import org.jooq.DSLContext; + +/** + * Narrow owner-internal projection storage. Allocation joins the existing assignment transaction. + */ +final class PreseededActorRuntimeProjectionRepository { + private final DSLContext dsl; + + PreseededActorRuntimeProjectionRepository(DSLContext dsl) { + this.dsl = dsl; + } + + void allocateFreshAssignment(PreseededActorAssignmentReceipt receipt) { + // This is only invoked after the fresh assignment owner commit path has validated all sources. + // Never invoked by replay or read: historical assignments cannot authorize backfill. + int inserted = + dsl.execute( + """ + INSERT INTO entity_preseeded_actor_runtime_projections + (tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, + assignment_uuid, intent_digest, published_owner_proof_digest) + SELECT tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, + assignment_uuid, intent_digest, published_owner_proof_digest + FROM entity_preseeded_actor_assignment_operations + WHERE assignment_uuid = ? AND character_uuid = ? AND intent_digest = ? + AND status = 'ASSIGNED' AND publication_evidence_format = 'CANONICAL_UUID' + """, + receipt.assignmentUuid(), + receipt.characterUuid(), + receipt.intentDigest()); + if (inserted != 1) { + throw new IllegalStateException("Fresh committed runtime projection source is unavailable"); + } + } + + Optional read(PreseededActorAssignmentReceipt receipt) { + var target = receipt.target(); + var row = + dsl.fetchOne( + """ + SELECT runtime_entity_id, projection_generation, projection_fence + FROM entity_preseeded_actor_runtime_projections + WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND game_instance_id = ? + AND character_uuid = ? AND assignment_uuid = ? AND intent_digest = ? + AND published_owner_proof_digest = ? AND projection_state = 'CURRENT' + """, + target.canonicalTenantUuid(), + target.playableStateNamespaceId(), + target.gameInstanceId(), + receipt.characterUuid(), + receipt.assignmentUuid(), + receipt.intentDigest(), + receipt.publishedOwnerProofDigest()); + if (row == null) { + return Optional.empty(); + } + return Optional.of( + new PreseededActorRuntimeReference( + new RuntimeEntityId(row.get("runtime_entity_id", Long.class)), + row.get("projection_generation", Long.class), + row.get("projection_fence", Long.class), + receipt)); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java index c9286781c2..36f2b957e8 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java @@ -18,6 +18,11 @@ public final class CanonicalPreseededActorAssignmentPeerInterceptor implements S public static final String RECEIPT_READ_METHOD_NAME = "entity_management.v1.CanonicalPreseededActorAssignmentService/" + "ReadPreseededActorAssignmentReceipt"; + public static final String RUNTIME_REFERENCE_READ_METHOD_NAME = + "entity_management.v1.CanonicalPreseededActorAssignmentService/" + + "ReadPreseededActorRuntimeReference"; + private static final Context.Key VERIFIED_RUNTIME_REFERENCE_PEER = + Context.key("firemud-preseeded-runtime-reference-peer"); private static final Context.Key VERIFIED_GAME_SESSION_PEER = Context.key("firemud-preseeded-actor-assignment-peer"); private static final Context.Key VERIFIED_WORLD_PEER = @@ -39,7 +44,8 @@ public ServerCall.Listener interceptCall( String methodName = call.getMethodDescriptor().getFullMethodName(); boolean assignmentWrite = METHOD_NAME.equals(methodName); boolean receiptRead = RECEIPT_READ_METHOD_NAME.equals(methodName); - if (!assignmentWrite && !receiptRead) { + boolean runtimeRead = RUNTIME_REFERENCE_READ_METHOD_NAME.equals(methodName); + if (!assignmentWrite && !receiptRead && !runtimeRead) { return next.startCall(call, headers); } @@ -47,7 +53,7 @@ public ServerCall.Listener interceptCall( GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) .orElse(null); boolean trustedPeer = - assignmentWrite + (assignmentWrite || runtimeRead) ? isTrustedGameSessionPeer(peer, trustedNamespace) : isTrustedWorldPeer(peer, trustedNamespace); if (!trustedPeer @@ -55,7 +61,7 @@ public ServerCall.Listener interceptCall( || SessionContext.isInternalService()) { call.close( Status.PERMISSION_DENIED.withDescription( - assignmentWrite + (assignmentWrite || runtimeRead) ? "Trusted Game Session peer required" : "Trusted World peer required"), new Metadata()); @@ -66,10 +72,23 @@ public ServerCall.Listener interceptCall( context = assignmentWrite ? context.withValue(VERIFIED_GAME_SESSION_PEER, peer) - : context.withValue(VERIFIED_WORLD_PEER, peer); + : receiptRead ? context.withValue(VERIFIED_WORLD_PEER, peer) : context; + if (runtimeRead) { + context = context.withValue(VERIFIED_RUNTIME_REFERENCE_PEER, peer); + } return Contexts.interceptCall(context, call, headers, next); } + public static void requireVerifiedRuntimeReferencePeer(String namespace) { + if (!isTrustedGameSessionPeer(VERIFIED_RUNTIME_REFERENCE_PEER.get(), namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + throw Status.PERMISSION_DENIED + .withDescription("Trusted Game Session runtime reference peer required") + .asRuntimeException(); + } + } + public static GrpcPeerIdentity currentVerifiedPeer() { return VERIFIED_GAME_SESSION_PEER.get(); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java index 5416948a51..a332460eb9 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java @@ -12,6 +12,12 @@ public PreseededActorAssignmentReceiptService(CharacterRepository characterRepos this.characterRepository = Objects.requireNonNull(characterRepository, "characterRepository"); } + /** Game Session's distinct purpose-specific read; does not create or repair projections. */ + public Optional readRuntimeReference( + PreseededActorAssignmentReceiptRequest request) { + return characterRepository.readPreseededActorRuntimeReference(Objects.requireNonNull(request)); + } + public Optional read( PreseededActorAssignmentReceiptRequest request) { Objects.requireNonNull(request, "request"); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorRuntimeReference.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorRuntimeReference.java new file mode 100644 index 0000000000..ab6e4ff2f5 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorRuntimeReference.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; + +/** Retained Entity projection and original immutable assignment provenance; never admission. */ +public record PreseededActorRuntimeReference( + RuntimeEntityId runtimeEntityId, + long projectionGeneration, + long projectionFence, + PreseededActorAssignmentReceipt assignmentReceipt) { + public PreseededActorRuntimeReference { + Objects.requireNonNull(runtimeEntityId, "runtimeEntityId"); + Objects.requireNonNull(assignmentReceipt, "assignmentReceipt"); + if (projectionGeneration <= 0 + || projectionFence <= 0 + || !"ASSIGNED".equals(assignmentReceipt.status())) { + throw new IllegalArgumentException("Committed runtime projection provenance is required"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeEntityId.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeEntityId.java new file mode 100644 index 0000000000..9493cc6272 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RuntimeEntityId.java @@ -0,0 +1,10 @@ +package net.firedevops.firemud.entitymanagement.service; + +/** Entity-owned numeric runtime identity; qualified by tenant and game instance in a reference. */ +public record RuntimeEntityId(long value) { + public RuntimeEntityId { + if (value <= 0) { + throw new IllegalArgumentException("runtimeEntityId must be positive"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java index 872b2e92b4..cee8f5c838 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java @@ -10,15 +10,23 @@ import net.firedevops.firemud.entitymanagement.security.CanonicalPreseededActorAssignmentPeerInterceptor; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidencePort; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceipt; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceiptRequest; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceiptService; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentService; +import net.firedevops.firemud.entitymanagement.service.PreseededActorRuntimeReference; import net.firedevops.firemud.entitymanagement.v1.AssignPreseededActorRequest; import net.firedevops.firemud.entitymanagement.v1.AssignPreseededActorResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalPreseededActorAssignmentServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorAssignmentReceiptRequest; import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorAssignmentReceiptResponse; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.TransactionTimedOutException; /** * Unregistered method-guarded assignment write and immutable receipt read. Assignment delegates @@ -160,6 +168,72 @@ public void readPreseededActorAssignmentReceipt( responseObserver.onCompleted(); } + @Override + public void readPreseededActorRuntimeReference( + ReadPreseededActorRuntimeReferenceRequest request, + StreamObserver responseObserver) { + try { + CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedRuntimeReferencePeer( + trustedNamespace); + } catch (StatusRuntimeException unauthorized) { + responseObserver.onError(unauthorized); + return; + } + final PreseededActorAssignmentReceiptRequest selector; + try { + selector = PreseededActorAssignmentGrpcCodec.fromRuntimeReferenceRequest(request); + } catch (IllegalArgumentException malformed) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Runtime reference selector is invalid") + .asRuntimeException()); + return; + } + final Optional stored; + try { + stored = Objects.requireNonNull(receiptService.readRuntimeReference(selector)); + } catch (TransientDataAccessException + | DataAccessResourceFailureException + | CannotCreateTransactionException + | TransactionTimedOutException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Runtime reference owner is unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException unexpected) { + responseObserver.onError( + Status.INTERNAL.withDescription("Runtime reference read failed").asRuntimeException()); + return; + } + if (stored.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("Exact current runtime projection not found") + .asRuntimeException()); + return; + } + final ReadPreseededActorRuntimeReferenceResponse response; + try { + response = + PreseededActorAssignmentGrpcCodec.toRuntimeReferenceResponse( + selector, stored.orElseThrow()); + } catch (RuntimeException contradictory) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Runtime projection provenance is contradictory") + .asRuntimeException()); + return; + } + try { + responseObserver.onNext(response); + } catch (RuntimeException observerFailure) { + responseObserver.onError(observerFailure); + return; + } + responseObserver.onCompleted(); + } + private static StatusRuntimeException toAssignmentFailureStatus(RuntimeException failure) { if (failure instanceof StatusRuntimeException statusFailure) { Status.Code code = statusFailure.getStatus().getCode(); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java index 47f3fa4a75..f4f9809a39 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.service.PreseededActorRuntimeReference; import net.firedevops.firemud.entitymanagement.v1.AssignPreseededActorRequest; import net.firedevops.firemud.entitymanagement.v1.AssignPreseededActorResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; @@ -16,6 +17,8 @@ import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentReceiptStatus; import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorAssignmentReceiptRequest; import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorAssignmentReceiptResponse; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; import net.firedevops.firemud.entitymanagement.validation.CanonicalEntitySourceValues; /** Closed schema-1 codecs for the run-owned assignment and World-owned receipt read. */ @@ -86,6 +89,42 @@ static AssignPreseededActorResponse toResponse( return response.build(); } + static PreseededActorAssignmentReceiptRequest fromRuntimeReferenceRequest( + ReadPreseededActorRuntimeReferenceRequest request) { + if (request == null + || request.getSchemaVersion() != SCHEMA_VERSION + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasExpectedTarget()) { + throw invalid("complete schema-1 runtime reference selector is required"); + } + return new PreseededActorAssignmentReceiptRequest( + parseUuid(request.getAssignmentUuid(), "assignment_uuid"), + parseUuid(request.getCanonicalAccountUuid(), "canonical_account_uuid"), + parseUuid(request.getCharacterUuid(), "character_uuid"), + request.getIntentDigest(), + fromExpectedTarget(request.getExpectedTarget())); + } + + static ReadPreseededActorRuntimeReferenceResponse toRuntimeReferenceResponse( + PreseededActorAssignmentReceiptRequest selector, PreseededActorRuntimeReference reference) { + var receipt = reference.assignmentReceipt(); + // Reuse the original exact receipt validation without changing its schema or bytes. + toReceiptReadResponse(new ReceiptReadRequest(selector.assignmentUuid(), selector), receipt); + return ReadPreseededActorRuntimeReferenceResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setRuntimeEntityId(reference.runtimeEntityId().value()) + .setProjectionGeneration(reference.projectionGeneration()) + .setProjectionFence(reference.projectionFence()) + .setAssignmentUuid(receipt.assignmentUuid().toString()) + .setCanonicalAccountUuid(receipt.canonicalAccountUuid().toString()) + .setCharacterUuid(receipt.characterUuid().toString()) + .setIntentDigest(receipt.intentDigest()) + .setExpectedTarget(toWireExpectedTarget(receipt.target())) + .setPublishedOwnerProofDigest(receipt.publishedOwnerProofDigest()) + .setCorePayload(toWireCorePayload(receipt.corePayload())) + .build(); + } + static ReceiptReadRequest fromReceiptReadRequest( ReadPreseededActorAssignmentReceiptRequest request) { if (request == null) { diff --git a/services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql b/services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql new file mode 100644 index 0000000000..4af6ab4271 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql @@ -0,0 +1,50 @@ +-- New S3 runtime identity; no existing receipt, character identity or replay bytes are rewritten. +-- Global sequence is deliberately stronger than per-instance uniqueness and is never recycled. +CREATE SEQUENCE entity_runtime_entity_id_sequence AS BIGINT NO CYCLE; +CREATE TABLE entity_preseeded_actor_runtime_projections ( + runtime_entity_id BIGINT NOT NULL DEFAULT nextval('entity_runtime_entity_id_sequence') CHECK (runtime_entity_id > 0), + tenant_uuid UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + game_instance_id VARCHAR(255) NOT NULL, + character_uuid UUID NOT NULL, + assignment_uuid UUID NOT NULL REFERENCES entity_preseeded_actor_assignment_operations (assignment_uuid), + intent_digest VARCHAR(64) NOT NULL CHECK (intent_digest ~ '^[0-9a-f]{64}$'), + published_owner_proof_digest VARCHAR(64) NOT NULL CHECK (published_owner_proof_digest ~ '^[0-9a-f]{64}$'), + projection_generation BIGINT NOT NULL DEFAULT 1 CHECK (projection_generation > 0), + projection_fence BIGINT NOT NULL DEFAULT 1 CHECK (projection_fence > 0), + projection_state VARCHAR(16) NOT NULL DEFAULT 'CURRENT' CHECK (projection_state IN ('CURRENT', 'FENCED')), + PRIMARY KEY (tenant_uuid, game_instance_id, runtime_entity_id), + UNIQUE (runtime_entity_id), + UNIQUE (tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid), + UNIQUE (assignment_uuid) +); + +/* [jooq ignore start] */ +CREATE FUNCTION validate_entity_preseeded_runtime_projection() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM entity_preseeded_actor_assignment_operations a + WHERE a.assignment_uuid = NEW.assignment_uuid AND a.status = 'ASSIGNED' + AND a.completed_at IS NOT NULL AND a.publication_evidence_format = 'CANONICAL_UUID' + AND a.tenant_uuid = NEW.tenant_uuid + AND a.playable_state_namespace_id = NEW.playable_state_namespace_id + AND a.game_instance_id = NEW.game_instance_id AND a.character_uuid = NEW.character_uuid + AND a.intent_digest = NEW.intent_digest + AND a.published_owner_proof_digest = NEW.published_owner_proof_digest + ) THEN + RAISE EXCEPTION 'Runtime projection requires exact committed assignment provenance'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_entity_preseeded_runtime_projection_source + BEFORE INSERT ON entity_preseeded_actor_runtime_projections + FOR EACH ROW EXECUTE FUNCTION validate_entity_preseeded_runtime_projection(); +-- No replacement transition is enabled until the exact current replacement-owner chain exists. +CREATE TRIGGER trg_entity_preseeded_runtime_projection_immutable + BEFORE UPDATE OR DELETE ON entity_preseeded_actor_runtime_projections + FOR EACH ROW EXECUTE FUNCTION reject_entity_assignment_history_removal(); +CREATE TRIGGER trg_entity_preseeded_runtime_projection_no_truncate + BEFORE TRUNCATE ON entity_preseeded_actor_runtime_projections + FOR EACH STATEMENT EXECUTE FUNCTION reject_entity_assignment_history_removal(); +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index acea05d73e..b51bd7495b 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -505,7 +505,7 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( .extracting(AppliedMigration::version) .containsExactly( "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", - "1018", "1019", "1020", "1021"); + "1018", "1019", "1020", "1021", "1022"); assertThat(successorHistory) .extracting(AppliedMigration::script) .containsExactly( @@ -523,7 +523,8 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( "V1018__canonical_roster_staged_retirement.sql", "V1019__canonical_roster_snapshot_retirement_seals.sql", "V1020__canonical_roster_created_retirement_recognition.sql", - "V1021__character_create_binary_safe_immutability.sql"); + "V1021__character_create_binary_safe_immutability.sql", + "V1022__preseeded_runtime_actor_projection.sql"); assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); try (Connection connection = connectToSchema(schema)) { @@ -595,6 +596,47 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( } } + @Test + void firstAssignmentCreatesTheFreshEntityTenantMappingAndItsOwnerRows() { + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_tenant_identities " + + "WHERE canonical_tenant_uuid = ?", + Integer.class, + tenantUuid)) + .isZero(); + + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + + assertThat(assigned.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_assignment_operations operation " + + "JOIN entity_tenant_identities tenant " + + "ON tenant.canonical_tenant_uuid = operation.tenant_uuid " + + "WHERE operation.assignment_uuid = ? AND operation.tenant_uuid = ?", + Integer.class, + assignmentUuid, + tenantUuid)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters actor " + + "JOIN entity_tenant_identities tenant " + + "ON tenant.entity_tenant_row_id = actor.tenant_id " + + "WHERE actor.character_uuid = ? AND tenant.canonical_tenant_uuid = ?", + Integer.class, + assigned.characterUuid(), + tenantUuid)) + .isEqualTo(1); + } + @Test void exactRetryReturnsSamePersistedActorAndChangedIntentConflictsBeforeAllocation() { PreseededActorAssignmentResult first = @@ -1510,6 +1552,230 @@ void separateAuthorizedAssignmentsCanCreateMultipleActorsEvenWithSameDisplayName .isEqualTo(1); } + @Test + void runtimeProjectionUpgradeRetainsAssignedReceiptWithoutHistoricalBackfill() throws Exception { + var scope = PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + var assigned = assign(assignmentUuid, accountUuid, 4L, scope, "Assigned Actor"); + var request = assignmentRequest(evidence(assignmentUuid, accountUuid, 4L, scope)); + var selector = + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + request.expectedTarget()); + var originalReceipt = + characterRepository.readPreseededActorAssignmentReceipt(selector).orElseThrow(); + String sourceSchema = jdbcTemplate.queryForObject("SELECT current_schema()", String.class); + assertThat(sourceSchema).matches("[a-zA-Z_][a-zA-Z0-9_]*"); + String schema = "rp_" + UUID.randomUUID().toString().replace("-", ""); + migrationFlyway(schema).target(MigrationVersion.fromVersion("1021")).load().migrate(); + // Retained-state fixture: copy actual owner-produced rows into the prior schema. This is + // historical migration input, never projection allocation or new-target authority. + try (Connection connection = connectToSchema(schema)) { + connection.setAutoCommit(false); + var retained = DSL.using(connection, SQLDialect.POSTGRES); + for (var table : + List.of( + Map.entry("entity_tenant_identities", "canonical_tenant_uuid"), + Map.entry("entity_playable_state_namespace_scopes", "tenant_uuid"), + Map.entry("characters", "tenant_uuid"), + Map.entry("entity_preseeded_actor_assignment_operations", "tenant_uuid"))) { + retained.execute( + "INSERT INTO " + + table.getKey() + + " SELECT * FROM \"" + + sourceSchema + + "\"." + + table.getKey() + + " WHERE " + + table.getValue() + + " = ?", + tenantUuid); + } + connection.commit(); + } + String retainedAssignment; + try (Connection connection = connectToSchema(schema)) { + retainedAssignment = + DSL.using(connection, SQLDialect.POSTGRES) + .fetchSingle( + "SELECT to_jsonb(a)::text AS image FROM entity_preseeded_actor_assignment_operations a WHERE assignment_uuid = ?", + assignmentUuid) + .get("image", String.class); + var repository = new CharacterRepository(DSL.using(connection, SQLDialect.POSTGRES)); + assertThat(repository.readPreseededActorAssignmentReceipt(selector)) + .contains(originalReceipt); + } + var originalHistory = appliedMigrationHistory(schema); + migrationFlyway(schema).load().migrate(); + assertThat(appliedMigrationHistory(schema).subList(0, originalHistory.size())) + .containsExactlyElementsOf(originalHistory); + try (Connection connection = connectToSchema(schema)) { + var dsl = DSL.using(connection, SQLDialect.POSTGRES); + assertThat( + dsl.fetchSingle( + "SELECT to_jsonb(a)::text AS image FROM entity_preseeded_actor_assignment_operations a WHERE assignment_uuid = ?", + assignmentUuid) + .get("image", String.class)) + .isEqualTo(retainedAssignment); + var restarted = new CharacterRepository(dsl); + assertThat(restarted.readPreseededActorAssignmentReceipt(selector)).contains(originalReceipt); + assertThat(restarted.readPreseededActorRuntimeReference(selector)).isEmpty(); + assertThat(restarted.readPreseededActorRuntimeReference(selector)).isEmpty(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) AS count FROM entity_preseeded_actor_runtime_projections") + .get("count", Long.class)) + .isZero(); + } + } + + @Test + void runtimeProjectionSurvivesLostReplyRepositoryRestartAndRejectsChangedSelectors() + throws Exception { + // Controlled owner evidence exercises real PostgreSQL storage; this is not production + // authority. + var scope = PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + var target = evidence(assignmentUuid, accountUuid, 4L, scope); + var request = assignmentRequest(target); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_runtime_projections WHERE tenant_uuid = ?", + Integer.class, + tenantUuid)) + .isZero(); + var assigned = assign(assignmentUuid, accountUuid, 4L, scope, "Assigned Actor"); + var selector = + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + request.expectedTarget()); + var originalReceipt = + characterRepository.readPreseededActorAssignmentReceipt(selector).orElseThrow(); + var original = characterRepository.readPreseededActorRuntimeReference(selector).orElseThrow(); + assertThat(original.runtimeEntityId().value()).isPositive(); + assertThat(original.projectionGeneration()).isEqualTo(1); + assertThat(original.projectionFence()).isEqualTo(1); + assertThat(original.assignmentReceipt()).isEqualTo(originalReceipt); + // Lost assignment reply is recovered through exact replay without another allocation. + assertThat(assign(assignmentUuid, accountUuid, 4L, scope, "Assigned Actor")) + .isEqualTo(assigned); + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + connection.setSchema(jdbcTemplate.queryForObject("SELECT current_schema()", String.class)); + var restarted = new CharacterRepository(DSL.using(connection, SQLDialect.POSTGRES)); + assertThat(restarted.readPreseededActorRuntimeReference(selector)).contains(original); + } + assertThat( + characterRepository.readPreseededActorRuntimeReference( + new PreseededActorAssignmentReceiptRequest( + UUID.randomUUID(), + accountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + request.expectedTarget()))) + .isEmpty(); + var t = request.expectedTarget(); + var replacement = + new PreseededActorAssignmentExpectedTarget( + t.canonicalTenantUuid(), + t.realmUuid(), + t.worldSlug(), + t.realmSlug(), + "replacement-instance", + t.catalogRevision(), + t.canonicalVersionUuid(), + t.frozenPolicyDigest(), + t.playableStateNamespaceId(), + t.publishedReleaseBundleRef(), + t.playableStateScope()); + assertThat( + characterRepository.readPreseededActorRuntimeReference( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + replacement))) + .isEmpty(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_runtime_projections WHERE tenant_uuid = ?", + Integer.class, + tenantUuid)) + .isEqualTo(1); + assertThat(characterRepository.readPreseededActorAssignmentReceipt(selector)) + .contains(originalReceipt); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_preseeded_actor_runtime_projections SET projection_fence = projection_fence + 1 WHERE assignment_uuid = ?", + assignmentUuid)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "DELETE FROM entity_preseeded_actor_runtime_projections WHERE assignment_uuid = ?", + assignmentUuid)) + .isInstanceOf(DataAccessException.class); + // Stale durable character authority must invalidate the retained runtime projection read. + jdbcTemplate.update( + "UPDATE characters SET actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'runtime projection negative fixture' WHERE character_uuid = ?", + assigned.characterUuid()); + assertThat(characterRepository.readPreseededActorRuntimeReference(selector)).isEmpty(); + } + + @Test + void concurrentFreshAssignmentAllocationsAreUniqueAndDuplicateOperationsAllocateOnce() + throws Exception { + var scope = PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + CountDownLatch ready = new CountDownLatch(4); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(4); + try { + List> futures = new ArrayList<>(); + // Two identical operations race, alongside two independent accounts in the same runtime. + for (int index = 0; index < 4; index++) { + UUID operation = index < 2 ? assignmentUuid : UUID.randomUUID(); + UUID account = index < 2 ? accountUuid : UUID.randomUUID(); + futures.add( + executor.submit( + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Runtime projection race did not start"); + } + return assign(operation, account, 4L, scope, "Assigned Actor"); + })); + } + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var first = futures.get(0).get(20, TimeUnit.SECONDS); + assertThat(futures.get(1).get(20, TimeUnit.SECONDS)).isEqualTo(first); + for (int index = 2; index < 4; index++) { + assertThat(futures.get(index).get(20, TimeUnit.SECONDS).outcome()) + .isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + } + var ids = + jdbcTemplate.queryForList( + "SELECT runtime_entity_id FROM entity_preseeded_actor_runtime_projections WHERE tenant_uuid = ?", + Long.class, + tenantUuid); + assertThat(ids) + .hasSize(3) + .doesNotHaveDuplicates() + .allSatisfy(id -> assertThat(id).isPositive()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + @Test void distinctConcurrentAssignmentsPersistOneWinnerAndOneReplayableConflict() throws Exception { CountDownLatch ready = new CountDownLatch(2); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java index 4e53b42260..4389710eb7 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java @@ -71,6 +71,8 @@ import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentReceiptStatus; import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorAssignmentReceiptRequest; import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorAssignmentReceiptResponse; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadRequest; import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; @@ -420,10 +422,102 @@ void composesExactMtlsOwnerReadsCapabilityAndActualPostgresAssignmentWriterAndRe .containsExactlyElementsOf(persistedRows); assertNoMutation(assignedBaseline, assignment); + var runtimeSelector = + ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(receiptReadRequest.getAssignmentUuid()) + .setCanonicalAccountUuid(receiptReadRequest.getCanonicalAccountUuid()) + .setCharacterUuid(receiptReadRequest.getCharacterUuid()) + .setIntentDigest(receiptReadRequest.getIntentDigest()) + .setExpectedTarget(receiptReadRequest.getExpectedTarget()) + .build(); + // Controlled owner sources and test PKI authorize only this passive local composition. + // Actual persisted projection comes from the production assignment writer, never fixture + // SQL. + var runtimeRead = callRuntimeRead(entityServer, "game-session-client", runtimeSelector); + assertThat(runtimeRead.getRuntimeEntityId()).isPositive(); + assertThat(runtimeRead.getProjectionGeneration()).isEqualTo(1); + assertThat(runtimeRead.getProjectionFence()).isEqualTo(1); + assertThat(runtimeRead.getExpectedTarget()) + .isEqualTo(receiptReadRequest.getExpectedTarget()); + assertThat(runtimeRead.getCharacterUuid()).isEqualTo(characterUuid.toString()); + assertThat(runtimeRead.getAssignmentUuid()) + .isEqualTo(assignment.assignmentUuid().toString()); + assertThat(runtimeRead.getIntentDigest()).isEqualTo(receipt.intentDigest()); + assertThat(runtimeRead.getPublishedOwnerProofDigest()) + .isEqualTo(receipt.publishedOwnerProofDigest()); + assertThat(runtimeReadEntryCount.get()).isEqualTo(1); + assertThat(runtimeReadEnteredOutsideTransaction.get()).isTrue(); + for (String wrongPeer : + List.of("world-client", "account-client", "foreign-game-session-client")) { + assertThatThrownBy(() -> callRuntimeRead(entityServer, wrongPeer, runtimeSelector)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + assertThat(runtimeReadEntryCount.get()).isEqualTo(1); + var changedRuntimeSelector = + runtimeSelector.toBuilder().setCharacterUuid(UUID.randomUUID().toString()).build(); + assertThatThrownBy( + () -> callRuntimeRead(entityServer, "game-session-client", changedRuntimeSelector)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); + // A replacement target cannot borrow the original assignment's projection. + var changedRuntimeTarget = + runtimeSelector.toBuilder() + .setExpectedTarget( + runtimeSelector.getExpectedTarget().toBuilder() + .setGameInstanceId("replacement-instance")) + .build(); + assertThatThrownBy( + () -> callRuntimeRead(entityServer, "game-session-client", changedRuntimeTarget)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); + var foreignRuntimeTarget = + runtimeSelector.toBuilder() + .setExpectedTarget( + runtimeSelector.getExpectedTarget().toBuilder() + .setPlayableStateNamespaceUuid(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> callRuntimeRead(entityServer, "game-session-client", foreignRuntimeTarget)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); + var wrongAssignment = + runtimeSelector.toBuilder().setAssignmentUuid(UUID.randomUUID().toString()).build(); + assertThatThrownBy( + () -> callRuntimeRead(entityServer, "game-session-client", wrongAssignment)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); + assertThat( + callRuntimeRead(entityServer, "game-session-client", runtimeSelector).toByteArray()) + .containsExactly(runtimeRead.toByteArray()); + assertThat(callReceiptRead(entityServer, "world-client", receiptReadRequest).toByteArray()) + .containsExactly(persistedRead.toByteArray()); + assertThat(assignmentAndActorRows(assignment, characterUuid)) + .containsExactlyElementsOf(persistedRows); + byte[] terminalResponse = assigned.toByteArray(); AssignPreseededActorResponse replay = call(entityServer, "game-session-client", wireRequest); assertThat(replay.toByteArray()).containsExactly(terminalResponse); + assertThat( + callRuntimeRead(entityServer, "game-session-client", runtimeSelector).toByteArray()) + .containsExactly(runtimeRead.toByteArray()); assertThat(assignmentAndActorRows(assignment, characterUuid)) .containsExactlyElementsOf(persistedRows); assertThat(characterRepository.readPreseededActorAssignmentReceipt(receiptRequest)) @@ -486,12 +580,25 @@ private CharacterRepository observeRepositoryEntry(CharacterRepository repositor throw new IllegalStateException( "Assignment receipt read was entered inside a caller-owned SQL transaction"); } + } else if (invocation + .getMethod() + .getName() + .equals("readPreseededActorRuntimeReference")) { + runtimeReadEntryCount.incrementAndGet(); + runtimeReadEnteredOutsideTransaction.set( + !TransactionSynchronizationManager.isActualTransactionActive()); + if (!runtimeReadEnteredOutsideTransaction.get()) { + throw new IllegalStateException( + "Runtime read entered inside caller SQL transaction"); + } } return invocation.proceed(); }); return (CharacterRepository) proxy.getProxy(); } + private final AtomicInteger runtimeReadEntryCount = new AtomicInteger(); + private final AtomicBoolean runtimeReadEnteredOutsideTransaction = new AtomicBoolean(); private final AtomicInteger writerEntryCount = new AtomicInteger(); private final AtomicBoolean writerEnteredOutsideTransaction = new AtomicBoolean(); private final AtomicInteger receiptReadEntryCount = new AtomicInteger(); @@ -593,6 +700,23 @@ private static AssignPreseededActorResponse call( } } + private static ReadPreseededActorRuntimeReferenceResponse callRuntimeRead( + Server server, String callerAlias, ReadPreseededActorRuntimeReferenceRequest request) + throws Exception { + CommonGrpcClientProperties callerTls = + TLS.pki().clientProperties(TLS_DIRECTORY, TLS.pki().identity(callerAlias)); + ManagedChannel channel = + new GrpcChannelFactory() + .buildChannel("127.0.0.1:" + server.getPort(), 6565, callerTls, false); + try { + return CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(15, TimeUnit.SECONDS) + .readPreseededActorRuntimeReference(request); + } finally { + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + private static ReadPreseededActorAssignmentReceiptResponse callReceiptRead( Server server, String callerAlias, ReadPreseededActorAssignmentReceiptRequest request) throws Exception { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 850495204d..c6595fc525 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -642,7 +642,8 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { .extracting(migration -> migration.getVersion().getVersion()) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021"); + "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021", + "1022"); assertThat(flyway.info().applied()) .filteredOn(migration -> migration.getVersion() != null) .extracting(migration -> migration.getScript()) @@ -668,9 +669,10 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { "V1018__canonical_roster_staged_retirement.sql", "V1019__canonical_roster_snapshot_retirement_seals.sql", "V1020__canonical_roster_created_retirement_recognition.sql", - "V1021__character_create_binary_safe_immutability.sql"); + "V1021__character_create_binary_safe_immutability.sql", + "V1022__preseeded_runtime_actor_projection.sql"); assertThat(flyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1021")); + .isEqualTo(MigrationVersion.fromVersion("1022")); assertThat(flyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); @@ -743,7 +745,8 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro .extracting(MigrationHistoryEntry::version) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021"); + "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021", + "1022"); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::script) .containsExactly( @@ -768,7 +771,8 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "V1018__canonical_roster_staged_retirement.sql", "V1019__canonical_roster_snapshot_retirement_seals.sql", "V1020__canonical_roster_created_retirement_recognition.sql", - "V1021__character_create_binary_safe_immutability.sql"); + "V1021__character_create_binary_safe_immutability.sql", + "V1022__preseeded_runtime_actor_projection.sql"); assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); try (Connection connection = connectToMigrationSchema(); @@ -1031,7 +1035,7 @@ private void migrateLegacySchemaToLatest() { assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); upgradeFlyway.migrate(); assertThat(upgradeFlyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1021")); + .isEqualTo(MigrationVersion.fromVersion("1022")); assertThat(upgradeFlyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index fb0abfc27d..cbbce33966 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -119,7 +119,7 @@ void upgradesActualEntity1014ParentWithoutChangingRetainedActorOrRosterRows() { DSLContext upgradedDsl = DSL.using(parentDataSource, SQLDialect.POSTGRES); assertThat(migrationHistory(upgradedDsl).subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); - assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1021"); + assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1022"); assertThat(retainedParentRows(upgradedDsl, character, snapshot)) .containsExactlyElementsOf(retainedRows); assertThat( @@ -165,7 +165,7 @@ void binaryGuardUpgradePreservesCreatedRowsHistoryAndTerminalReplay() throws Exc assertThat(migrationHistory(retainedDsl).subList(0, historyBefore.size())) .containsExactlyElementsOf(historyBefore); - assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1021"); + assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1022"); assertThat(retainedDsl.fetch(retainedRowsSql).getValues(0, String.class)) .containsExactlyElementsOf(before); assertThat(retainedRepository.settle(retainedProof, null)).isEqualTo(terminal); @@ -230,7 +230,7 @@ void upgradesRetainedV1016CreatedActorBeforeQuarantineWithoutChangingRows() thro migrate(retainedDataSource, retainedSchema, null); - assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1021"); + assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1022"); assertThat(retainedRow(retainedDsl, "characters", "character_uuid", characterId)) .isEqualTo(actorBefore); assertThat( diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java index ddcf54a3c4..1494dcbb89 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java @@ -84,7 +84,8 @@ void upgradeRetainedV1011ActorReceiptAndSealedSnapshot() { UUID.randomUUID(), new CanonicalGameplayRosterSnapshotReference(UUID.randomUUID(), "a".repeat(64)), target()); - transaction.executeWithoutResult(ignored -> seedAssignedActorAndSnapshot()); + transaction.executeWithoutResult( + ignored -> seedHistoricalV1011AssignmentActorAndSnapshotWithoutProjection()); List retained = retainedRows(); migrate(dataSource, "latest"); assertThat(retainedRows()).containsExactlyElementsOf(retained); @@ -406,7 +407,8 @@ void forward1015To1016PreservesInstalledHistoryRetainedRowsAndOldSnapshotGuards( UUID.randomUUID(), new CanonicalGameplayRosterSnapshotReference(UUID.randomUUID(), "a".repeat(64)), target()); - transaction.executeWithoutResult(ignored -> seedAssignedActorAndSnapshot()); + transaction.executeWithoutResult( + ignored -> seedHistoricalV1011AssignmentActorAndSnapshotWithoutProjection()); List retained1011Rows = retainedRows(); migrate(source, "1014"); assertThat(retainedRows()).containsExactlyElementsOf(retained1011Rows); @@ -3195,24 +3197,7 @@ private static CanonicalGameplayRosterRetentionPolicy policy(Duration duration) private void seedAssignedActorAndSnapshot() { var target = binding.target(); UUID assignment = UUID.randomUUID(); - var request = - new PreseededActorAssignmentRequest( - assignment, - binding.canonicalAccountUuid(), - new PreseededActorCorePayload( - PreseededActorCorePayload.ActorKind.PLAYER, "Retained Actor"), - new PreseededActorAssignmentExpectedTarget( - target.tenantUuid(), - target.realmUuid(), - target.worldSlug(), - target.realmSlug(), - target.gameInstanceUuid().toString(), - target.catalogRevision(), - target.canonicalVersionUuid(), - target.publishedPolicyDigest(), - target.playableStateNamespaceId(), - target.publishedReleaseBundleRef(), - target.playableStateScope())); + var request = assignmentRequest(assignment); var evidence = new PreseededActorAssignmentOwnerEvidence( assignment, @@ -3251,6 +3236,124 @@ private void seedAssignedActorAndSnapshot() { "ACCOUNT_DATABASE_INSERT"), request.mutationIntentDigest()) .characterUuid(); + seedSnapshot(actor); + } + + /** + * Seeds a controlled pre-V1022 retained owner record at its historical schema frontier. This + * fixture deliberately has no runtime projection; only fresh assignments at the current schema + * use the production assignment path above. + */ + private void seedHistoricalV1011AssignmentActorAndSnapshotWithoutProjection() { + var target = binding.target(); + UUID assignment = UUID.randomUUID(); + UUID actor = UUID.randomUUID(); + var request = assignmentRequest(assignment); + + dsl.execute( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) " + + "VALUES (?, ?, ?) ON CONFLICT (tenant_uuid, playable_state_namespace_id) DO NOTHING", + target.tenantUuid(), + target.playableStateNamespaceId(), + target.playableStateScope().name()); + dsl.execute( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?) " + + "ON CONFLICT (canonical_tenant_uuid) DO NOTHING", + target.tenantUuid()); + long entityTenantRowId = + dsl.fetchSingle( + "SELECT entity_tenant_row_id FROM entity_tenant_identities " + + "WHERE canonical_tenant_uuid = ?", + target.tenantUuid()) + .get("entity_tenant_row_id", Long.class); + + dsl.execute( + "INSERT INTO entity_preseeded_actor_assignment_operations " + + "(assignment_uuid, intent_digest, account_uuid, account_uuid_provenance, " + + "account_identity_schema_version, account_identity_target_namespace, " + + "source_account_row_id, eligibility, eligibility_evaluated_at, " + + "membership_authority_generation, eligibility_evidence_digest, " + + "account_authority_snapshot_digest, account_purpose, account_currentness, " + + "published_owner_proof_digest, published_release_bundle_ref, " + + "tenant_uuid, realm_uuid, world_slug, realm_slug, game_instance_id, " + + "catalog_revision, published_version_id, published_version_number, " + + "canonical_version_uuid, publication_evidence_format, " + + "frozen_policy_digest, playable_state_namespace_id, playable_state_scope, " + + "entry_policy, actor_kind, display_name, status) " + + "VALUES (?, ?, ?, 'ACCOUNT_DATABASE_INSERT', 1, 'dev', 51, 'ELIGIBLE', " + + "clock_timestamp(), 4, ?, ?, 'PRESEEDED_ACTOR_STAGING', " + + "'CURRENT_AT_REVALIDATION', ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, " + + "'CANONICAL_UUID', ?, ?, ?, ?, ?, ?, 'PENDING')", + assignment, + request.mutationIntentDigest(), + binding.canonicalAccountUuid(), + "1".repeat(64), + "2".repeat(64), + target.publishedOwnerProofDigest(), + target.publishedReleaseBundleRef(), + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.playableStateScope().name(), + target.entryPolicy().name(), + request.corePayload().actorKind().name(), + request.corePayload().displayName()); + dsl.execute( + "INSERT INTO characters " + + "(account_id, name, tenant_id, playable_state_key, character_uuid, account_uuid, " + + "tenant_uuid, playable_state_namespace_id, playable_state_scope, " + + "actor_identity_status, actor_identity_quarantine_reason) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'OWNER_RESOLVED', NULL)", + 51L, + request.corePayload().displayName(), + entityTenantRowId, + target.playableStateNamespaceId().toString(), + actor, + binding.canonicalAccountUuid(), + target.tenantUuid(), + target.playableStateNamespaceId(), + target.playableStateScope().name()); + assertThat( + dsl.execute( + "UPDATE entity_preseeded_actor_assignment_operations " + + "SET status = 'ASSIGNED', character_uuid = ?, " + + "completed_at = clock_timestamp() WHERE assignment_uuid = ? " + + "AND status = 'PENDING'", + actor, + assignment)) + .isEqualTo(1); + seedSnapshot(actor); + } + + private PreseededActorAssignmentRequest assignmentRequest(UUID assignment) { + var target = binding.target(); + return new PreseededActorAssignmentRequest( + assignment, + binding.canonicalAccountUuid(), + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Retained Actor"), + new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope())); + } + + private void seedSnapshot(UUID actor) { + var target = binding.target(); dsl.execute( "INSERT INTO entity_canonical_gameplay_roster_snapshots " + "(snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, realm_uuid, " @@ -3378,7 +3481,8 @@ private List rebuildLegacyCohort( migrate(source, "1011"); dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); - transaction.executeWithoutResult(ignored -> seedAssignedActorAndSnapshot()); + transaction.executeWithoutResult( + ignored -> seedHistoricalV1011AssignmentActorAndSnapshotWithoutProjection()); migrate(source, "1017"); legacyRequests = new java.util.ArrayList<>(); legacyNonces = new java.util.HashMap<>(); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index ea1a70379e..27e4fa5ec3 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -106,7 +106,7 @@ void seedLegacyRowsBeforeV1011() { dsl.fetchSingle( "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") .get(0, String.class)) - .isEqualTo("1021"); + .isEqualTo("1022"); } @AfterEach diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java index e01dea40c1..e10e4ff515 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java @@ -92,6 +92,45 @@ void acceptsOnlyTheExactSameNamespaceWorldCertificateForTheReceiptReadMethod() { verify(next).startCall(any(), any()); } + @Test + void runtimeReadHasItsOwnExactGameSessionPurposeAndNeverWorldOrAssignmentAuthority() { + var interceptor = new CanonicalPreseededActorAssignmentPeerInterceptor(NAMESPACE); + var readCall = + callFor( + CanonicalPreseededActorAssignmentPeerInterceptor.RUNTIME_REFERENCE_READ_METHOD_NAME, + peerSession(EXACT_PEER)); + ServerCallHandler next = mock(ServerCallHandler.class); + when(next.startCall(any(), any())) + .thenAnswer( + invocation -> { + CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedRuntimeReferencePeer( + NAMESPACE); + assertThatThrownBy( + () -> + CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedWorldPeer( + NAMESPACE)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy( + () -> + CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedPeer( + NAMESPACE)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + return new ServerCall.Listener<>() {}; + }); + interceptor.interceptCall(readCall, new Metadata(), next); + verify(next).startCall(any(), any()); + for (String uri : + List.of(EXACT_WORLD_PEER, "spiffe://firemud/ns/other/sa/game-session-service")) { + var wrongCall = + callFor( + CanonicalPreseededActorAssignmentPeerInterceptor.RUNTIME_REFERENCE_READ_METHOD_NAME, + peerSession(uri)); + ServerCallHandler wrongNext = mock(ServerCallHandler.class); + interceptor.interceptCall(wrongCall, new Metadata(), wrongNext); + verify(wrongNext, never()).startCall(any(), any()); + } + } + @Test void rejectsAbsentWrongServiceAndCrossNamespaceCertificatesBeforeHandler() { var interceptor = new CanonicalPreseededActorAssignmentPeerInterceptor(NAMESPACE); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java index f93d8c280c..cb39dfefa4 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -39,7 +40,9 @@ import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentService; import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.service.PreseededActorRuntimeReference; import net.firedevops.firemud.entitymanagement.service.RunOwnedPreseededAssignmentAuthority; +import net.firedevops.firemud.entitymanagement.service.RuntimeEntityId; import net.firedevops.firemud.entitymanagement.v1.AssignPreseededActorRequest; import net.firedevops.firemud.entitymanagement.v1.AssignPreseededActorResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; @@ -48,6 +51,8 @@ import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentReceiptStatus; import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorAssignmentReceiptRequest; import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorAssignmentReceiptResponse; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -516,6 +521,177 @@ void invalidPersistedResultStillReturnsBoundedInternalWithoutPartialResponse() { assertThat(response.errorDescription).isEqualTo("Preseeded actor assignment failed"); } + @Test + void runtimeReferenceRequiresDistinctVerifiedPurposeBeforeDecoding() { + var receiptService = mock(PreseededActorAssignmentReceiptService.class); + var handler = + new CanonicalPreseededActorAssignmentGrpcService( + NAMESPACE, mock(PreseededActorAssignmentService.class), receiptService); + var observer = new RuntimeObserver(); + handler.readPreseededActorRuntimeReference( + ReadPreseededActorRuntimeReferenceRequest.getDefaultInstance(), observer); + assertThat(observer.errorCode).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.terminalCount).isEqualTo(1); + assertThat(observer.value).isNull(); + verifyNoInteractions(receiptService); + } + + @Test + void runtimeReferenceReturnsExactTypedProjectionOrOneBoundedFailure() { + var receiptService = mock(PreseededActorAssignmentReceiptService.class); + var handler = + new CanonicalPreseededActorAssignmentGrpcService( + NAMESPACE, mock(PreseededActorAssignmentService.class), receiptService); + var wire = + ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(ASSIGNMENT_UUID.toString()) + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setCharacterUuid(CHARACTER_UUID.toString()) + .setIntentDigest(receiptRequest().intentDigest()) + .setExpectedTarget(request().getExpectedTarget()) + .build(); + var selector = PreseededActorAssignmentGrpcCodec.fromRuntimeReferenceRequest(wire); + when(receiptService.readRuntimeReference(selector)) + .thenReturn( + Optional.of( + new PreseededActorRuntimeReference(new RuntimeEntityId(71), 1, 1, receipt()))); + var success = invokeRuntimeRead(handler, wire); + assertThat(success.value.getRuntimeEntityId()).isEqualTo(71); + assertThat(success.value.getExpectedTarget()).isEqualTo(wire.getExpectedTarget()); + assertThat(success.value.getAssignmentUuid()).isEqualTo(wire.getAssignmentUuid()); + assertThat(success.terminalCount).isEqualTo(1); + assertThat(success.errorCode).isNull(); + when(receiptService.readRuntimeReference(selector)).thenReturn(Optional.empty()); + var missing = invokeRuntimeRead(handler, wire); + assertThat(missing.errorCode).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.value).isNull(); + assertThat(missing.terminalCount).isEqualTo(1); + var malformed = invokeRuntimeRead(handler, wire.toBuilder().setSchemaVersion(2).build()); + assertThat(malformed.errorCode).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(malformed.terminalCount).isEqualTo(1); + assertThatThrownBy( + () -> + PreseededActorAssignmentGrpcCodec.fromRuntimeReferenceRequest( + wire.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void runtimeReferenceMapsOnlyExplicitAvailabilityFailuresWithoutDisclosingOwnerDetails() { + var receiptService = mock(PreseededActorAssignmentReceiptService.class); + var handler = + new CanonicalPreseededActorAssignmentGrpcService( + NAMESPACE, mock(PreseededActorAssignmentService.class), receiptService); + var wire = + ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(ASSIGNMENT_UUID.toString()) + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setCharacterUuid(CHARACTER_UUID.toString()) + .setIntentDigest(receiptRequest().intentDigest()) + .setExpectedTarget(request().getExpectedTarget()) + .build(); + var selector = PreseededActorAssignmentGrpcCodec.fromRuntimeReferenceRequest(wire); + for (RuntimeException unavailable : + List.of( + new org.springframework.dao.TransientDataAccessResourceException( + "private connection detail"), + new org.springframework.dao.QueryTimeoutException("private query detail"), + new org.springframework.dao.CannotAcquireLockException("private lock detail"), + new org.springframework.dao.DataAccessResourceFailureException( + "private resource detail"), + new org.springframework.transaction.CannotCreateTransactionException( + "private transaction detail"), + new org.springframework.transaction.TransactionTimedOutException( + "private timeout detail"))) { + doThrow(unavailable).when(receiptService).readRuntimeReference(selector); + var observer = invokeRuntimeRead(handler, wire); + assertThat(observer.errorCode).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observer.errorDescription).isEqualTo("Runtime reference owner is unavailable"); + assertThat(observer.errorHasCause).isFalse(); + assertThat(observer.value).isNull(); + assertThat(observer.terminalCount).isEqualTo(1); + } + for (RuntimeException unexpected : + List.of( + new IllegalStateException("private unexpected detail"), + new org.jooq.exception.DataAccessException("private SQL detail"), + new org.springframework.jdbc.BadSqlGrammarException( + "private task", "private SQL", new java.sql.SQLException("private syntax detail")), + new org.springframework.transaction.TransactionSystemException( + "private transaction system detail"))) { + doThrow(unexpected).when(receiptService).readRuntimeReference(selector); + var observer = invokeRuntimeRead(handler, wire); + assertThat(observer.errorCode).isEqualTo(Status.Code.INTERNAL); + assertThat(observer.errorDescription).isEqualTo("Runtime reference read failed"); + assertThat(observer.errorHasCause).isFalse(); + assertThat(observer.value).isNull(); + assertThat(observer.terminalCount).isEqualTo(1); + } + } + + private static RuntimeObserver invokeRuntimeRead( + CanonicalPreseededActorAssignmentGrpcService handler, + ReadPreseededActorRuntimeReferenceRequest request) { + var observer = new RuntimeObserver(); + ServerCall call = mock(ServerCall.class); + MethodDescriptor descriptor = mock(MethodDescriptor.class); + when(descriptor.getFullMethodName()) + .thenReturn( + CanonicalPreseededActorAssignmentPeerInterceptor.RUNTIME_REFERENCE_READ_METHOD_NAME); + when(call.getMethodDescriptor()).thenReturn(descriptor); + Attributes peerAttributes = + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, peerSession()).build(); + when(call.getAttributes()).thenReturn(peerAttributes); + new CanonicalPreseededActorAssignmentPeerInterceptor(NAMESPACE) + .interceptCall( + call, + new Metadata(), + (ignoredCall, ignoredHeaders) -> { + handler.readPreseededActorRuntimeReference(request, observer); + return new ServerCall.Listener<>() {}; + }); + return observer; + } + + private static final class RuntimeObserver + implements StreamObserver { + private ReadPreseededActorRuntimeReferenceResponse value; + private String errorDescription; + private boolean errorHasCause; + private Status.Code errorCode; + private int terminalCount; + + @Override + public void onNext(ReadPreseededActorRuntimeReferenceResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + Status status = Status.fromThrowable(failure); + errorDescription = status.getDescription(); + errorHasCause = failure.getCause() != null; + errorCode = status.getCode(); + terminalCount++; + } + + @Override + public void onCompleted() { + terminalCount++; + } + } + private static CapturingObserver invoke( CanonicalPreseededActorAssignmentGrpcService handler, AssignPreseededActorRequest request) { var response = new CapturingObserver(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java new file mode 100644 index 0000000000..48cf48b72c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java @@ -0,0 +1,344 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPreseededActorAssignmentServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; + +/** Passive exact-original-assignment reader. A reference grants neither placement nor admission. */ +public final class CanonicalPreseededActorRuntimeReferenceClient + extends AbstractReloadingBlockingGrpcClient< + CanonicalPreseededActorAssignmentServiceGrpc + .CanonicalPreseededActorAssignmentServiceBlockingStub> { + private static final int SCHEMA_VERSION = 1; + private static final int MAX_REQUEST_BYTES = 8 * 1024; + private static final int MAX_RESPONSE_BYTES = 8 * 1024; + private static final long CALL_DEADLINE_SECONDS = 20L; + private static final int MAX_GAME_INSTANCE_ID_LENGTH = 255; + private static final int MAX_DISPLAY_NAME_CODE_POINTS = 100; + private static final int MAX_RELEASE_REF_LENGTH = 1024; + private static final Pattern RAW_SHA256 = Pattern.compile("[0-9a-f]{64}"); + + private final String namespace; + + public CanonicalPreseededActorRuntimeReferenceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Preseeded actor runtime reference"), + channels, + CanonicalPreseededActorRuntimeReferenceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed Game Session workload namespace required"); + } + this.namespace = namespace; + } + + /** Initializes the manual channel outside any ambient SQL transaction or synchronization. */ + public void init() throws IOException { + requireNoAmbientSql( + "Preseeded actor runtime reference client initialization requires no ambient SQL"); + initOnce( + "Preseeded actor runtime reference client is closed", + "Entity runtime reference unavailable"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected CanonicalPreseededActorAssignmentServiceGrpc + .CanonicalPreseededActorAssignmentServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + return CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withCompression("gzip"); + } + + /** Reads the actual retained projection; this call never allocates or renews authority. */ + public RuntimeActorReference read(ReadPreseededActorRuntimeReferenceRequest request) { + requireNoAmbientSql("Runtime reference RPC requires no ambient SQL"); + requireRequest(request); + var response = + requireInitializedStub("Entity runtime reference client is unavailable") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(MAX_REQUEST_BYTES) + .readPreseededActorRuntimeReference(request); + requireResponse(request, response); + return new RuntimeActorReference(namespace, response); + } + + private static void requireRequest(ReadPreseededActorRuntimeReferenceRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSchemaVersion() != SCHEMA_VERSION + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasExpectedTarget() + || request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException("Closed complete schema-1 assignment request required"); + } + var target = request.getExpectedTarget(); + if (!target.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Assignment request contains unknown fields"); + } + + requireCanonicalNonNilUuid(request.getAssignmentUuid(), "assignment_uuid"); + requireCanonicalNonNilUuid(request.getCanonicalAccountUuid(), "canonical_account_uuid"); + requireCanonicalNonNilUuid(request.getCharacterUuid(), "character_uuid"); + requireCanonicalNonNilUuid(target.getCanonicalTenantUuid(), "canonical_tenant_uuid"); + requireCanonicalNonNilUuid(target.getRealmUuid(), "realm_uuid"); + requireCanonicalNonNilUuid(target.getCanonicalVersionUuid(), "canonical_version_uuid"); + requireCanonicalNonNilUuid( + target.getPlayableStateNamespaceUuid(), "playable_state_namespace_uuid"); + if (!RealmEntryPolicy.isCanonicalSlug(target.getWorldSlug()) + || !RealmEntryPolicy.isCanonicalSlug(target.getRealmSlug())) { + throw new IllegalArgumentException("Assignment target requires canonical realm selectors"); + } + requireBoundedText(target.getGameInstanceId(), "game_instance_id", MAX_GAME_INSTANCE_ID_LENGTH); + if (target.getCatalogRevision() <= 0L) { + throw new IllegalArgumentException("catalog_revision must be positive"); + } + requireDigest(target.getFrozenPolicyDigest(), "frozen_policy_digest"); + requireBoundedText( + target.getPublishedReleaseBundleRef(), + "published_release_bundle_ref", + MAX_RELEASE_REF_LENGTH); + if (target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + && target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) { + throw new IllegalArgumentException("playable_state_scope must be SHARED or ISOLATED"); + } + requireDigest(request.getIntentDigest(), "intent_digest"); + } + + private static void requireResponse( + ReadPreseededActorRuntimeReferenceRequest request, + ReadPreseededActorRuntimeReferenceResponse response) { + if (response == null + || response.getSerializedSize() > MAX_RESPONSE_BYTES + || response.getSchemaVersion() != SCHEMA_VERSION + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasExpectedTarget() + || !response.hasCorePayload() + || !request.getExpectedTarget().equals(response.getExpectedTarget()) + || !request.getAssignmentUuid().equals(response.getAssignmentUuid()) + || !request.getCanonicalAccountUuid().equals(response.getCanonicalAccountUuid()) + || !request.getCharacterUuid().equals(response.getCharacterUuid()) + || !request.getIntentDigest().equals(response.getIntentDigest()) + || response.getRuntimeEntityId() <= 0L + || response.getProjectionGeneration() <= 0L + || response.getProjectionFence() <= 0L) { + throw invalidResponse( + "Entity changed the exact original assignment, target, identity or projection"); + } + var core = response.getCorePayload(); + if (!core.getUnknownFields().asMap().isEmpty() + || core.getActorKind() + != CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) { + throw invalidResponse("Entity returned an open or unsupported actor core"); + } + try { + requireDigest(response.getPublishedOwnerProofDigest(), "published_owner_proof_digest"); + requireDisplayName(core.getDisplayName()); + } catch (IllegalArgumentException malformed) { + throw invalidResponse("Entity returned malformed assignment provenance", malformed); + } + } + + /** Numeric runtime entity identity qualified by its actual Entity-owned scope. */ + public static final class RuntimeEntityId { + private final UUID tenantId; + private final String gameInstanceId; + private final long value; + + private RuntimeEntityId(UUID tenantId, String gameInstanceId, long value) { + this.tenantId = tenantId; + this.gameInstanceId = gameInstanceId; + this.value = value; + } + + public UUID tenantId() { + return tenantId; + } + + public String gameInstanceId() { + return gameInstanceId; + } + + public long value() { + return value; + } + + @Override + public boolean equals(Object other) { + return other instanceof RuntimeEntityId id + && value == id.value + && tenantId.equals(id.tenantId) + && gameInstanceId.equals(id.gameInstanceId); + } + + @Override + public int hashCode() { + return Objects.hash(tenantId, gameInstanceId, value); + } + } + + /** Constructible only after an authenticated, exact, closed Entity response passes validation. */ + public static final class RuntimeActorReference { + private final String workloadNamespace; + private final ReadPreseededActorRuntimeReferenceResponse receipt; + private final RuntimeEntityId runtimeEntityId; + + private RuntimeActorReference( + String workloadNamespace, ReadPreseededActorRuntimeReferenceResponse receipt) { + this.workloadNamespace = workloadNamespace; + this.receipt = receipt; + this.runtimeEntityId = + new RuntimeEntityId( + UUID.fromString(receipt.getExpectedTarget().getCanonicalTenantUuid()), + receipt.getExpectedTarget().getGameInstanceId(), + receipt.getRuntimeEntityId()); + } + + public String workloadNamespace() { + return workloadNamespace; + } + + public RuntimeEntityId runtimeEntityId() { + return runtimeEntityId; + } + + public long projectionGeneration() { + return receipt.getProjectionGeneration(); + } + + public long projectionFence() { + return receipt.getProjectionFence(); + } + + public UUID assignmentUuid() { + return UUID.fromString(receipt.getAssignmentUuid()); + } + + public UUID canonicalAccountUuid() { + return UUID.fromString(receipt.getCanonicalAccountUuid()); + } + + public UUID characterUuid() { + return UUID.fromString(receipt.getCharacterUuid()); + } + + public String intentDigest() { + return receipt.getIntentDigest(); + } + + public UUID playableStateNamespaceId() { + return UUID.fromString(receipt.getExpectedTarget().getPlayableStateNamespaceUuid()); + } + + public net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget + target() { + return receipt.getExpectedTarget(); + } + + public String publishedOwnerProofDigest() { + return receipt.getPublishedOwnerProofDigest(); + } + + public net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentCorePayload + corePayload() { + return receipt.getCorePayload(); + } + } + + private static void requireDisplayName(String value) { + if (value == null + || value.isBlank() + || !value.equals(value.trim()) + || value.codePointCount(0, value.length()) > MAX_DISPLAY_NAME_CODE_POINTS + || containsUnpairedSurrogate(value) + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("display_name must be bounded printable text"); + } + } + + private static void requireBoundedText(String value, String field, int maxLength) { + if (value == null + || value.isBlank() + || !value.equals(value.trim()) + || value.length() > maxLength + || containsUnpairedSurrogate(value) + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(field + " is incomplete or outside its text bound"); + } + } + + private static boolean containsUnpairedSurrogate(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } + + private static void requireDigest(String value, String field) { + if (value == null || !RAW_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be raw lowercase SHA-256 hex"); + } + } + + private static void requireCanonicalNonNilUuid(String value, String field) { + try { + DraftAuthorizationFenceBinding.canonicalUuid(value); + if ("00000000-0000-0000-0000-000000000000".equals(value)) { + throw new IllegalArgumentException("nil UUID is not allowed"); + } + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", invalid); + } + } + + private static IllegalStateException invalidResponse(String message) { + return new IllegalStateException( + "Entity preseeded actor runtime reference response is invalid: " + message); + } + + private static IllegalStateException invalidResponse(String message, Throwable cause) { + return new IllegalStateException( + "Entity preseeded actor runtime reference response is invalid: " + message, cause); + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1040.4__human_completion_exact_original_launch_binding.sql b/services/game-session-service/src/main/resources/db/migration/V1040.4__human_completion_exact_original_launch_binding.sql new file mode 100644 index 0000000000..e50ff12730 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1040.4__human_completion_exact_original_launch_binding.sql @@ -0,0 +1,98 @@ +-- Bind each completion row to its own exact original owner and captured launch tuple. +-- Existing Java and attempt guards remain; retained rows and prior migrations are unchanged. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_game_session_canonical_human_runtime_completion() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime game_instances%ROWTYPE; + launch game_session_canonical_instance_launch%ROWTYPE; + intent game_session_canonical_initial_admission_intent%ROWTYPE; + attempt game_session_canonical_initial_admission_attempt%ROWTYPE; + original game_session_start_session_operator_attempt%ROWTYPE; +BEGIN + SELECT * INTO launch FROM game_session_canonical_instance_launch + WHERE target_namespace=NEW.target_namespace + AND game_instance_uuid=NEW.canonical_game_instance_id; + SELECT * INTO runtime FROM game_instances + WHERE tenant_id=NEW.game_session_tenant_id AND id=NEW.game_instance_id; + SELECT * INTO intent FROM game_session_canonical_initial_admission_intent + WHERE target_namespace=NEW.target_namespace + AND initial_admission_request_id=NEW.initial_admission_request_id; + SELECT * INTO attempt FROM game_session_canonical_initial_admission_attempt + WHERE target_namespace=NEW.target_namespace + AND initial_admission_request_id=NEW.initial_admission_request_id; + SELECT * INTO original FROM game_session_start_session_operator_attempt + WHERE target_namespace=NEW.target_namespace + AND owner_attempt_id=NEW.original_owner_attempt_id + AND control_plane_request_id=NEW.control_plane_request_id; + + IF launch.target_namespace IS NULL OR runtime.id IS NULL OR intent.target_namespace IS NULL + OR attempt.target_namespace IS NULL OR original.target_namespace IS NULL + OR runtime.status IS DISTINCT FROM 'RUNNING' + OR runtime.row_version IS DISTINCT FROM NEW.completed_running_row_version + OR launch.captured_starting_row_version IS DISTINCT FROM NEW.captured_starting_row_version + OR launch.game_session_tenant_id IS DISTINCT FROM NEW.game_session_tenant_id + OR launch.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR launch.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR launch.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR launch.canonical_realm_id IS DISTINCT FROM NEW.realm_id + OR launch.world_slug IS DISTINCT FROM NEW.world_slug + OR launch.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR launch.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR launch.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR launch.complete_launch_binding_evidence->'descriptor'->>'requestDigest' + IS DISTINCT FROM NEW.descriptor_request_digest + OR launch.complete_launch_binding_evidence->'descriptor'->>'resultDigest' + IS DISTINCT FROM NEW.descriptor_result_digest + OR launch.complete_launch_binding_evidence->'releaseAttestation'->>'evidenceDigest' + IS DISTINCT FROM NEW.release_attestation_digest + OR intent.state IS DISTINCT FROM 'HOLD_ATTACHED' + OR intent.request_digest IS DISTINCT FROM NEW.request_digest + OR intent.hold_identity_bytes IS NULL + OR intent.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR attempt.status IS DISTINCT FROM 'PENDING' + OR attempt.request_digest IS DISTINCT FROM NEW.request_digest + OR attempt.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR attempt.world_slug IS DISTINCT FROM NEW.world_slug + OR attempt.realm_id IS DISTINCT FROM NEW.realm_id + OR attempt.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR attempt.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR attempt.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR attempt.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR attempt.active_lifecycle_epoch IS DISTINCT FROM NEW.active_lifecycle_epoch + OR attempt.expected_catalog_revision IS DISTINCT FROM NEW.expected_catalog_revision + OR attempt.origin_kind IS DISTINCT FROM NEW.origin_kind + OR attempt.expected_prior_pointer_version IS DISTINCT FROM NEW.expected_prior_pointer_version + OR attempt.hold_id IS DISTINCT FROM NEW.hold_id + OR attempt.hold_fence IS DISTINCT FROM NEW.hold_fence + OR attempt.hold_binding_digest IS DISTINCT FROM NEW.hold_binding_digest + OR attempt.account_protection_id IS DISTINCT FROM NEW.account_protection_id + OR attempt.account_protection_fence IS DISTINCT FROM NEW.account_protection_fence + OR attempt.original_owner_attempt_id IS DISTINCT FROM NEW.original_owner_attempt_id + OR attempt.original_owner_mutation_id IS DISTINCT FROM NEW.original_owner_mutation_id + OR attempt.original_owner_fence IS DISTINCT FROM NEW.original_owner_fence + OR attempt.account_protection_evidence_bytes IS DISTINCT FROM NEW.account_protection_evidence_bytes + OR original.owner_mutation_id IS DISTINCT FROM NEW.original_owner_mutation_id + OR original.owner_fence IS DISTINCT FROM NEW.original_owner_fence + OR original.phase_state IS DISTINCT FROM 'OWNER_EXECUTION_PENDING' + OR original.lease_expires_at <= clock_timestamp() + OR original.post_authorization_execution_tuple IS DISTINCT FROM NEW.original_start_session_tuple + OR launch.original_start_session_tuple IS DISTINCT FROM NEW.original_start_session_tuple + OR original.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR original.account_redemption_projection IS DISTINCT FROM NEW.account_redemption_projection + OR EXISTS (SELECT 1 FROM gameplay_admission_pointer p + WHERE p.target_namespace=NEW.target_namespace + AND p.initial_admission_request_id=NEW.initial_admission_request_id) + OR EXISTS (SELECT 1 FROM gameplay_admission_pointer_event e + WHERE e.target_namespace=NEW.target_namespace + AND e.initial_admission_request_id=NEW.initial_admission_request_id) + THEN + RAISE EXCEPTION 'Human runtime completion requires exact pending protection, live original owner, attached hold, and RUNNING CAS' + USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1038.5__current_issuer_local_operation_membership.sql b/services/game-session-service/src/main/resources/db/migration/V1040.5__current_issuer_local_operation_membership.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V1038.5__current_issuer_local_operation_membership.sql rename to services/game-session-service/src/main/resources/db/migration/V1040.5__current_issuer_local_operation_membership.sql diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua index dce9a79f69..a76293aa47 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-binding-local-retirement.lua @@ -253,7 +253,7 @@ for _, operation in ipairs(operations) do end end for field, value in pairs(baseline) do - if redis.call('HGET', KEYS[1], field) ~= value then return -1 end + if actualFields[field] ~= value then return -1 end end if actualCapacity > tonumber(plannedPartitionCapacity) or actualReservations < baselineReservations diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json index efb9348e9b..ae3d9820b1 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-binding-local-retirement.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.issuer-binding-local-retirement.v1", "resourcePath": "redis/lua/game-session-issuer-binding-local-retirement.lua", - "sha256": "6454e04296ca915004d53175dc70d1b113ed1e0a4bf612ea4b0b6516da51e756", + "sha256": "65afdf95a21a25ea872c97dfe79fb808740389c0fd877249b47ba4605f739e8e", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java index 61af829daa..f8d6c3c323 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -565,7 +565,7 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { var anchor = initialCoverageOwner(dsl, () -> state) .completeInitialBootstrap(intent.operationId(), intent.requestId()); - // This historical phase has no V1038.5 membership table. Adapt only its slot-count read; + // This historical phase has no V1040.5 membership table. Adapt only its slot-count read; // registration still uses the actual owner and all enabled old-schema guards. This does not // qualify the new membership gate before that schema exists. AtomicInteger oldPhaseSlotCountSubstitutions = new AtomicInteger(); @@ -738,7 +738,8 @@ public void renderEnd(ExecuteContext context) { context.sql(oldSlotCount); } else if (sql != null && sql.contains("game_session_canonical_issuer_current_local_operation")) { - throw new AssertionError("Unexpected membership read in the pre-V1038.5 producer"); + throw new AssertionError( + "Unexpected membership read in the pre-V1040.5 producer"); } } })); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index 31156f1e82..8edbe68d66 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -581,6 +581,70 @@ void accountControlAdvancePreservesUnrelatedCapacityDuringOriginalRetirement() { } } + @Test + void retirementRequiresAndPreservesExactSeededBaselineSnapshot() throws Exception { + // Sibling cases retain Redis hashes, so use a distinct layout for the seeded baseline. + try (var fixture = newFixture(BigInteger.valueOf(13), BigInteger.ONE, 1)) { + assertThat(fixture.originalBaselineReservationCount()).isOne(); + assertThat(fixture.originalBaselineBindingCount()).isOne(); + fixture.publishOriginalWithControlledAccountLease(); + assertThat(fixture.recordOriginalAccountAbort().isAccountAborted()).isTrue(); + var pendingRelease = fixture.prepareIssuerRelease(); + var releaseReadback = fixture.projectIssuerRelease(pendingRelease); + var release = fixture.completeIssuerRelease(pendingRelease, releaseReadback); + assertThat(release.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + + var pendingRetirement = fixture.prepareIssuerRetirement(fixture.transitionId()); + var baseline = + fixture.readPreparedPartitionWork(release.originalOperation()).baselineFields(); + var baselineCapacity = + baseline.entrySet().stream() + .filter( + entry -> + entry + .getKey() + .startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec + .RESERVATION_FIELD_PREFIX)) + .findFirst() + .orElseThrow(); + byte[] baselineCapacityField = baselineCapacity.getKey().getBytes(StandardCharsets.US_ASCII); + byte[] partitionKey = fixture.issuerPartitionKey(); + byte[] beforeRetirement = physicalFieldSet(partitionKey); + String historyBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); + String headBefore = partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); + String retirementBefore = retirementImage(fixture.dsl(), fixture.transitionId()); + List membershipBefore = currentOperationIds(fixture.dsl()); + LuaInvocation invocation = retirementInvocation(fixture, pendingRetirement); + + administratorCommands.hdel(partitionKey, new byte[][] {baselineCapacityField}); + byte[] missingBaseline = physicalFieldSet(partitionKey); + assertThat(evaluate(invocation)).isEqualTo(-1L); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(missingBaseline); + + administratorCommands.hset( + partitionKey, baselineCapacityField, release.exactReleasedMemberValueBytes()); + byte[] mismatchedBaseline = physicalFieldSet(partitionKey); + assertThat(evaluate(invocation)).isEqualTo(-1L); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(mismatchedBaseline); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(historyBefore); + assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) + .isEqualTo(headBefore); + assertThat(retirementImage(fixture.dsl(), fixture.transitionId())) + .isEqualTo(retirementBefore); + assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBefore); + + administratorCommands.hset(partitionKey, baselineCapacityField, baselineCapacity.getValue()); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeRetirement); + assertThat(fixture.retireIssuerCapacity(pendingRetirement).scriptOutcome()).isEqualTo(1L); + byte[] afterRetirement = physicalFieldSet(partitionKey); + assertRetirementFieldDelta(beforeRetirement, afterRetirement, pendingRetirement); + var retiredFields = decodeFields(afterRetirement); + baseline.forEach((field, value) -> assertThat(retiredFields.get(field)).isEqualTo(value)); + } + } + @Test void retirementRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() throws Exception { try (var fixture = newFixture(BigInteger.valueOf(6), BigInteger.ONE, 0)) { @@ -659,7 +723,8 @@ void postRetirementSqlRejectsUnaccountedCurrentReservationInAnotherPartition() t @Test void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceMismatch() { - try (var fixture = newFixture(BigInteger.valueOf(3), BigInteger.ONE, 1)) { + // A seeded baseline needs its own physical layout; sibling cases retain their issuer hashes. + try (var fixture = newFixture(BigInteger.valueOf(11), BigInteger.ONE, 1)) { UUID originalId = fixture.originalOperationId(); List membershipBefore = currentOperationIds(fixture.dsl()); String originalBefore = localOperationImage(fixture.dsl(), originalId); @@ -714,7 +779,7 @@ void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceM assertThat( transaction.execute( "UPDATE game_session_canonical_issuer_partition_reservation reservation" - + " SET coverage_fence = coverage_fence + 1" + + " SET coverage_fence = reservation.coverage_fence + 1" + " FROM game_session_canonical_issuer_binding_local_operation original" + " WHERE original.operation_id = ?" + " AND reservation.reservation_id = original.reservation_id", @@ -722,6 +787,8 @@ void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceM .isOne(); })) .isInstanceOf(org.jooq.exception.DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) .hasMessageContaining("exact installed local-operation source"); assertThatThrownBy( () -> @@ -737,7 +804,7 @@ void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceM assertThat( transaction.execute( "UPDATE game_session_canonical_issuer_partition_reservation reservation" - + " SET coverage_fence = coverage_fence + 1" + + " SET coverage_fence = reservation.coverage_fence + 1" + " FROM game_session_canonical_issuer_installed_anchor anchor" + " JOIN game_session_canonical_issuer_partition_build_cohort_row cohort" + " ON cohort.build_operation_id = anchor.build_operation_id" @@ -748,6 +815,8 @@ void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceM .isOne(); })) .isInstanceOf(org.jooq.exception.DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) .hasMessageContaining( "Installed issuer reservation requires exact bootstrap or current local-operation membership"); assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBefore); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java index 45bfbc28f1..af2ee3e76a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java @@ -326,6 +326,200 @@ public ExpectedClosedEvidence lockExpectedClosedForRealm( } } + @Test + void protectedClosedAbortRetainsImmutableOriginAfterSyntheticCurrentPointerRemoval() + throws Exception { + var harness = CanonicalInitialAdmissionIntentRepositoryIntegrationTest.harness(postgres); + try { + var target = harness.seed(); + var catalog = target.catalog(); + var pointers = + new GameSessionCanonicalAdmissionPointerRepository( + harness.dsl(), + new GameSessionCanonicalRealmCatalogRepository(harness.dsl()), + new GameplayAdmissionPointerEventRepository(harness.dsl())); + var closeRequest = + new net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest( + uuid(1299), + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.creationRequestId(), + catalog.catalogRevision(), + "controlled-closed-owner", + "Immutable CLOSED origin for synthetic missing-pointer storage proof"); + var closed = pointers.prepareInitialClosed(closeRequest); + harness.transactions().executeWithoutResult(status -> pointers.createInitialClosed(closed)); + var origin = + pointers + .readOriginalClosedOrigin(catalog.targetNamespace(), closeRequest.requestId()) + .orElseThrow(); + Prepared prepared = prepare(target, "protected-closed-missing-pointer", 1281, true); + var repository = repository(harness); + harness + .transactions() + .executeWithoutResult( + status -> repository.reserveProtected(prepared.request(), prepared.protection())); + Record pending = terminal(harness, prepared.request()); + assertThat(pending.get("status", String.class)).isEqualTo("PENDING"); + assertThat(pending.get("account_protection_id", UUID.class)) + .isEqualTo(prepared.protection().accountProtectionId()); + assertThat(pending.get("account_protection_evidence_bytes", byte[].class)) + .containsExactly(prepared.protection().canonicalBytes()); + String catalogBefore = + harness.dsl().fetch("SELECT * FROM game_session_canonical_realm_catalog").formatJSON(); + String originBefore = + harness + .dsl() + .fetch("SELECT * FROM game_session_canonical_closed_admission_pointer_request") + .formatJSON(); + String auditBefore = + harness + .dsl() + .fetch("SELECT * FROM gameplay_admission_pointer_event ORDER BY id") + .formatJSON(); + Long pointerId = + harness + .dsl() + .fetchSingle( + "SELECT id FROM gameplay_admission_pointer WHERE representation_version = 2 " + + "AND target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId()) + .get("id", Long.class); + // Isolate only survivor immutability for one synthetic setup DELETE in this disposable + // schema. This is not an issued writer or an independently advanced OPEN route. No guard + // is exempted during the actual abort, and the immutable origin/catalog/audit stay intact. + harness + .dsl() + .execute( + "ALTER TABLE gameplay_admission_pointer DISABLE TRIGGER " + + "gameplay_admission_pointer_canonical_immutable"); + try { + harness + .transactions() + .executeWithoutResult( + status -> + assertThat( + harness + .dsl() + .execute( + "DELETE FROM gameplay_admission_pointer WHERE id = ? " + + "AND representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ?", + pointerId, + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId())) + .isEqualTo(1)); + } finally { + harness + .dsl() + .execute( + "ALTER TABLE gameplay_admission_pointer ENABLE TRIGGER " + + "gameplay_admission_pointer_canonical_immutable"); + } + assertThat( + harness + .dsl() + .fetchSingle( + "SELECT tgenabled::text AS enabled FROM pg_trigger " + + "WHERE tgrelid = 'gameplay_admission_pointer'::regclass " + + "AND tgname = 'gameplay_admission_pointer_canonical_immutable'") + .get("enabled", String.class)) + .isEqualTo("O"); + assertThat( + harness + .dsl() + .fetchSingle( + "SELECT count(*) AS disabled FROM pg_trigger trigger_row " + + "JOIN pg_class relation ON relation.oid = trigger_row.tgrelid " + + "WHERE relation.relnamespace = current_schema()::regnamespace " + + "AND trigger_row.tgenabled NOT IN ('O', 'A')") + .get("disabled", Long.class)) + .isZero(); + assertThat(harness.dsl().fetchCount(org.jooq.impl.DSL.table("gameplay_admission_pointer"))) + .isZero(); + assertThat(terminal(harness, prepared.request()).formatJSON()) + .isEqualTo(pending.formatJSON()); + assertThat( + pointers.readOriginalClosedOrigin( + catalog.targetNamespace(), closeRequest.requestId())) + .contains(origin); + + harness + .transactions() + .executeWithoutResult( + status -> + repository.abortProtected( + prepared.request(), + prepared.protection(), + "synthetic current pointer missing")); + Record aborted = terminal(harness, prepared.request()); + assertThat(aborted.get("status", String.class)).isEqualTo("ABORTED"); + assertThat(aborted.get("prior_pointer_request_id", UUID.class)).isEqualTo(origin.requestId()); + assertThat(aborted.get("prior_pointer_request_digest", String.class)) + .isEqualTo(origin.requestDigest()); + assertThat(aborted.get("prior_pointer_audit_event_id", Long.class)) + .isEqualTo(origin.auditEventId()); + assertThat(aborted.get("account_protection_id", UUID.class)) + .isEqualTo(prepared.protection().accountProtectionId()); + assertThat(aborted.get("account_protection_evidence_bytes", byte[].class)) + .containsExactly(prepared.protection().canonicalBytes()); + assertThat(aborted.get("pointer_id")).isNull(); + assertThat(aborted.get("pointer_version")).isNull(); + assertThat(aborted.get("audit_event_id")).isNull(); + var proof = + repository + .read( + prepared.request().targetNamespace(), + prepared.request().initialAdmissionRequestId()) + .orElseThrow(); + harness + .transactions() + .executeWithoutResult( + status -> + repository.abortProtected( + prepared.request(), + prepared.protection(), + "synthetic current pointer missing")); + assertThat(terminal(harness, prepared.request()).formatJSON()) + .isEqualTo(aborted.formatJSON()); + assertThat( + repository.read( + prepared.request().targetNamespace(), + prepared.request().initialAdmissionRequestId())) + .contains(proof); + assertThat(harness.dsl().fetchCount(org.jooq.impl.DSL.table("gameplay_admission_pointer"))) + .isZero(); + assertThat( + harness + .dsl() + .fetch("SELECT * FROM game_session_canonical_realm_catalog") + .formatJSON()) + .isEqualTo(catalogBefore); + assertThat( + harness + .dsl() + .fetch("SELECT * FROM game_session_canonical_closed_admission_pointer_request") + .formatJSON()) + .isEqualTo(originBefore); + assertThat( + harness + .dsl() + .fetch("SELECT * FROM gameplay_admission_pointer_event ORDER BY id") + .formatJSON()) + .isEqualTo(auditBefore); + assertThat( + pointers.readOriginalClosedOrigin( + catalog.targetNamespace(), closeRequest.requestId())) + .contains(origin); + } finally { + harness.close(); + } + } + @Test void commitsOneProtectionBoundPointerAuditAttemptAndIntentWithExactReplay() throws Exception { var harness = CanonicalInitialAdmissionIntentRepositoryIntegrationTest.harness(postgres); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java new file mode 100644 index 0000000000..d3df8383a4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java @@ -0,0 +1,235 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPreseededActorAssignmentServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentCorePayload; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** Controlled loopback source and test PKI: no actual Entity SQL or production custody proof. */ +@Timeout(60) +class CanonicalPreseededActorRuntimeReferenceClientMtlsTest { + private static final String NAMESPACE = "game-session-test"; + private static final String GAME_SESSION_PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final String CHARACTER_UUID = "22222222-2222-4222-8222-222222222222"; + private static final String INTENT_DIGEST = "a".repeat(64); + + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Preseeded actor assignment test CA", + new LoopbackMtlsTestPki.IdentitySpec("client", GAME_SESSION_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "entity-server", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service", + true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-role", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", + true), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign-namespace", + "spiffe://firemud/ns/other/sa/entity-management-service", + true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-client", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", + false), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign-client", "spiffe://firemud/ns/other/sa/game-session-service", false)); + } + + @Test + void initializedClientReturnsClosedResponseFromSameNamespaceEntityPeer() throws Exception { + exercise("entity-server", true); + } + + @Test + void sameCaWrongServerRoleAndForeignNamespaceAreRejectedBeforeHandler() throws Exception { + for (String identity : List.of("wrong-role", "foreign-namespace")) { + exercise(identity, false); + } + } + + @Test + void controlledReceiverRejectsWrongCallerPurposeAndNamespace() throws Exception { + exercise("entity-server", false, "wrong-client"); + exercise("entity-server", false, "foreign-client"); + } + + private static void exercise(String identity, boolean accepted) throws Exception { + exercise(identity, accepted, "client"); + } + + private static void exercise(String identity, boolean accepted, String caller) throws Exception { + var request = request(); + var response = assignedResponse(request); + var handlerInvocations = new AtomicInteger(); + var observedRequest = new AtomicReference(); + var observedPeer = new AtomicReference(); + var service = + new CanonicalPreseededActorAssignmentServiceGrpc + .CanonicalPreseededActorAssignmentServiceImplBase() { + @Override + public void readPreseededActorRuntimeReference( + ReadPreseededActorRuntimeReferenceRequest request, + StreamObserver observer) { + handlerInvocations.incrementAndGet(); + observedRequest.set(request); + var peer = GrpcPeerIdentity.current(); + observedPeer.set(peer == null ? null : peer.uri()); + if (peer == null || !GAME_SESSION_PEER.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + }; + Server server = server(identity, service); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("localhost:" + server.getPort()); + try (var client = + new CanonicalPreseededActorRuntimeReferenceClient( + endpoints, + pki.clientProperties(directory, pki.identity(caller)), + new GrpcChannelFactory(), + NAMESPACE)) { + client.init(); + if (accepted) { + var reference = client.read(request); + assertThat(reference.runtimeEntityId().value()).isEqualTo(response.getRuntimeEntityId()); + assertThat(reference.runtimeEntityId().tenantId().toString()) + .isEqualTo(request.getExpectedTarget().getCanonicalTenantUuid()); + assertThat(reference.runtimeEntityId().gameInstanceId()) + .isEqualTo(request.getExpectedTarget().getGameInstanceId()); + assertThat(reference.characterUuid().toString()).isEqualTo(request.getCharacterUuid()); + assertThat(reference.assignmentUuid().toString()).isEqualTo(request.getAssignmentUuid()); + assertThat(reference.target()).isEqualTo(request.getExpectedTarget()); + assertThat(reference.projectionGeneration()).isEqualTo(1); + assertThat(reference.projectionFence()).isEqualTo(1); + assertThat(reference.publishedOwnerProofDigest()) + .isEqualTo(response.getPublishedOwnerProofDigest()); + assertThat(handlerInvocations).hasValue(1); + assertThat(observedRequest.get()).isEqualTo(request); + assertThat(observedPeer.get()).isEqualTo(GAME_SESSION_PEER); + } else { + assertThatThrownBy(() -> client.read(request)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> { + assertThat(failure.getStatus().getCode()) + .isEqualTo( + caller.equals("client") + ? Status.Code.UNAUTHENTICATED + : Status.Code.PERMISSION_DENIED); + }); + if (caller.equals("client")) { + assertThat(handlerInvocations).hasValue(0); + assertThat(observedRequest.get()).isNull(); + assertThat(observedPeer.get()).isNull(); + } else { + assertThat(handlerInvocations).hasValue(1); + } + } + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static Server server( + String identity, + CanonicalPreseededActorAssignmentServiceGrpc.CanonicalPreseededActorAssignmentServiceImplBase + service) + throws Exception { + var serverIdentity = pki.identity(identity); + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(serverIdentity), + pki.trustManagerFactory(), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + factory.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + return factory.createServer().start(); + } + + private static ReadPreseededActorRuntimeReferenceRequest request() { + return ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid("11111111-1111-4111-8111-111111111111") + .setCanonicalAccountUuid("33333333-3333-4333-8333-333333333333") + .setExpectedTarget( + PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid("44444444-4444-4444-8444-444444444444") + .setRealmUuid("55555555-5555-4555-8555-555555555555") + .setWorldSlug("outer-reach") + .setRealmSlug("green-march") + .setGameInstanceId("opaque-instance:preserved") + .setCatalogRevision(7L) + .setCanonicalVersionUuid("66666666-6666-4666-8666-666666666666") + .setFrozenPolicyDigest("b".repeat(64)) + .setPlayableStateNamespaceUuid("77777777-7777-4777-8777-777777777777") + .setPublishedReleaseBundleRef("release:bounded/v1") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .setCharacterUuid(CHARACTER_UUID) + .setIntentDigest(INTENT_DIGEST) + .build(); + } + + private static ReadPreseededActorRuntimeReferenceResponse assignedResponse( + ReadPreseededActorRuntimeReferenceRequest request) { + return ReadPreseededActorRuntimeReferenceResponse.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(request.getAssignmentUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setCharacterUuid(request.getCharacterUuid()) + .setIntentDigest(request.getIntentDigest()) + .setExpectedTarget(request.getExpectedTarget()) + .setPublishedOwnerProofDigest("c".repeat(64)) + .setRuntimeEntityId(7301L) + .setProjectionGeneration(1) + .setProjectionFence(1) + .setCorePayload( + PreseededActorAssignmentCorePayload.newBuilder() + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .setDisplayName("Pilot One")) + .build(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java new file mode 100644 index 0000000000..4bf0927355 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java @@ -0,0 +1,224 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import java.lang.reflect.Modifier; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPreseededActorAssignmentServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentCorePayload; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Controlled response validation only; no mTLS, persistence or production authority claim. */ +class CanonicalPreseededActorRuntimeReferenceClientTest { + private static final String NAMESPACE = "game-session-test"; + private static final String CHARACTER_UUID = "22222222-2222-4222-8222-222222222222"; + private static final String INTENT_DIGEST = "a".repeat(64); + @TempDir Path directory; + + @Test + void privateReferenceConstructionAndActualRpcHaveFiniteDeadlineAndBounds() throws Exception { + for (var constructor : + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference.class + .getDeclaredConstructors()) { + assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); + } + var stub = stub(); + when(stub.readPreseededActorRuntimeReference(request())) + .thenReturn(assignedResponse(request())); + try (var client = client(stub)) { + var ref = client.read(request()); + assertThat(ref.runtimeEntityId().value()).isEqualTo(7301); + assertThat(ref.characterUuid().toString()).isEqualTo(CHARACTER_UUID); + assertThat(ref.workloadNamespace()).isEqualTo(NAMESPACE); + assertThat(ref.playableStateNamespaceId().toString()) + .isEqualTo(request().getExpectedTarget().getPlayableStateNamespaceUuid()); + verify(stub).withDeadlineAfter(20, TimeUnit.SECONDS); + verify(stub).withMaxInboundMessageSize(8192); + verify(stub).withMaxOutboundMessageSize(8192); + verify(stub).readPreseededActorRuntimeReference(request()); + verify(stub, never()).readPreseededActorAssignmentReceipt(any()); + } + } + + @Test + void rejectsChangedTupleDigestGenerationOpenCoreAndUnboundedResponses() throws Exception { + var base = assignedResponse(request()); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var malformed = + List.of( + base.toBuilder().setSchemaVersion(2).build(), + base.toBuilder().setUnknownFields(unknown).build(), + base.toBuilder().setAssignmentUuid("99999999-9999-4999-8999-999999999999").build(), + base.toBuilder() + .setCanonicalAccountUuid("99999999-9999-4999-8999-999999999999") + .build(), + base.toBuilder().setCharacterUuid("99999999-9999-4999-8999-999999999999").build(), + base.toBuilder().setIntentDigest("d".repeat(64)).build(), + base.toBuilder() + .setExpectedTarget( + base.getExpectedTarget().toBuilder().setGameInstanceId("replacement-instance")) + .build(), + base.toBuilder() + .setExpectedTarget( + base.getExpectedTarget().toBuilder() + .setPlayableStateNamespaceUuid("99999999-9999-4999-8999-999999999999")) + .build(), + base.toBuilder() + .setExpectedTarget(base.getExpectedTarget().toBuilder().setUnknownFields(unknown)) + .build(), + base.toBuilder().setRuntimeEntityId(0).build(), + base.toBuilder().setRuntimeEntityId(-1).build(), + base.toBuilder().setProjectionGeneration(0).build(), + base.toBuilder().setProjectionFence(0).build(), + base.toBuilder().setPublishedOwnerProofDigest("sha256:" + "b".repeat(64)).build(), + base.toBuilder().clearCorePayload().build(), + base.toBuilder() + .setCorePayload(base.getCorePayload().toBuilder().setUnknownFields(unknown)) + .build(), + base.toBuilder() + .setCorePayload(base.getCorePayload().toBuilder().setActorKindValue(999)) + .build(), + base.toBuilder() + .setCorePayload(base.getCorePayload().toBuilder().setDisplayName("x".repeat(9000))) + .build()); + var stub = stub(); + try (var client = client(stub)) { + for (var response : malformed) { + when(stub.readPreseededActorRuntimeReference(request())).thenReturn(response); + assertThatThrownBy(() -> client.read(request())).isInstanceOf(IllegalStateException.class); + } + } + } + + @Test + void rejectsInvalidSelectorsAndAmbientSqlBeforeActualRead() throws Exception { + var stub = stub(); + try (var client = client(stub)) { + for (var invalid : + List.of( + request().toBuilder().setSchemaVersion(2).build(), + request().toBuilder().clearExpectedTarget().build(), + request().toBuilder() + .setCharacterUuid("00000000-0000-0000-0000-000000000000") + .build(), + request().toBuilder().setIntentDigest("no").build(), + request().toBuilder() + .setExpectedTarget( + request().getExpectedTarget().toBuilder().setGameInstanceId("x".repeat(9000))) + .build())) { + assertThatThrownBy(() -> client.read(invalid)).isInstanceOf(IllegalArgumentException.class); + } + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(request())).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clear(); + } + verify(stub, never()).readPreseededActorRuntimeReference(any()); + } + } + + private CanonicalPreseededActorRuntimeReferenceClient client( + CanonicalPreseededActorAssignmentServiceGrpc + .CanonicalPreseededActorAssignmentServiceBlockingStub + stub) + throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "test-cert").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "test-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "test-ca").toString()); + var channels = mock(GrpcChannelFactory.class); + when(channels.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(mock(ManagedChannel.class)); + var client = + new CanonicalPreseededActorRuntimeReferenceClient( + new ServiceEndpointsProperties(), tls, channels, NAMESPACE); + client.init(); + ReflectionTestUtils.setField(client, "stub", stub); + return client; + } + + private static CanonicalPreseededActorAssignmentServiceGrpc + .CanonicalPreseededActorAssignmentServiceBlockingStub + stub() { + var stub = + mock( + CanonicalPreseededActorAssignmentServiceGrpc + .CanonicalPreseededActorAssignmentServiceBlockingStub.class); + when(stub.withDeadlineAfter(20, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withMaxInboundMessageSize(8192)).thenReturn(stub); + when(stub.withMaxOutboundMessageSize(8192)).thenReturn(stub); + return stub; + } + + private static ReadPreseededActorRuntimeReferenceRequest request() { + return ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid("11111111-1111-4111-8111-111111111111") + .setCanonicalAccountUuid("33333333-3333-4333-8333-333333333333") + .setExpectedTarget( + PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid("44444444-4444-4444-8444-444444444444") + .setRealmUuid("55555555-5555-4555-8555-555555555555") + .setWorldSlug("outer-reach") + .setRealmSlug("green-march") + .setGameInstanceId("opaque-instance:preserved") + .setCatalogRevision(7L) + .setCanonicalVersionUuid("66666666-6666-4666-8666-666666666666") + .setFrozenPolicyDigest("b".repeat(64)) + .setPlayableStateNamespaceUuid("77777777-7777-4777-8777-777777777777") + .setPublishedReleaseBundleRef("release:bounded/v1") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .setCharacterUuid(CHARACTER_UUID) + .setIntentDigest(INTENT_DIGEST) + .build(); + } + + private static ReadPreseededActorRuntimeReferenceResponse assignedResponse( + ReadPreseededActorRuntimeReferenceRequest request) { + return ReadPreseededActorRuntimeReferenceResponse.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(request.getAssignmentUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setCharacterUuid(request.getCharacterUuid()) + .setIntentDigest(request.getIntentDigest()) + .setExpectedTarget(request.getExpectedTarget()) + .setPublishedOwnerProofDigest("c".repeat(64)) + .setRuntimeEntityId(7301L) + .setProjectionGeneration(1) + .setProjectionFence(1) + .setCorePayload( + PreseededActorAssignmentCorePayload.newBuilder() + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .setDisplayName("Pilot One")) + .build(); + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V1044.1__canonical_initial_hold_precondition_status.sql b/services/world-management-service/src/main/resources/db/migration/V1044.1__canonical_initial_hold_precondition_status.sql new file mode 100644 index 0000000000..b89a3b6dbb --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1044.1__canonical_initial_hold_precondition_status.sql @@ -0,0 +1,26 @@ +-- A durable canonical initial-admission hold is a lifecycle precondition failure. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_guard_canonical_initial_admission_hold_lifecycle() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF (OLD.status IS DISTINCT FROM NEW.status + OR OLD.lifecycle_epoch IS DISTINCT FROM NEW.lifecycle_epoch) + AND EXISTS ( + SELECT 1 + FROM "${serviceSchema}".initial_admission_bind_hold h + WHERE h.tenant_id = OLD.tenant_id + AND h.game_instance_id = OLD.game_instance_id + AND h.canonical_request_bytes IS NOT NULL + AND h.status IN ('PENDING', 'RECONCILIATION_REQUIRED') + ) THEN + RAISE EXCEPTION 'World lifecycle is fenced by a canonical initial-admission hold' + USING ERRCODE = '55000'; + END IF; + RETURN NEW; +END; +$$; + +REVOKE ALL ON FUNCTION world_guard_canonical_initial_admission_hold_lifecycle() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index b8de421897..f8f8d607f3 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -1965,7 +1965,7 @@ private static void assertAbortedHoldStored( gate.commit(); var identity = acquiring.get(20, TimeUnit.SECONDS); - assertThat(transitioning.get(20, TimeUnit.SECONDS)).isEqualTo("40001"); + assertThat(transitioning.get(20, TimeUnit.SECONDS)).isEqualTo("55000"); var current = world .dsl() From e9efb96da9283938d128c004d6295fec4e96dd45 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:44:25 +1300 Subject: [PATCH 3/9] Qualify settlement extraction and isolate retained issuer proof layouts --- design/project-management/ai-observations.md | 5 +++++ .../player-access-and-session.md | 4 ++-- ...tialAdmissionSettlementReadClientTest.java | 21 ++++++------------- ...suerPhysicalRetirementIntegrationTest.java | 5 +++-- 4 files changed, 16 insertions(+), 19 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5c63f636f3..de40d54877 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -460,3 +460,8 @@ Entry format: - Observation: the production migration was present and executed in other schema contexts. A controlled historical SQL seed preserves the old assignment receipt, actor and snapshot without manufacturing a runtime projection or moving the test to the latest frontier. Current-schema assignments retain the production writer. Later shutdown connection noise is separate and its cause remains unproven. - Outcome: full Entity R722 executes 584 methods, with 519 passing, 46 failing on a missing placeholder in the new historical INSERT and 19 failing on separate PostgreSQL connection setup. R723 corrects only that placeholder and passes all 65 affected native cases with no skips; the 454 unit methods and other 65 native cases retain their R722 passing attribution. Enabled affected static analysis and formatting pass. The failed full-check aggregate remains recorded; the focused recovery does not relabel it as green. - Expected pattern: retain the exact pre-upgrade schema, source rows and history in migration proof. Use explicitly historical fixture input when current Java requires a later schema; do not add production compatibility branches or backfill authority merely to seed a test. + +- `2026-10-29`: Retained Redis layouts must be unique across combined fixture cases + - Context: The #3341 membership guard passed alone in R978, but its combined R981 run reused layout 11 already initialized by a sibling with different baseline data. Bootstrap correctly refused before the guard assertions. + - Outcome: Give the seeded guard layout 17 while retaining the existing layout 11 and snapshot layout 13 cases. R983 passes all three together; the original R981 aggregate remains failed. Production SQL and Redis guards are unchanged by this fixture repair. + - Expected pattern: Check the full class's retained key/layout identities when adding a physical fixture. An isolated pass does not establish shared-container isolation; run the actual former collision cases together after repair. 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 3cce1d5031..c7c0af64b1 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,9 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components -The initial Entity runtime-actor producer and passive Game Session reference client are separated from the later World/region bootstrap consumer. Fresh authenticated preseeded assignment allocates the retained numeric runtime projection in its existing Entity transaction; the distinct exact Game Session read never allocates or backfills historical assignments. The producer retains its original receipt semantics, V1022 SQL postimage, migration fixtures, and focused owner/security proof. This receiving extraction has not yet been validated. Production registration, runtime replacement, lifecycle cleanup registration, region ownership, protected admission and activation remain unqualified; the [Entity runtime owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) defines the bounded contract. +The initial Entity runtime-actor producer and passive Game Session reference client are separated from the later World/region bootstrap consumer. Fresh authenticated preseeded assignment allocates the retained numeric runtime projection in its existing Entity transaction; the distinct exact Game Session read never allocates or backfills historical assignments. The producer retains its original receipt semantics, V1022 SQL postimage, migration fixtures, and focused owner/security proof. R981 freshly passes all 27 selected Entity owner/security units and all 96 selected Entity PostgreSQL cases across the six affected assignment, runtime projection and historical-fixture suites. This qualifies the controlled receiving producer and its retained migrations; broader composition and production limits remain below. Production registration, runtime replacement, lifecycle cleanup registration, region ownership, protected admission and activation remain unqualified; the [Entity runtime owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) defines the bounded contract. -The current-membership correction prepares forward V1040.5 and SQL-maintained references to original unretired local operations. Projection, capacity, slot registration, ADD-mutation reads and retirement conflict checks use current ownership rather than enumerating lifetime immutable history; pending-retirement validation starts from the bounded partition heads. Existing immutable provenance and exact owner checks remain required. The native retirement proof now checks current membership through pending/lost-reply/completion rollback/exact retry and more than 256 lifetime cycles. Its migration fixture adapts only the historical pre-membership slot-count read, retaining actual old-schema guards and post-upgrade backfill/current reads; it does not qualify a new gate before its schema exists. R974 freshly passed 14 of its 15 selected native cases, including the 257-cycle turnover case, but failed aggregate validation on shared-layout fixture setup. R975 and R977 passed the historical-frontier upgrade/backfill case; their new negative-guard proof exposed assertion and SQL-qualification defects, corrected before R978 passed that guard case. V1040.5 passes the migration-frontier check after renumbering the unapplied correction above its parent. These passing executions cover 16 distinct membership-related native cases across the retained runs; the earlier failed aggregates remain failures, and final combined receiving validation remains pending. This does not establish registration, live issuer custody, activation or production admission. +The current-membership correction prepares forward V1040.5 and SQL-maintained references to original unretired local operations. Projection, capacity, slot registration, ADD-mutation reads and retirement conflict checks use current ownership rather than enumerating lifetime immutable history; pending-retirement validation starts from the bounded partition heads. Existing immutable provenance and exact owner checks remain required. The native retirement proof now checks current membership through pending/lost-reply/completion rollback/exact retry and more than 256 lifetime cycles. Its migration fixture adapts only the historical pre-membership slot-count read, retaining actual old-schema guards and post-upgrade backfill/current reads; it does not qualify a new gate before its schema exists. R974 freshly passed 14 of its 15 selected native cases, including the 257-cycle turnover case, but failed aggregate validation on shared-layout fixture setup. R975 and R977 passed the historical-frontier upgrade/backfill case; their new negative-guard proof exposed assertion and SQL-qualification defects, corrected before R978 passed that guard case. V1040.5 passes the migration-frontier check after renumbering the unapplied correction above its parent. These passing executions cover 16 distinct membership-related native cases across the retained runs; the earlier failed aggregates remain failures. The combined receiving R981 then passes 159 of 160 selected methods, including both actual World–Game Session–Account settlement compositions, but fails one membership fixture bootstrap because two cases reuse layout 11 with different baseline data. It also fails the full-SHA migration-frontier argument guard and a primitive-array varargs static warning in the new snapshot test. The fixture now uses its own layout 17, the test passes a named two-dimensional byte array, and R983 passes all three former-collision/snapshot cases together with integration Checkstyle, SpotBugs and formatting. All 160 distinct selected methods therefore have passing execution across R981/R983; R981 remains a failed aggregate. The complete immutable-parent frontier and final documentation checks are separate publication checks. This does not establish registration, live issuer custody, activation or production admission. The next protected-settlement correction versions both sides of the closed response and aligns the SQL `EXPECT_CLOSED` negative terminal with the existing immutable-origin contract through forward V1040.3. R970 passes 31 focused codec/client/verifier/service unit cases and one actual World–Game Session–Account acquisition composition, with enabled affected analysis, formatting and migration-frontier checks. Its aggregate fails the new later-request extension because that fixture reuses the same original owner attempt, which V1006 correctly permits only once. After removing that invalid extension, R971 passes the focused native protected-abort case and integration analysis/formatting. The native case proves actual competing-intent refusal while the first request is pending, original terminal/read/replay and unchanged pointer/audit. Its positive current-origin refusal remains controlled: neither result proves independent pointer advancement before abort or later-OPEN recovery. The separate current-inventory/retained-history turnover correction remains unfinished. diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java index 4855f92d70..f7693d6a4c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java @@ -130,8 +130,7 @@ void actualMtlsPreservesLargeCompleteProtectionAndTerminalAcrossExactReplay() th @Test void actualMtlsPreservesDefinitiveAbortAndRejectsInvalidOwnerResponses() throws Exception { - var evidence = - AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.ABORTED); + var evidence = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.ABORTED); var response = AccountInitialAdmissionSettlementReadGrpcCodec.toResponse(evidence); responder.set(input -> response); start("gs"); @@ -160,8 +159,7 @@ void actualMtlsPreservesDefinitiveAbortAndRejectsInvalidOwnerResponses() throws @Test void nativeTransportStatusesRemainUnchangedAndNoAutomaticRetryOccurs() throws Exception { - var evidence = - AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED); + var evidence = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED); start("gs"); client = newClient("account", NAMESPACE); client.init(); @@ -190,9 +188,7 @@ private void assertWrongServer(String identity) throws Exception { start(identity); client = newClient("account", NAMESPACE); client.init(); - var input = - AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED) - .input(); + var input = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED).input(); assertThatThrownBy(() -> client.read(input)) .satisfies( error -> @@ -206,9 +202,7 @@ void controlledReceiverRefusesNonAccountCertificateBeforeEvidenceDecode() throws start("gs"); client = newClient("entity", NAMESPACE); client.init(); - var input = - AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED) - .input(); + var input = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED).input(); assertThatThrownBy(() -> client.read(input)) .satisfies( error -> @@ -219,8 +213,7 @@ void controlledReceiverRefusesNonAccountCertificateBeforeEvidenceDecode() throws @Test void localNamespaceAndSqlFailBeforeAnyRpc() throws Exception { - var evidence = - AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED); + var evidence = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED); start("gs"); client = newClient("account", "other"); assertThatThrownBy(() -> client.read(evidence.input())) @@ -270,9 +263,7 @@ void requiresFileBackedTlsAndExplicitInitializationBeforeChannelUse() throws Exc LoopbackMtlsTestPki.placeholderTls(directory), factory, NAMESPACE); - var input = - AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED) - .input(); + var input = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED).input(); assertThatThrownBy(() -> client.read(input)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index 8edbe68d66..fb6ac4da76 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -618,7 +618,8 @@ void retirementRequiresAndPreservesExactSeededBaselineSnapshot() throws Exceptio List membershipBefore = currentOperationIds(fixture.dsl()); LuaInvocation invocation = retirementInvocation(fixture, pendingRetirement); - administratorCommands.hdel(partitionKey, new byte[][] {baselineCapacityField}); + byte[][] baselineCapacityFields = {baselineCapacityField}; + administratorCommands.hdel(partitionKey, baselineCapacityFields); byte[] missingBaseline = physicalFieldSet(partitionKey); assertThat(evaluate(invocation)).isEqualTo(-1L); assertThat(physicalFieldSet(partitionKey)).isEqualTo(missingBaseline); @@ -724,7 +725,7 @@ void postRetirementSqlRejectsUnaccountedCurrentReservationInAnotherPartition() t @Test void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceMismatch() { // A seeded baseline needs its own physical layout; sibling cases retain their issuer hashes. - try (var fixture = newFixture(BigInteger.valueOf(11), BigInteger.ONE, 1)) { + try (var fixture = newFixture(BigInteger.valueOf(17), BigInteger.ONE, 1)) { UUID originalId = fixture.originalOperationId(); List membershipBefore = currentOperationIds(fixture.dsl()); String originalBefore = localOperationImage(fixture.dsl(), originalId); From 7f0ae3848101270635da1013212f10c3703bb4d5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:10:47 +1300 Subject: [PATCH 4/9] fix(game-session): preserve frozen membership and keyed retirement reads --- design/project-management/ai-observations.md | 15 +- .../gameplay-rules-entities-and-effects.md | 4 +- ...ingLocalRetirementOperationRepository.java | 15 +- ...er_bootstrap_membership_frozen_columns.sql | 119 ++++++++++++++ ...lGameplayIssuerLifecycleProofFixtures.java | 8 +- ...suerPhysicalRetirementIntegrationTest.java | 154 ++++++++++++++++++ 6 files changed, 308 insertions(+), 7 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1040.6__issuer_bootstrap_membership_frozen_columns.sql diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index de40d54877..8c2318a0c0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -462,6 +462,19 @@ Entry format: - Expected pattern: retain the exact pre-upgrade schema, source rows and history in migration proof. Use explicitly historical fixture input when current Java requires a later schema; do not add production compatibility branches or backfill authority merely to seed a test. - `2026-10-29`: Retained Redis layouts must be unique across combined fixture cases - - Context: The #3341 membership guard passed alone in R978, but its combined R981 run reused layout 11 already initialized by a sibling with different baseline data. Bootstrap correctly refused before the guard assertions. + - Context: #3341 membership-guard integration fixture; isolated R978 and combined R981 runs. + - Observation: The guard passed alone, but the combined run reused layout 11 already initialized by a sibling with different baseline data. Bootstrap correctly refused before the guard assertions, so the isolated pass did not establish shared-container isolation. - Outcome: Give the seeded guard layout 17 while retaining the existing layout 11 and snapshot layout 13 cases. R983 passes all three together; the original R981 aggregate remains failed. Production SQL and Redis guards are unchanged by this fixture repair. - Expected pattern: Check the full class's retained key/layout identities when adding a physical fixture. An isolated pass does not establish shared-container isolation; run the actual former collision cases together after repair. + +- `2026-10-29`: Explicitly selected analysis tasks can still be disabled + - Context: Gameplay R987 passed the three World migration-frontier regression cases and applied formatting, but omitted `-PfullCheck` when selecting Checkstyle, SpotBugs and formatting checks. + - Observation: Gradle returned success while those selected checks were `SKIPPED`. The initial progress report incorrectly described them as passing; test execution and formatter application were real, but did not establish enabled analysis or formatting verification. + - Outcome: R990 separately passes the enabled World integration Checkstyle, SpotBugs and formatting checks. Its aggregate remains failed on a Game Session negative-test oracle; this does not change R987's skipped-task attribution. + - Expected pattern: Include `-PfullCheck` and inspect the selected task outcomes before claiming those checks passed. Preserve R987 as the passing regression run with its skipped checks and record the subsequent enabled checks separately. + +- `2026-10-29`: An unrelated bot report delayed capture of a completed Hosted review + - Context: #3341 Hosted1 finished at 18:57 NZDT, while its original FireController operation remained `active / trigger_recovered` without native evidence. + - Observation: FireController's owner reproduced a false CodeRabbit attribution conflict caused by a newly created and edited Greptile report. The original immutable capture already contained the completed review, all three findings and the exact original comparison; no replacement trigger was needed. + - Outcome: The owner deployed the bounded parser correction, and the same operation recovered its three findings at 19:55 NZDT without changing review allowances or attribution. Gameplay consumed and adjudicated that original evidence. + - Expected pattern: Preserve the original attempt, report the capture mismatch to the tool owner and continue safe local work. Distinguish actual provider completion from stale local operation state; do not spend another review to recover existing results. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 142c6b4b78..25d8dbc830 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -106,7 +106,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. The authenticated assignment handler and caller remain manually composed and unregistered; retained-identity promotion, controller/execution replacement and production admission remain unavailable. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof). See [Protected preseeded assignment ingress](#protected-preseeded-assignment-ingress); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Entity V1020 typed created-retirement recognition](../../../services/entity-management-service/src/main/resources/db/migration/V1020__canonical_roster_created_retirement_recognition.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql); [Entity V1014 retirement observation](../../../services/entity-management-service/src/main/resources/db/migration/V1014__canonical_roster_retirement_observation.sql); [Game Session V1017 retirement observation](../../../services/game-session-service/src/main/resources/db/migration/V1017__canonical_roster_retirement_observation.sql); [CanonicalGameplayRosterRetirementEvidence.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java); [CanonicalPreseededActorAssignmentGrpcService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java); [CanonicalPreseededActorAssignmentPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java); [PreseededActorAssignmentGrpcCodec.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java); [PreseededActorAssignmentConfiguration.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java); [CanonicalPreseededActorAssignmentClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClient.java); [V1018 staged retirement](../../../services/entity-management-service/src/main/resources/db/migration/V1018__canonical_roster_staged_retirement.sql); [V1019 snapshot retirement seals](../../../services/entity-management-service/src/main/resources/db/migration/V1019__canonical_roster_snapshot_retirement_seals.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java); [CanonicalPreseededActorAssignmentGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java); [CanonicalPreseededActorAssignmentPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java); [PreseededActorAssignmentGrpcCodecTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java); [PreseededActorAssignmentIngressFactoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentIngressFactoryTest.java); [CanonicalPreseededActorAssignmentClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java); [CanonicalPreseededActorAssignmentClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientMtlsTest.java); [PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java); [Canonical roster correction migration-ordering PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. The authenticated assignment handler and caller remain manually composed and unregistered; retained-identity promotion, controller/execution replacement and production admission remain unavailable. The bounded preseeded PLAYER runtime projection and purpose-specific reference read are present; generic actor runtime and replacement remain incomplete. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof). See [Protected preseeded assignment ingress](#protected-preseeded-assignment-ingress); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. R981 passes the bounded runtime-reference owner/security units and selected Entity PostgreSQL receiving suites; complete-suite and production limits remain. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Entity V1020 typed created-retirement recognition](../../../services/entity-management-service/src/main/resources/db/migration/V1020__canonical_roster_created_retirement_recognition.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql); [Entity V1014 retirement observation](../../../services/entity-management-service/src/main/resources/db/migration/V1014__canonical_roster_retirement_observation.sql); [Game Session V1017 retirement observation](../../../services/game-session-service/src/main/resources/db/migration/V1017__canonical_roster_retirement_observation.sql); [CanonicalGameplayRosterRetirementEvidence.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java); [CanonicalPreseededActorAssignmentGrpcService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java); [CanonicalPreseededActorAssignmentPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java); [PreseededActorAssignmentGrpcCodec.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java); [PreseededActorAssignmentConfiguration.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java); [CanonicalPreseededActorAssignmentClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClient.java); [V1018 staged retirement](../../../services/entity-management-service/src/main/resources/db/migration/V1018__canonical_roster_staged_retirement.sql); [V1019 snapshot retirement seals](../../../services/entity-management-service/src/main/resources/db/migration/V1019__canonical_roster_snapshot_retirement_seals.sql); [PreseededActorRuntimeProjectionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java); [V1022 runtime projection](../../../services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql); [CanonicalPreseededActorRuntimeReferenceClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java); [CanonicalPreseededActorAssignmentGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java); [CanonicalPreseededActorAssignmentPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java); [PreseededActorAssignmentGrpcCodecTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java); [PreseededActorAssignmentIngressFactoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentIngressFactoryTest.java); [CanonicalPreseededActorAssignmentClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java); [CanonicalPreseededActorAssignmentClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientMtlsTest.java); [PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java); [Canonical roster correction migration-ordering PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java); [CanonicalPreseededActorRuntimeReferenceClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java); [CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | @@ -185,7 +185,7 @@ The bounded v1 executor accepts only a self-targeted `APPLY_ACTION_STATE` declar ### Unified Actor and Combat Boundary -No general persisted actor runtime model is implemented. `WHO` remains player-presence oriented; gods/admins are role and presentation overlays on player presence. The locked implementation direction is one persisted opaque actor core shared by `PLAYER` and `NPC`, with Entity Management owning actor identity and durable actor state, World Management owning location and occupancy, Game Session owning ephemeral session attachment and player-facing presence projection, Game Logic resolving gameplay targets and effects against actor identity, and Account Service owning account identity and authorization inputs. Presence and disposition are separate; disconnect does not defeat an actor. The future core has no universal targetability or visibility fields: release-pinned observation and targeting policies evaluate optional authored facts. Its DML-authored disposition owns base action admission; conditions and equipment can add restrictions but cannot grant behavior that the disposition denies or become competing lifecycle owners. +The bounded preseeded `PLAYER` runtime projection is implemented with Entity-owned typed numeric `runtimeEntityId` scoped by `{tenantId, gameInstanceId}`; it retains the distinct durable character UUID and exact original assignment provenance. No general persisted actor runtime model or NPC runtime is implemented. `WHO` remains player-presence oriented; gods/admins are role and presentation overlays on player presence. The [Entity runtime identity owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#runtime-actor-identity) defines the shared typed runtime core, with Entity Management owning actor identity and durable actor state, World Management owning location and occupancy, Game Session owning ephemeral session attachment and player-facing presence projection, Game Logic resolving gameplay targets and effects against actor identity, and Account Service owning account identity and authorization inputs. Presence and disposition are separate; disconnect does not defeat an actor. The future core has no universal targetability or visibility fields: release-pinned observation and targeting policies evaluate optional authored facts. Its DML-authored disposition owns base action admission; conditions and equipment can add restrictions but cannot grant behavior that the disposition denies or become competing lifecycle owners. Damage, mitigation, resistances, combat timing, body-region resolution, defeat, corpses, loot, respawn, and revival are not implemented. Resource adjustment has no implicit death, victory, corpse, loot, respawn, or revival meaning. Future combat must consume the shared actor/state/effect model and keep combat authority out of Game Session. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java index 381a6f61d4..33d992b742 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java @@ -118,13 +118,22 @@ private CanonicalGameplayIssuerBindingLocalRetirementOperation readCompletedReti return dsl.transactionResult( configuration -> { DSLContext transaction = org.jooq.impl.DSL.using(configuration); + // The release has a unique transition key; its operation is the retirement's unique + // release key. Resolve those two point identities instead of filtering retained history. + Record release = + transaction.fetchOne( + "SELECT operation_id FROM " + + RELEASE + + " WHERE transition_id = ? AND issuer_id = ? AND status = 'RELEASED'", + transitionId, + ISSUER); + if (release == null) return null; Record retirement = transaction.fetchOne( "SELECT * FROM " + RETIREMENT - + " WHERE issuer_id = ? AND transition_id = ? AND status = 'RETIRED'", - ISSUER, - transitionId); + + " WHERE release_operation_id = ? AND status = 'RETIRED'", + uuid(release, "operation_id")); if (retirement == null) return null; return readCompletedRetirementInTransaction(transaction, retirement); }); diff --git a/services/game-session-service/src/main/resources/db/migration/V1040.6__issuer_bootstrap_membership_frozen_columns.sql b/services/game-session-service/src/main/resources/db/migration/V1040.6__issuer_bootstrap_membership_frozen_columns.sql new file mode 100644 index 0000000000..062ab0a0cd --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1040.6__issuer_bootstrap_membership_frozen_columns.sql @@ -0,0 +1,119 @@ +-- Keep retained bootstrap membership stable across unrelated additive reservation columns. +-- Replace only the point-membership guard; original cohort bytes and all owner guards stay intact. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION gs_require_issuer_reservation_current_membership(reservation_identity uuid) +RETURNS void +LANGUAGE plpgsql +AS $$ +DECLARE + reservation game_session_canonical_issuer_partition_reservation%ROWTYPE; + anchor game_session_canonical_issuer_installed_anchor%ROWTYPE; + original game_session_canonical_issuer_binding_local_operation%ROWTYPE; +BEGIN + SELECT * INTO STRICT reservation + FROM game_session_canonical_issuer_partition_reservation + WHERE reservation_id = reservation_identity; + SELECT * INTO anchor FROM game_session_canonical_issuer_installed_anchor + WHERE issuer_id = reservation.issuer_id; + IF NOT FOUND THEN + -- Genuine initial inventory preparation precedes the first positive installed anchor. + RETURN; + END IF; + SELECT * INTO original FROM game_session_canonical_issuer_binding_local_operation + WHERE reservation_id = reservation_identity; + IF FOUND THEN + IF original.anchor_bootstrap_operation_id <> anchor.bootstrap_operation_id + OR NOT gs_issuer_local_operation_has_exact_source(original.operation_id) THEN + RAISE EXCEPTION 'Issuer reservation differs from its exact installed local-operation source' + USING ERRCODE = '23514'; + END IF; + IF gs_issuer_local_operation_has_exact_retirement(original.operation_id) THEN + IF EXISTS (SELECT 1 FROM game_session_canonical_issuer_current_local_operation current + WHERE current.operation_id = original.operation_id) THEN + RAISE EXCEPTION 'Retired issuer operation cannot remain in current membership' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_current_local_operation current + WHERE current.operation_id = original.operation_id + AND current.issuer_id = original.issuer_id + AND current.anchor_bootstrap_operation_id = anchor.bootstrap_operation_id + AND current.partition_id = original.partition_id) THEN + RAISE EXCEPTION 'Unretired issuer reservation requires its exact current local operation' + USING ERRCODE = '23514'; + END IF; + RETURN; + END IF; + -- Bootstrap source keys are reservation UUID text, unique within the exact installed build. + -- Preserve the complete original identity, owner, fences, layout and creation timestamp. + -- Lifecycle and inventory revision are mutable under their existing owner guards; a qualified + -- release must not lose baseline membership merely because it advances those two columns. + -- Compare only the explicit frozen attributes: unrelated additive columns must not change + -- membership or require rewriting the immutable captured cohort. + IF EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_partition_build_cohort_row cohort + WHERE cohort.build_operation_id = anchor.build_operation_id + AND cohort.source_operation_id = anchor.bootstrap_operation_id + AND cohort.issuer_id = anchor.issuer_id + AND cohort.source_kind = 'RESERVATION' + AND cohort.source_key = reservation_identity::text + AND cohort.source_inventory_revision <= reservation.inventory_revision + AND cohort.source_row_json::jsonb -> 'reservation_id' + = to_jsonb(reservation.reservation_id) + AND cohort.source_row_json::jsonb -> 'binding_ref' + = to_jsonb(reservation.binding_ref) + AND cohort.source_row_json::jsonb -> 'account_id' + = to_jsonb(reservation.account_id) + AND cohort.source_row_json::jsonb -> 'tenant_id' + = to_jsonb(reservation.tenant_id) + AND cohort.source_row_json::jsonb -> 'game_instance_id' + = to_jsonb(reservation.game_instance_id) + AND cohort.source_row_json::jsonb -> 'runtime_game_instance_id' + = to_jsonb(reservation.runtime_game_instance_id) + AND cohort.source_row_json::jsonb -> 'session_id' + = to_jsonb(reservation.session_id) + AND cohort.source_row_json::jsonb -> 'binding_generation' + = to_jsonb(reservation.binding_generation) + AND cohort.source_row_json::jsonb -> 'transition_id' + = to_jsonb(reservation.transition_id) + AND cohort.source_row_json::jsonb -> 'issuer_id' + = to_jsonb(reservation.issuer_id) + AND cohort.source_row_json::jsonb -> 'issuer_auth_generation' + = to_jsonb(reservation.issuer_auth_generation) + AND cohort.source_row_json::jsonb -> 'playable_state_namespace_id' + = to_jsonb(reservation.playable_state_namespace_id) + AND cohort.source_row_json::jsonb -> 'character_id' + = to_jsonb(reservation.character_id) + AND cohort.source_row_json::jsonb -> 'playable_state_scope' + = to_jsonb(reservation.playable_state_scope) + AND cohort.source_row_json::jsonb -> 'region_id' + = to_jsonb(reservation.region_id) + AND cohort.source_row_json::jsonb -> 'region_epoch' + = to_jsonb(reservation.region_epoch) + AND cohort.source_row_json::jsonb -> 'partition_id' + = to_jsonb(reservation.partition_id) + AND cohort.source_row_json::jsonb -> 'issuer_index_layout_version' + = to_jsonb(reservation.issuer_index_layout_version) + AND cohort.source_row_json::jsonb -> 'issuer_index_partition_count' + = to_jsonb(reservation.issuer_index_partition_count) + AND cohort.source_row_json::jsonb -> 'issuer_index_partition_capacity' + = to_jsonb(reservation.issuer_index_partition_capacity) + AND cohort.source_row_json::jsonb -> 'reservation_fence' + = to_jsonb(reservation.reservation_fence) + AND cohort.source_row_json::jsonb -> 'issuer_coverage_operation_id' + = to_jsonb(reservation.issuer_coverage_operation_id) + AND cohort.source_row_json::jsonb -> 'issuer_coverage_operation_fence' + = to_jsonb(reservation.issuer_coverage_operation_fence) + AND cohort.source_row_json::jsonb -> 'coverage_fence' + = to_jsonb(reservation.coverage_fence) + AND cohort.source_row_json::jsonb -> 'inventory_snapshot_revision' + = to_jsonb(reservation.inventory_snapshot_revision) + AND cohort.source_row_json::jsonb -> 'created_at' + = to_jsonb(reservation.created_at)) THEN + RETURN; + END IF; + RAISE EXCEPTION 'Installed issuer reservation requires exact bootstrap or current local-operation membership' + USING ERRCODE = '23514'; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java index 34f0fb4581..5b5b62d2bd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java @@ -31,6 +31,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -130,6 +131,11 @@ protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( Candidate candidate, int seedBootstrapMemberCount) { + return newFixture(candidate, seedBootstrapMemberCount, null); + } + + protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( + Candidate candidate, int seedBootstrapMemberCount, MigrationVersion migrationTarget) { DriverManagerDataSource accountDataSource = new DriverManagerDataSource(); accountDataSource.setDriverClassName("org.postgresql.Driver"); String postgresJdbcUrl = postgres().getJdbcUrl(); @@ -138,7 +144,7 @@ protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( accountDataSource.setUsername(postgres().getUsername()); accountDataSource.setPassword(postgres().getPassword()); return new CanonicalGameplayAdmissionAbortCompositionFixture( - accountDataSource, candidate, issuerOwner, seedBootstrapMemberCount); + accountDataSource, candidate, issuerOwner, seedBootstrapMemberCount, migrationTarget); } protected static Candidate controlledCandidate() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index fb6ac4da76..12ce95c3bc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; @@ -578,6 +579,39 @@ void accountControlAdvancePreservesUnrelatedCapacityDuringOriginalRetirement() { byte[] beforeRetirementRetry = physicalFieldSet(partitionKey); assertThat(fixture.retireIssuerCapacity(retirementRetry).scriptOutcome()).isEqualTo(2L); assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeRetirementRetry); + + String historyBeforeCompletedRead = durableHistoryImage(fixture.dsl(), NIL_UUID); + String headBeforeCompletedRead = + partitionHeadImage(fixture.dsl(), fixture.originalPartitionId()); + fixture.moveIssuerSourceCheckpoint(); + fixture.moveIssuerIncarnation(); + var historicalRetry = fixture.prepareIssuerRetirement(fixture.transitionId()); + assertThat(historicalRetry.operationId()).isEqualTo(retirementRetry.operationId()); + assertThat(historicalRetry.exactAbsenceReadbackFieldSetBytes()) + .isEqualTo(retirementRetry.exactAbsenceReadbackFieldSetBytes()); + + var unavailableCurrentIssuerRepository = + new CanonicalGameplayIssuerBindingLocalRetirementOperationRepository( + fixture.dsl(), + () -> { + throw new AssertionError( + "Completed history must not read current issuer authority"); + }); + var unavailableAuthorityRetry = + unavailableCurrentIssuerRepository.prepareOrResume(fixture.transitionId()); + assertThat(unavailableAuthorityRetry.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED); + assertThat(unavailableAuthorityRetry.operationId()).isEqualTo(retirementRetry.operationId()); + assertThat(unavailableAuthorityRetry.exactAbsenceReadbackFieldSetBytes()) + .isEqualTo(retirementRetry.exactAbsenceReadbackFieldSetBytes()); + assertThatThrownBy(() -> fixture.prepareIssuerRetirement(UUID.randomUUID())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage("First-NEW admission abort source does not exist"); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)) + .isEqualTo(historyBeforeCompletedRead); + assertThat(partitionHeadImage(fixture.dsl(), fixture.originalPartitionId())) + .isEqualTo(headBeforeCompletedRead); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(beforeRetirementRetry); } } @@ -722,6 +756,126 @@ void postRetirementSqlRejectsUnaccountedCurrentReservationInAnotherPartition() t } } + @Test + void bootstrapMembershipPreservesFrozenOwnershipAcrossAnUnrelatedAdditiveColumn() { + // Capture through the real bootstrap owner at the published prior migration frontier. + try (var fixture = + newFixture( + controlledCandidate(BigInteger.valueOf(19), BigInteger.ONE), + 1, + MigrationVersion.fromVersion("1040.5"))) { + assertThat(fixture.originalBaselineReservationCount()).isOne(); + String baselineSourceSql = + " FROM game_session_canonical_issuer_installed_anchor anchor" + + " JOIN game_session_canonical_issuer_partition_build_cohort_row cohort" + + " ON cohort.build_operation_id = anchor.build_operation_id" + + " AND cohort.source_operation_id = anchor.bootstrap_operation_id" + + " AND cohort.issuer_id = anchor.issuer_id" + + " AND cohort.source_kind = 'RESERVATION'"; + UUID baselineReservationId = + fixture + .dsl() + .fetchSingle("SELECT cohort.source_key::uuid" + baselineSourceSql) + .get(0, UUID.class); + String retainedOwnerSql = + "SELECT jsonb_build_object('cohort', to_jsonb(cohort), 'anchor', to_jsonb(anchor))::text" + + baselineSourceSql; + String retainedOwnerBefore = fixture.dsl().fetchSingle(retainedOwnerSql).get(0, String.class); + String reservationBefore = reservationImage(fixture.dsl(), baselineReservationId); + byte[] partitionBefore = physicalFieldSet(fixture.issuerPartitionKey()); + List membershipBefore = currentOperationIds(fixture.dsl()); + String durableHistoryBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); + List migrationHistoryBefore = fixture.migrationHistoryImage(); + + assertThat( + fixture.upgradeWithDefaultGameSessionMigrations( + MigrationVersion.fromVersion("1040.6"))) + .isOne(); + List migrationHistoryAfter = fixture.migrationHistoryImage(); + assertThat(migrationHistoryAfter).hasSize(migrationHistoryBefore.size() + 1); + assertThat(migrationHistoryAfter.subList(0, migrationHistoryBefore.size())) + .containsExactlyElementsOf(migrationHistoryBefore); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(durableHistoryBefore); + assertThat(fixture.dsl().fetchSingle(retainedOwnerSql).get(0, String.class)) + .isEqualTo(retainedOwnerBefore); + assertThat(reservationImage(fixture.dsl(), baselineReservationId)) + .isEqualTo(reservationBefore); + assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBefore); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(partitionBefore); + + fixture + .dsl() + .execute( + "ALTER TABLE game_session_canonical_issuer_partition_reservation" + + " ADD COLUMN non_authority_annotation text"); + // The captured immutable JSON has no new key; the current row has an explicit SQL NULL. + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT jsonb_exists(cohort.source_row_json::jsonb, 'non_authority_annotation')" + + baselineSourceSql) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT non_authority_annotation FROM" + + " game_session_canonical_issuer_partition_reservation" + + " WHERE reservation_id = ?", + baselineReservationId) + .get(0, String.class)) + .isNull(); + fixture + .dsl() + .fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", baselineReservationId); + + assertThatThrownBy( + () -> + fixture + .dsl() + .transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET coverage_fence = coverage_fence + 1" + + " WHERE reservation_id = ?", + baselineReservationId)) + .isOne(); + transaction.fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", + baselineReservationId); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining( + "Installed issuer reservation requires exact bootstrap or current local-operation membership"); + fixture + .dsl() + .fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", baselineReservationId); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT (to_jsonb(reservation) - 'non_authority_annotation')::text FROM" + + " game_session_canonical_issuer_partition_reservation reservation" + + " WHERE reservation_id = ?", + baselineReservationId) + .get(0, String.class)) + .isEqualTo(reservationBefore); + assertThat(fixture.dsl().fetchSingle(retainedOwnerSql).get(0, String.class)) + .isEqualTo(retainedOwnerBefore); + assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBefore); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(partitionBefore); + } + } + @Test void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceMismatch() { // A seeded baseline needs its own physical layout; sibling cases retain their issuer hashes. From b12624d2ba5303b02cf15235aa99ba50631e5293 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:37:31 +1300 Subject: [PATCH 5/9] fix(game-session): keep response callbacks outside owner failure mapping --- .../api-contracts.md | 2 +- .../game-session-service/api-contracts.md | 2 +- .../game-session-service/runtime-and-data.md | 10 +++- design/project-management/ai-observations.md | 6 ++ .../player-access-and-session.md | 6 +- ...ialAdmissionSettlementReadGrpcService.java | 12 +++- ...dmissionSettlementReadGrpcServiceTest.java | 59 +++++++++++++++++++ 7 files changed, 89 insertions(+), 8 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index fffabe5458..97125dcb95 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -104,7 +104,7 @@ This read authenticates historical assignment provenance only. It does not reval `CanonicalPreseededActorAssignmentService.ReadPreseededActorRuntimeReference` is a distinct read for the exact same-namespace Game Session workload. It loads the actual Entity-owned projection for the original assignment, full expected target and character; it never allocates or backfills a missing projection. The [Entity runtime projection owner](./runtime-and-data.md#initial-runtime-actor-projection-and-reference) defines allocation, uniqueness, retained generations and nonreuse. The response carries that typed scoped numeric runtime identity, projection generation/fence and complete original assignment provenance in a closed bounded envelope. The existing assignment and World-only receipt messages retain their character-UUID semantics and immutable bytes. -The service authenticates this method's Game Session peer before selector decoding, rejects unknown or malformed fields and mismatched scope/provenance, and bounds both request and response at its manual transport boundary. It returns no reference for missing, stale or contradictory projection state and exposes no general entity lookup. The method's narrow manual composition does not register a production handler, authorize an unsupported replacement or confer placement, region ownership, player admission or activation. Game Session independently joins its [World initial-location read](../world-management-service/api-contracts.md#canonical-initial-player-location) and current region lease before using the reference in a binding bridge. +The service authenticates this method's Game Session peer before selector decoding, rejects unknown or malformed fields and mismatched scope/provenance, and bounds both request and response at its manual transport boundary. It returns no reference for missing, stale or contradictory projection state and exposes no general entity lookup. Peer failure returns `PERMISSION_DENIED`; malformed selectors return `INVALID_ARGUMENT`; an absent or stale projection returns `NOT_FOUND`, including quarantine or selector drift; contradictory provenance returns `FAILED_PRECONDITION`; transient data-access or transaction failures return `UNAVAILABLE`; other failures return `INTERNAL`. This read preserves `NOT_FOUND` for absent or stale projections, while the assignment write maps a dependency `NOT_FOUND` to `FAILED_PRECONDITION`. The method's narrow manual composition does not register a production handler, authorize an unsupported replacement or confer placement, region ownership, player admission or activation. Game Session independently joins its [World initial-location read](../world-management-service/api-contracts.md#canonical-initial-player-location) and current region lease before using the reference in a binding bridge. ## Player-created roster and selected character diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index e17e37d6b5..a612a53dbf 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -84,7 +84,7 @@ The prepared protected Human path is still not callable through a default runtim #### Account-purpose initial-admission settlement read -`AccountInitialAdmissionSettlementReadService.GetAccountInitialAdmissionSettlement` is a separate internal method restricted to the exact same-namespace Account mTLS workload without end-user context. Its request carries the complete original Account protection evidence and a read correlation ID; the 12 MiB request and response bounds apply only to this method. Request and response each carry exactly one supported schema version; missing, duplicate or unsupported versions refuse. Game Session joins that evidence to its retained original attempt and protection binding, then reads the exact pointer/audit/terminal owner result. The response contains the unchanged protection and authenticated owner proof for either an exact `COMMITTED` result or a definitive `ABORTED` result; it is not a caller-supplied outcome or a currentness renewal. Missing or mismatched protection, `PENDING`, unavailable owner data, or incomplete terminal evidence returns no positive settlement proof. This read is manually composed and unregistered; Account's local settlement consequence is described in [Account Runtime and Data](../account-service/runtime-and-data.md#original-startsession-source-protection-storage). +`AccountInitialAdmissionSettlementReadService.GetAccountInitialAdmissionSettlement` is a separate internal method restricted to the exact same-namespace Account mTLS workload without end-user context. Its request carries the complete original Account protection evidence and a read correlation ID; the 12 MiB request and response bounds apply only to this method. A receiver must explicitly configure its transport inbound-message limit to accommodate that request bound; binding this service does not configure the transport limit. This is a required receiver configuration, not evidence that the current shared server or deployment accepts such requests. Request and response each carry exactly one supported schema version; missing, duplicate or unsupported versions refuse. Game Session joins that evidence to its retained original attempt and protection binding, then reads the exact pointer/audit/terminal owner result. The response contains the unchanged protection and authenticated owner proof for either an exact `COMMITTED` result or a definitive `ABORTED` result; it is not a caller-supplied outcome or a currentness renewal. Missing or mismatched protection, `PENDING`, unavailable owner data, or incomplete terminal evidence returns no positive settlement proof. This read is manually composed and unregistered; Account's local settlement consequence is described in [Account Runtime and Data](../account-service/runtime-and-data.md#original-startsession-source-protection-storage). ### Public character-creation source read 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 f89d173cf0..5e25619d49 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,15 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- **Local NEW issuer preparation:** the unregistered Game Session sources now manually compose the initial issuer anchor, ordinary post-baseline one-key member/capacity projection and issuer-local release, each with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Ordinary ADD revalidates the target’s current Account authority, while terminal cleanup and non-target accounting preserve captured Account provenance. Completed-original bootstrap retries return retained installation evidence; current physical verification remains separate. The bounded foundation does not execute physical retirement; retained storage and fail-closed accounting remain prerequisites for the separate settlement owner. The settlement stage now supplies that separate executable owner and exact retirement readback while retaining the same original-source and currentness requirements. Its bounded current-membership correction maintains `game_session_canonical_issuer_current_local_operation` as references to immutable local operations: registration adds a reference, pending cleanup retains it, and only an exactly proven completed retirement removes it. Ordinary projection reads use that current set while original operations, reservations and completion receipts remain retained provenance; this adds no inventory or admission authority. The current-versus-retained boundary remains owned by the [Redis issuer-index contract](../../system-architecture-redis.md#issuer-active-binding-index). The focused component proofs do not establish operational source or incarnation custody. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS, and admission remain absent. Operational source/incarnation custody, legacy recovery, production PKI, runtime registration, and activation remain open; see the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the physical contract. +- **Local NEW issuer anchor:** the unregistered bootstrap owner installs the initial issuer anchor with exact physical readback and controlled Account checkpoint and stable-incarnation collaborators. Completed-original retries return retained installation evidence; current physical verification remains separate. The [issuer anchor owner](../../system-architecture-redis.md#installed-issuer-anchor-for-ordinary-new) defines the contract. + +- **Local NEW issuer projection and release:** the ordinary post-baseline owner projects one-key member/capacity state and performs issuer-local release with exact physical readback. Ordinary ADD revalidates the target’s current Account authority; terminal cleanup and non-target accounting preserve captured Account provenance. + +- **Local NEW issuer physical retirement:** `CanonicalGameplayIssuerBindingLocalRetirementOperationRepository` and `CanonicalGameplayIssuerBindingLocalRetirementRedisOwner` execute retirement of the exact released capacity under the original release receipt and partition revision, with independent physical readback. Original-source and currentness requirements remain enforced. The [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records the implementation and focused proof. + +- **Local NEW current issuer membership:** `game_session_canonical_issuer_current_local_operation` references immutable local operations. Registration adds a reference, pending cleanup retains it, and exactly proven completed retirement removes it. Ordinary reads use this current set while original operations, reservations and completion receipts remain retained provenance; this adds no inventory or admission authority. The [Redis issuer-index contract](../../system-architecture-redis.md#issuer-active-binding-index) owns this boundary. + +- **Issuer qualification limits:** these owners remain manually composed and unregistered. Their focused proofs do not establish operational source or incarnation custody, legacy recovery, production PKI, registration or activation. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS and admission remain outside this component boundary; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns detailed proof attribution and gaps. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8c2318a0c0..ae1d1d6a02 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -478,3 +478,9 @@ Entry format: - Observation: FireController's owner reproduced a false CodeRabbit attribution conflict caused by a newly created and edited Greptile report. The original immutable capture already contained the completed review, all three findings and the exact original comparison; no replacement trigger was needed. - Outcome: The owner deployed the bounded parser correction, and the same operation recovered its three findings at 19:55 NZDT without changing review allowances or attribution. Gameplay consumed and adjudicated that original evidence. - Expected pattern: Preserve the original attempt, report the capture mismatch to the tool owner and continue safe local work. Distinguish actual provider completion from stale local operation state; do not spend another review to recover existing results. + +- `2026-10-29`: Local resource admission does not establish queue order + - Context: The focused #3341 R992 retry waited behind the Account timing experiment while later R993 successor validation also requested the canonical resource slot. + - Observation: R993 acquired the freed slot first, and R992 exhausted its admission budget before Gradle or tests ran. Submitting the front retry earlier did not reserve execution priority; the initial queueing assumption delayed its proof. + - Outcome: R996 subsequently passes the exact front case under the ordinary guard. R992 remains an unexecuted admission failure, not a failed native test or successful retry. + - Expected pattern: Observe admission of the priority proof before launching another heavier waiter. Serialize subsequent qualification at the orchestrator when order matters rather than assuming fairness from resource exclusion. 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 c7c0af64b1..7d448fe867 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,9 +12,11 @@ The initial Entity runtime-actor producer and passive Game Session reference cli The current-membership correction prepares forward V1040.5 and SQL-maintained references to original unretired local operations. Projection, capacity, slot registration, ADD-mutation reads and retirement conflict checks use current ownership rather than enumerating lifetime immutable history; pending-retirement validation starts from the bounded partition heads. Existing immutable provenance and exact owner checks remain required. The native retirement proof now checks current membership through pending/lost-reply/completion rollback/exact retry and more than 256 lifetime cycles. Its migration fixture adapts only the historical pre-membership slot-count read, retaining actual old-schema guards and post-upgrade backfill/current reads; it does not qualify a new gate before its schema exists. R974 freshly passed 14 of its 15 selected native cases, including the 257-cycle turnover case, but failed aggregate validation on shared-layout fixture setup. R975 and R977 passed the historical-frontier upgrade/backfill case; their new negative-guard proof exposed assertion and SQL-qualification defects, corrected before R978 passed that guard case. V1040.5 passes the migration-frontier check after renumbering the unapplied correction above its parent. These passing executions cover 16 distinct membership-related native cases across the retained runs; the earlier failed aggregates remain failures. The combined receiving R981 then passes 159 of 160 selected methods, including both actual World–Game Session–Account settlement compositions, but fails one membership fixture bootstrap because two cases reuse layout 11 with different baseline data. It also fails the full-SHA migration-frontier argument guard and a primitive-array varargs static warning in the new snapshot test. The fixture now uses its own layout 17, the test passes a named two-dimensional byte array, and R983 passes all three former-collision/snapshot cases together with integration Checkstyle, SpotBugs and formatting. All 160 distinct selected methods therefore have passing execution across R981/R983; R981 remains a failed aggregate. The complete immutable-parent frontier and final documentation checks are separate publication checks. This does not establish registration, live issuer custody, activation or production admission. +Forward V1040.6 compares the 26 frozen bootstrap ownership attributes explicitly, preserving cohort membership across unrelated additive columns. Completed retirement resolves the unique original transition/release/retirement keys without reading later mutable issuer authority. R985 and R990 pass the populated V1040.5-to-V1040.6 upgrade, additive-column membership and historical-backfill cases. R996 passes the completed-history retry after issuer checkpoint/incarnation movement and with unavailable current issuer authority, including wrong-transition refusal and unchanged SQL/Redis postimages. These four distinct selected cases have passing execution across R990/R996; R990 remains a failed aggregate because its negative oracle expected the wrong exception. R992 expired at local resource admission before Gradle or tests ran and has no execution credit. Enabled affected main/integration analysis and formatting pass in R990; R994 and R998 separately qualify the settlement-handler callback correction and canonical documentation. This remains focused component proof with controlled custody and no registration or activation. + The next protected-settlement correction versions both sides of the closed response and aligns the SQL `EXPECT_CLOSED` negative terminal with the existing immutable-origin contract through forward V1040.3. R970 passes 31 focused codec/client/verifier/service unit cases and one actual World–Game Session–Account acquisition composition, with enabled affected analysis, formatting and migration-frontier checks. Its aggregate fails the new later-request extension because that fixture reuses the same original owner attempt, which V1006 correctly permits only once. After removing that invalid extension, R971 passes the focused native protected-abort case and integration analysis/formatting. The native case proves actual competing-intent refusal while the first request is pending, original terminal/read/replay and unchanged pointer/audit. Its positive current-origin refusal remains controlled: neither result proves independent pointer advancement before abort or later-OPEN recovery. The separate current-inventory/retained-history turnover correction remains unfinished. -The bounded issuer foundation in #3310 owns bootstrap, ordinary local projection and proof-backed release after a known first-NEW Account abort. The executable original-operation physical-retirement owner and its turnover proof belong with #2973 settlement. The foundation retains the V1038/V1038.4 storage and history guards required by ordinary projection; it retains terminal capacity and refuses fresh allocation at the existing 256-unretired-operation bound until the successor supplies physical retirement. This separates executable capability without weakening the canonical retirement contract or claiming unknown-decision orphan-cleanup delivery. Earlier combined proof below retains its original source attribution. +The bounded issuer foundation in #3310 owns bootstrap, ordinary local projection and proof-backed release after a known first-NEW Account abort. The executable original-operation physical-retirement owner and its turnover proof belong with #3341 settlement. The foundation retains the V1038/V1038.4 storage and history guards required by ordinary projection; on its own it retains terminal capacity and refuses fresh allocation at the existing 256-unretired-operation bound. The separate #3341 settlement owner supplies executable physical retirement and its focused turnover proof, with production custody and registration still unqualified. This separates executable capability without weakening the canonical retirement contract or claiming unknown-decision orphan-cleanup delivery. Earlier combined proof below retains its original source attribution. Ordinary NEW exact retry now reconstructs the original durable local issuer operation after legitimate provisional and Account-member progression. It retains the frozen reservation, member bytes, operation identity, fences, generation and local snapshot while requiring current eligible source revisions to remain at least the frozen revision and mutually coherent. Initial creation still requires exact current revision; current anchor, lineage, Account control, source/incarnation and lifecycle checks remain mandatory. R918 freshly passes all 17 selected cases (nine units and eight PostgreSQL/Redis cases), including reconstructed operation and projection owners after actual provisional publication, candidate-member presence and physical Account-member repair/acknowledgement. Independent Spring transaction-only and synchronization-only refusals are proved. The current `develop` dependency updates are reconciled locally; migration frontier, jOOQ generation, affected enabled static analysis, formatting and documentation checks pass. These are focused manually composed component results with controlled Account/source collaborators, not operational custody, default registration or public-admission qualification. @@ -48,7 +50,7 @@ The manually composed first-NEW abort path now joins actual Account current-call R625 freshly passes the combined owner gate: 11 unit cases, 35 issuer PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips. Enabled affected Checkstyle, SpotBugs and formatting pass; R626 documentation checks pass. The new release case drives the actual Account abort and retained Game Session source through SQL release preparation, exact one-key Redis mutation and independent complete readback, then a fresh SQL completion. Another registered transition advances the real inventory clock between preparation and completion. Proof preserves the original operation, reservation and anchor bytes, rejects bare terminal flags and conflicting or newer physical members, replays a lost response without new identities, excludes only completed release capacity for subsequent ordinary NEW, and retains exact Account member history through issuer release and a physical post-abort runtime retirement. The [canonical issuer release owner](../../architecture/system-architecture-redis.md#binding-local-issuer-release-provenance) defines the separate preparation and completion revisions. This settles only the binding-local issuer obligation; it does not remove the Account member, settle region cleanup, acknowledge admitting issuer/region membership or make the candidate playable. Earlier failed R617–R624 attempts remain retained evidence. Descriptor, launch/World, current-source/incarnation and test-PKI collaborators remain controlled; operational authority and production activation are not established. -The preserved combined issuer checkpoint implements the [original-operation physical retirement contract](../../architecture/system-architecture-redis.md#original-operation-issuer-physical-retirement) under the existing release/local-mutation owner; its executable retirement component is now assigned to #2973. On the original combined source, R675 passes 77 cases: 21 units, 49 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips; enabled affected static analysis, formatting and 547-file documentation checks pass. Physical proof includes 257 actual Game Session releases and retirements with complete immutable SQL history, original lost-reply/restart recovery and completed retry, stale ADD and release rejection, pending same-partition exclusion, missing-revision and foreign/currentness refusal, preservation of newer fields, a 256-readable/257-refused current local-entry bound, and actual 514-field release/readback/persistence/reload. The wide case uses 250 owner-produced provisional bootstrap rows and a small post-baseline cohort; the turnover case retires each terminal field rather than accumulating 256 terminal fields. The physical mutation revision is a separate positively installed UUID domain, and historical unfenced bootstrap audit rows remain retained without qualifying current fenced coverage. The seven Account composition cases separately retain their real current-caller, lease, abort and issuer-release attribution. The new turnover cases use controlled upstream Account lease/abort, issuer checkpoint, launch/World and stable-incarnation inputs; they do not prove those producers or production authority. R672 remains a failed aggregate, including its oversized test-only history image, current-readback omission and retirement Lua shape failure; R677 separately passes the corrected 46-case preflight before R675. Operational custody, registration, admitting acknowledgements, barrier OPEN, final CAS and playable admission remain unproved. +The preserved combined issuer checkpoint implements the [original-operation physical retirement contract](../../architecture/system-architecture-redis.md#original-operation-issuer-physical-retirement) under the existing release/local-mutation owner; its executable retirement component belongs to #3341. On the original combined source, R675 passes 77 cases: 21 units, 49 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases, with zero failures, errors or skips; enabled affected static analysis, formatting and 547-file documentation checks pass. Physical proof includes 257 actual Game Session releases and retirements with complete immutable SQL history, original lost-reply/restart recovery and completed retry, stale ADD and release rejection, pending same-partition exclusion, missing-revision and foreign/currentness refusal, preservation of newer fields, a 256-readable/257-refused current local-entry bound, and actual 514-field release/readback/persistence/reload. The wide case uses 250 owner-produced provisional bootstrap rows and a small post-baseline cohort; the turnover case retires each terminal field rather than accumulating 256 terminal fields. The physical mutation revision is a separate positively installed UUID domain, and historical unfenced bootstrap audit rows remain retained without qualifying current fenced coverage. The seven Account composition cases separately retain their real current-caller, lease, abort and issuer-release attribution. The new turnover cases use controlled upstream Account lease/abort, issuer checkpoint, launch/World and stable-incarnation inputs; they do not prove those producers or production authority. R672 remains a failed aggregate, including its oversized test-only history image, current-readback omission and retirement Lua shape failure; R677 separately passes the corrected 46-case preflight before R675. Operational custody, registration, admitting acknowledgements, barrier OPEN, final CAS and playable admission remain unproved. The preceding qualified correction separates immutable Account provenance from current ADD authority through the original abort, release and retirement readers, and makes the full completed-original bootstrap retry return its retained installation result without replaying baseline writes. Current target ADD guards, complete inventory accounting and mandatory physical-field checks remain required. Across R687, R688 and R689, that checkpoint qualifies 88 selected case methods: 26 units, 55 Game Session PostgreSQL/Redis cases and seven actual Account–Game Session cases. R687 remains a failed 88-case aggregate with 11 failures; R688 recovers those affected suites with 24 cases and one different Redis-startup failure, and R689 separately passes that unchanged negative case. The only source difference between R687 and R688 is test-layout isolation for two new cases; production postimages are identical. The physical suite again proves 257 actual releases and retirements, the 256/257 current-entry boundary and 514-field readback. New proof covers Account A advancing through the real acquisition-intent owner while unrelated Account B progresses, stale target ADD refusal, original cleanup and retirement, newer-field preservation, and unchanged SQL/proofs/Redis state through full bootstrap retries after NEW, release and retirement. That control case starts from captured `NO_ACTIVE_ACCOUNT_WIDE_FLOW`; it does not produce a new `HISTORICAL` control tuple. Enabled affected static analysis and formatting pass. Controlled upstream/source/incarnation inputs and all operational-custody, registration, admitting-acknowledgement, OPEN, final-CAS and activation limits remain unchanged. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcService.java index 08fbd77cad..d6e78e021c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcService.java @@ -68,18 +68,18 @@ public void getAccountInitialAdmissionSettlement( .asRuntimeException()); return; } + GetAccountInitialAdmissionSettlementResponse response; try { var evidence = owner.read(input); - var response = AccountInitialAdmissionSettlementReadGrpcCodec.toResponse(evidence); + response = AccountInitialAdmissionSettlementReadGrpcCodec.toResponse(evidence); AccountInitialAdmissionSettlementReadGrpcCodec.fromResponse(input, response); - observer.onNext(response); - observer.onCompleted(); } catch (TooManyRowsException unproved) { observer.onError( Status.FAILED_PRECONDITION .withDescription("Exact protected terminal is unavailable") .withCause(unproved) .asRuntimeException()); + return; } catch (CannotCreateTransactionException | DataAccessResourceFailureException | TransientDataAccessException unavailable) { @@ -88,6 +88,7 @@ public void getAccountInitialAdmissionSettlement( .withDescription("Settlement owner is unavailable") .withCause(unavailable) .asRuntimeException()); + return; } catch (org.jooq.exception.DataAccessException | org.springframework.dao.DataAccessException storageFailure) { if (hasTransientSqlState(storageFailure)) { @@ -103,19 +104,24 @@ public void getAccountInitialAdmissionSettlement( .withCause(storageFailure) .asRuntimeException()); } + return; } catch (IllegalArgumentException | IllegalStateException unproved) { observer.onError( Status.FAILED_PRECONDITION .withDescription("Exact protected terminal is unavailable") .withCause(unproved) .asRuntimeException()); + return; } catch (RuntimeException unexpected) { observer.onError( Status.INTERNAL .withDescription("Settlement owner read failed") .withCause(unexpected) .asRuntimeException()); + return; } + observer.onNext(response); + observer.onCompleted(); } private static boolean hasTransientSqlState(Throwable failure) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcServiceTest.java index 0b3ca57caa..ccb6486f33 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcServiceTest.java @@ -258,6 +258,65 @@ void malformedAndForeignSelectorsRefuseBeforeOwnerAndKnownUnprovedFactsStayClose assertThat(unexpected.getCause()).isInstanceOf(UnsupportedOperationException.class); } + @Test + void responseOnNextFailurePropagatesWithoutASecondCallback() { + assertResponseCallbackFailure(true); + } + + @Test + void responseOnCompletedFailurePropagatesWithoutASecondTerminalCallback() { + assertResponseCallbackFailure(false); + } + + private void assertResponseCallbackFailure(boolean failOnNext) { + var input = new AccountInitialAdmissionSettlementReadInput(UUID.randomUUID(), protection()); + var terminal = + new GameSessionCanonicalInitialAdmissionOwnerProof( + input.protection().request().worldAdmissionHoldIdentity(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + null, + null, + "sha256:" + "c".repeat(64), + true, + TERMINAL); + when(owner.read(any())) + .thenReturn( + new AccountInitialAdmissionSettlementReadEvidence( + input.readRequestId(), input.protection(), terminal)); + List callbacks = new java.util.ArrayList<>(); + var failure = new IllegalStateException("observer callback failed"); + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(GetAccountInitialAdmissionSettlementResponse value) { + callbacks.add("next"); + if (failOnNext) throw failure; + } + + @Override + public void onError(Throwable error) { + callbacks.add("error"); + } + + @Override + public void onCompleted() { + callbacks.add("completed"); + throw failure; + } + }; + var context = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer(NAMESPACE, "account-service")); + var request = AccountInitialAdmissionSettlementReadGrpcCodec.toRequest(input, NAMESPACE); + assertThatThrownBy( + () -> + context.run( + () -> service().getAccountInitialAdmissionSettlement(request, observer))) + .isSameAs(failure); + assertThat(callbacks) + .containsExactlyElementsOf(failOnNext ? List.of("next") : List.of("next", "completed")); + } + private AccountInitialAdmissionSettlementReadGrpcService service() { return new AccountInitialAdmissionSettlementReadGrpcService(owner, NAMESPACE); } From c58d581b71afab18c24f301439be5a58cef1315f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:56:55 +1300 Subject: [PATCH 6/9] docs: retain failed aggregate attribution beside passing Entity proof --- .../gameplay-rules-entities-and-effects.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 25d8dbc830..fcff9b19d1 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -106,7 +106,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. The authenticated assignment handler and caller remain manually composed and unregistered; retained-identity promotion, controller/execution replacement and production admission remain unavailable. The bounded preseeded PLAYER runtime projection and purpose-specific reference read are present; generic actor runtime and replacement remain incomplete. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof). See [Protected preseeded assignment ingress](#protected-preseeded-assignment-ingress); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. R981 passes the bounded runtime-reference owner/security units and selected Entity PostgreSQL receiving suites; complete-suite and production limits remain. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Entity V1020 typed created-retirement recognition](../../../services/entity-management-service/src/main/resources/db/migration/V1020__canonical_roster_created_retirement_recognition.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql); [Entity V1014 retirement observation](../../../services/entity-management-service/src/main/resources/db/migration/V1014__canonical_roster_retirement_observation.sql); [Game Session V1017 retirement observation](../../../services/game-session-service/src/main/resources/db/migration/V1017__canonical_roster_retirement_observation.sql); [CanonicalGameplayRosterRetirementEvidence.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java); [CanonicalPreseededActorAssignmentGrpcService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java); [CanonicalPreseededActorAssignmentPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java); [PreseededActorAssignmentGrpcCodec.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java); [PreseededActorAssignmentConfiguration.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java); [CanonicalPreseededActorAssignmentClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClient.java); [V1018 staged retirement](../../../services/entity-management-service/src/main/resources/db/migration/V1018__canonical_roster_staged_retirement.sql); [V1019 snapshot retirement seals](../../../services/entity-management-service/src/main/resources/db/migration/V1019__canonical_roster_snapshot_retirement_seals.sql); [PreseededActorRuntimeProjectionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java); [V1022 runtime projection](../../../services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql); [CanonicalPreseededActorRuntimeReferenceClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java); [CanonicalPreseededActorAssignmentGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java); [CanonicalPreseededActorAssignmentPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java); [PreseededActorAssignmentGrpcCodecTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java); [PreseededActorAssignmentIngressFactoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentIngressFactoryTest.java); [CanonicalPreseededActorAssignmentClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java); [CanonicalPreseededActorAssignmentClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientMtlsTest.java); [PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java); [Canonical roster correction migration-ordering PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java); [CanonicalPreseededActorRuntimeReferenceClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java); [CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. The authenticated assignment handler and caller remain manually composed and unregistered; retained-identity promotion, controller/execution replacement and production admission remain unavailable. The bounded preseeded PLAYER runtime projection and purpose-specific reference read are present; generic actor runtime and replacement remain incomplete. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof). See [Protected preseeded assignment ingress](#protected-preseeded-assignment-ingress); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. The bounded runtime-reference owner/security units and selected Entity PostgreSQL receiving suites pass within R981, whose aggregate remains failed on the separate Game Session membership fixture and frontier/static checks; complete-suite and production limits remain. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Entity V1020 typed created-retirement recognition](../../../services/entity-management-service/src/main/resources/db/migration/V1020__canonical_roster_created_retirement_recognition.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql); [Entity V1014 retirement observation](../../../services/entity-management-service/src/main/resources/db/migration/V1014__canonical_roster_retirement_observation.sql); [Game Session V1017 retirement observation](../../../services/game-session-service/src/main/resources/db/migration/V1017__canonical_roster_retirement_observation.sql); [CanonicalGameplayRosterRetirementEvidence.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java); [CanonicalPreseededActorAssignmentGrpcService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcService.java); [CanonicalPreseededActorAssignmentPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptor.java); [PreseededActorAssignmentGrpcCodec.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodec.java); [PreseededActorAssignmentConfiguration.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java); [CanonicalPreseededActorAssignmentClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClient.java); [V1018 staged retirement](../../../services/entity-management-service/src/main/resources/db/migration/V1018__canonical_roster_staged_retirement.sql); [V1019 snapshot retirement seals](../../../services/entity-management-service/src/main/resources/db/migration/V1019__canonical_roster_snapshot_retirement_seals.sql); [PreseededActorRuntimeProjectionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java); [V1022 runtime projection](../../../services/entity-management-service/src/main/resources/db/migration/V1022__preseeded_runtime_actor_projection.sql); [CanonicalPreseededActorRuntimeReferenceClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClient.java) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java); [CanonicalPreseededActorAssignmentGrpcServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java); [CanonicalPreseededActorAssignmentPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java); [PreseededActorAssignmentGrpcCodecTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java); [PreseededActorAssignmentIngressFactoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentIngressFactoryTest.java); [CanonicalPreseededActorAssignmentClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java); [CanonicalPreseededActorAssignmentClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientMtlsTest.java); [PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java); [Canonical roster correction migration-ordering PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java); [CanonicalPreseededActorRuntimeReferenceClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientTest.java); [CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorRuntimeReferenceClientMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | 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 7d448fe867..7fdc4bb5a5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components -The initial Entity runtime-actor producer and passive Game Session reference client are separated from the later World/region bootstrap consumer. Fresh authenticated preseeded assignment allocates the retained numeric runtime projection in its existing Entity transaction; the distinct exact Game Session read never allocates or backfills historical assignments. The producer retains its original receipt semantics, V1022 SQL postimage, migration fixtures, and focused owner/security proof. R981 freshly passes all 27 selected Entity owner/security units and all 96 selected Entity PostgreSQL cases across the six affected assignment, runtime projection and historical-fixture suites. This qualifies the controlled receiving producer and its retained migrations; broader composition and production limits remain below. Production registration, runtime replacement, lifecycle cleanup registration, region ownership, protected admission and activation remain unqualified; the [Entity runtime owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) defines the bounded contract. +The initial Entity runtime-actor producer and passive Game Session reference client are separated from the later World/region bootstrap consumer. Fresh authenticated preseeded assignment allocates the retained numeric runtime projection in its existing Entity transaction; the distinct exact Game Session read never allocates or backfills historical assignments. The producer retains its original receipt semantics, V1022 SQL postimage, migration fixtures, and focused owner/security proof. R981 freshly passes all 27 selected Entity owner/security units and all 96 selected Entity PostgreSQL cases across the six affected assignment, runtime projection and historical-fixture suites. These Entity cases passed within R981; its aggregate remains failed on a separate Game Session membership fixture, the migration-frontier argument and static checks. This qualifies the controlled receiving producer and its retained migrations; broader composition and production limits remain below. Production registration, runtime replacement, lifecycle cleanup registration, region ownership, protected admission and activation remain unqualified; the [Entity runtime owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) defines the bounded contract. The current-membership correction prepares forward V1040.5 and SQL-maintained references to original unretired local operations. Projection, capacity, slot registration, ADD-mutation reads and retirement conflict checks use current ownership rather than enumerating lifetime immutable history; pending-retirement validation starts from the bounded partition heads. Existing immutable provenance and exact owner checks remain required. The native retirement proof now checks current membership through pending/lost-reply/completion rollback/exact retry and more than 256 lifetime cycles. Its migration fixture adapts only the historical pre-membership slot-count read, retaining actual old-schema guards and post-upgrade backfill/current reads; it does not qualify a new gate before its schema exists. R974 freshly passed 14 of its 15 selected native cases, including the 257-cycle turnover case, but failed aggregate validation on shared-layout fixture setup. R975 and R977 passed the historical-frontier upgrade/backfill case; their new negative-guard proof exposed assertion and SQL-qualification defects, corrected before R978 passed that guard case. V1040.5 passes the migration-frontier check after renumbering the unapplied correction above its parent. These passing executions cover 16 distinct membership-related native cases across the retained runs; the earlier failed aggregates remain failures. The combined receiving R981 then passes 159 of 160 selected methods, including both actual World–Game Session–Account settlement compositions, but fails one membership fixture bootstrap because two cases reuse layout 11 with different baseline data. It also fails the full-SHA migration-frontier argument guard and a primitive-array varargs static warning in the new snapshot test. The fixture now uses its own layout 17, the test passes a named two-dimensional byte array, and R983 passes all three former-collision/snapshot cases together with integration Checkstyle, SpotBugs and formatting. All 160 distinct selected methods therefore have passing execution across R981/R983; R981 remains a failed aggregate. The complete immutable-parent frontier and final documentation checks are separate publication checks. This does not establish registration, live issuer custody, activation or production admission. From 626db8b7d21e7b6904db9147f76ce43cab328533 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:07:54 +1300 Subject: [PATCH 7/9] fix(gameplay): compare frozen issuer sources by native values --- .../runtime-and-data.md | 4 +- ...system-architecture-identifier-glossary.md | 2 +- design/project-management/ai-observations.md | 6 + .../gameplay-rules-entities-and-effects.md | 2 + .../player-access-and-session.md | 2 + ...ameplayIssuerPartitionBuildRepository.java | 118 ++++++++++- ...rent_issuer_local_operation_membership.sql | 9 +- ...er_bootstrap_membership_frozen_columns.sql | 8 +- ...eplayAdmissionAbortCompositionFixture.java | 67 +++++- ...lGameplayIssuerLifecycleProofFixtures.java | 17 +- ...rtitionBuildRepositoryIntegrationTest.java | 142 +++++++++++++ ...suerPhysicalRetirementIntegrationTest.java | 192 ++++++++++++++++++ .../CanonicalGameplayIssuerTestFixtures.java | 38 ++++ 13 files changed, 587 insertions(+), 20 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index cd7dcaf053..67857a10e7 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -364,6 +364,8 @@ Copies into an isolated playtest namespace allocate a new fork-local `characterI Entity Management owns one persisted runtime actor for every active gameplay being. In the target runtime projection, its actor identity is the typed numeric `runtimeEntityId`, scoped by `{tenantId, gameInstanceId}` as defined by the [identifier glossary](../../system-architecture-identifier-glossary.md). It is separate from the durable character UUID scoped by `{tenantId, playableStateNamespaceId}`. An older transport's `actorId` or character UUID is not silently reinterpreted as this runtime identity; services must not substitute private character row keys, parse or hash UUIDs, invent composite references such as `PLAYER:`, or introduce another opaque alias for the same runtime actor. +Every producer of a live runtime `entityId` must use the same Entity-owned allocation authority before a consumer treats its value as this runtime actor identity. Independently allocated legacy character, NPC or container row IDs must not be compared with or substituted for an owner-qualified `runtimeEntityId`; a matching numeric value does not establish the same actor. This precondition preserves one target identity rather than adding an alias. + - The actor core carries `tenantId`, `playableStateNamespaceId`, `gameInstanceId`, the resolved `playableStateScope` when it represents durable playable state, `actorKind`, display name, and presence state. It does not persist universal targetability or visibility fields. - A `PLAYER` actor is a runtime projection of the persisted actor and is unique for the active `{tenantId, playableStateNamespaceId, gameInstanceId, characterId}` execution context; it does not replace the canonical durable actor storage key `{tenantId, playableStateNamespaceId, characterId}` or turn separately validated `playableStateScope` into an identity dimension. `gameInstanceId` remains the replaceable runtime target/fence, and this S3 projection may be recreated during replacement while preserving the namespace-backed character. Disconnect/reconnect changes presence on the projection rather than creating a replacement durable identity. - An `NPC` actor links to one NPC runtime instance. An authored NPC definition may create many concurrent runtime NPC actors and is not itself actor identity. @@ -383,7 +385,7 @@ Character and NPC records remain the durable domain records for their respective ### Initial Runtime Actor Projection and Reference -The Entity-owned initial runtime projection is allocated only through the exact applicable authenticated assignment owner chain after its current authorization and target checks. Its complete unique association is `{tenantId, playableStateNamespaceId, gameInstanceId, characterId}`. The durable projection retains the original assignment operation, receipt and intent digest, complete target, projection fence and projection generation. Existing assignment, placement and roster character-UUID fields and immutable receipt bytes remain unchanged. For this projection boundary, the durable Entity `entity_runtime_entity_id_sequence` is the sole allocator. Adopting another canonical allocator requires an explicit migration that preserves uniqueness and nonreuse; allocator unavailability never authorizes runtime fallback to another allocator. A private database row key is never promoted into this role. +The Entity-owned initial runtime projection is allocated only through the exact applicable authenticated assignment owner chain after its current authorization and target checks. Its complete unique association is `{tenantId, playableStateNamespaceId, gameInstanceId, characterId}`. The durable projection retains the original assignment operation, receipt and intent digest, complete target, projection fence and projection generation. Existing assignment, placement and roster character-UUID fields and immutable receipt bytes remain unchanged. For this projection boundary, the durable Entity `entity_runtime_entity_id_sequence` is the sole allocator. Adopting another canonical allocator requires an explicit migration that preserves uniqueness and nonreuse; allocator unavailability never authorizes runtime fallback to another allocator. A private database row key is never promoted into this role. The bounded projection does not qualify convergence of legacy allocators; the [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#active-gaps) retains that implementation gap. Allocation guarantees concurrent uniqueness, stable exact retry and restart, and nonreuse throughout the required runtime and retention lifetime. Reconnect alone does not replace the projection. Runtime replacement is target state: the replacement owner allocates a new projection generation and runtime ID while retaining and fencing the previous association. A controlled source cannot authorize production allocation. Allocation alone establishes neither World placement, an active lifecycle, a Game Session region lease nor admission. diff --git a/design/architecture/system-architecture-identifier-glossary.md b/design/architecture/system-architecture-identifier-glossary.md index 2f688830dd..ebe3549bec 100644 --- a/design/architecture/system-architecture-identifier-glossary.md +++ b/design/architecture/system-architecture-identifier-glossary.md @@ -74,7 +74,7 @@ World Management may use a numeric room row key as `roomInstanceId` only when it ## Entity Identifiers -- `entityId` – identifies a live runtime entity (character, NPC, or container entity) within `(tenantId, gameInstanceId)` and may be a stable scoped number. Room-presence surfaces may present an item as an entity, but that presentation identity does not replace the typed `itemInstanceId` used by containment and equipment contracts. The target Entity runtime actor projection calls this typed identity `runtimeEntityId`; that name does not introduce another identity or alias. Its association to the separate durable character UUID and original assignment is owned by [Entity Runtime and Data](./microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference). +- `entityId` – identifies a live runtime entity (character, NPC, or container entity) within `(tenantId, gameInstanceId)` and may be a stable scoped number. Room-presence surfaces may present an item as an entity, but that presentation identity does not replace the typed `itemInstanceId` used by containment and equipment contracts. The target Entity runtime actor projection calls this same typed identity `runtimeEntityId`; treating values from different live producers as that one identity requires those producers to share the Entity-owned allocator. This is not a claim that current legacy row IDs already share that allocation. The allocator precondition, current legacy isolation and association to the separate durable character UUID and original assignment are owned by [Entity Runtime and Data](./microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference). - `itemInstanceId` – identifies a concrete live item instance within `(tenantId, gameInstanceId)`. It is distinct from the item's `entityTemplateId` and from any `entityId` used by a generic runtime-entity surface, and may be a stable scoped number under the same allocation, stability, and non-reuse guarantees. - `entityTemplateId` – identifies a versioned entity template (items, NPC definitions, equipment templates) scoped by `(tenantId, versionId)` and is a UUID logical identity. - Stable numeric `entityId` values may be presented to authorized players as disambiguators and accepted in gameplay commands. Resolution still enforces tenant, game-instance, location/visibility, and authorization scope. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index ae1d1d6a02..583da83a3b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -484,3 +484,9 @@ Entry format: - Observation: R993 acquired the freed slot first, and R992 exhausted its admission budget before Gradle or tests ran. Submitting the front retry earlier did not reserve execution priority; the initial queueing assumption delayed its proof. - Outcome: R996 subsequently passes the exact front case under the ordinary guard. R992 remains an unexecuted admission failure, not a failed native test or successful retry. - Expected pattern: Observe admission of the priority proof before launching another heavier waiter. Serialize subsequent qualification at the orchestrator when order matters rather than assuming fairness from resource exclusion. + +- `2026-10-29`: A published candidate migration was incorrectly treated as an applied artifact + - Context: #3341 needed a native timestamp/binary comparison correction in candidate V1040.5/.6. The initial forward-only approach could not cross V1040.5's earlier populated backfill. + - Observation: Publication in an unmerged PR was assumed to freeze those artifacts, although neither was in the immutable receiving parent and no authorized retained/live application was known. That unsupported assumption delayed the complete upgrade repair. + - Outcome: The owning migration contract and Overseer confirmed normal in-PR candidate correction, preserving all receiving-parent checksums and original evidence. R1010 subsequently passes populated actual-parent V1040.4 upgrade and changed-session owner proof; publication alone is not retained applied-state evidence. + - Expected pattern: Establish actual receiving-parent and applied-state obligations before choosing forward-only migration repair. A later migration cannot repair an earlier migration that fails before it executes; concrete retained applied-state evidence must be resolved rather than rewritten. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index fcff9b19d1..4fcba94e4e 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -245,6 +245,8 @@ The next review correction at code checkpoint `ce02d51f608f199e531de32c1d15f63cb ## Active Gaps +The initial runtime projection has one retained Entity allocator, but legacy character, NPC and container allocation paths have not converged onto it. Their numeric row IDs are not interchangeable with the purpose-specific owner-qualified runtime reference. Unified producer allocation and generic actor lookup remain unimplemented; the [Entity runtime identity owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#runtime-actor-identity) defines the target precondition. + - Entity has not registered `entity_preseeded_actor_runtime_projections` with the World instance-lifecycle cleanup owner or defined its termination disposition and acknowledgement. Room-ground cleanup does not cover this S3 family, so whole-instance `TERMINATED` remains blocked until owner registration and retention/cleanup proof exist; the [Entity runtime contract](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) records its lineage and deletion boundary. - Accepted TICK-03 requires command-level required/optional effect classification and invariant-sensitive routing; current gameplay families do not yet provide complete classification or terminal-outcome proof. See [ADR 0053](../../architecture/decisions/adr-0053-command-atomicity-by-invariant-class.md) and its [tick failure/operations owner](../../architecture/system-architecture-tick-failures-and-operations.md). - Accepted TICK-04 remains an implementation and proof gap: current replay paths do not establish cross-service operation/target/request-digest-bound participant guards, causal read composition, stale-precondition handling, or mixed-floor handling. The canonical mutation identity, participant-guard, and root/child lineage rules are owned by [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and the [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); accepted generated-child allocation is defined in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); its implementation and proof remain incomplete. This tracker records implementation and proof status only. 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 7fdc4bb5a5..df3fd3200a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Canonical NEW admission components +The #3341 session-rendering correction compares current cohort values through their authoritative PostgreSQL row types while retaining original frozen JSON, digests and plan identities. Candidate V1040.5/.6 compare frozen binary and timestamp attributes natively, including the earlier populated backfill. R1009 passes the initially-hex/escape capture and changed-session prepare/read/retry case plus three existing physical guard cases; its aggregate retains the failed actual-parent fixture setup. R1010 corrects that fixture ordering and passes actual populated V1040.4-to-V1040.6 upgrade before current-only ordinary NEW code, preserving applied history, cohort rows, anchor proof and Redis bytes, followed by actual baseline-member abort and exact retry under different connection settings. Enabled affected main/integration analysis, jOOQ generation and formatting pass across R1008–R1010. R1008's failed session-setting assertion and four unavailable PostgreSQL setup cases remain retained. These are controlled native owner and migration proofs, without production activation, custody or complete original-NEW recovery qualification. + The initial Entity runtime-actor producer and passive Game Session reference client are separated from the later World/region bootstrap consumer. Fresh authenticated preseeded assignment allocates the retained numeric runtime projection in its existing Entity transaction; the distinct exact Game Session read never allocates or backfills historical assignments. The producer retains its original receipt semantics, V1022 SQL postimage, migration fixtures, and focused owner/security proof. R981 freshly passes all 27 selected Entity owner/security units and all 96 selected Entity PostgreSQL cases across the six affected assignment, runtime projection and historical-fixture suites. These Entity cases passed within R981; its aggregate remains failed on a separate Game Session membership fixture, the migration-frontier argument and static checks. This qualifies the controlled receiving producer and its retained migrations; broader composition and production limits remain below. Production registration, runtime replacement, lifecycle cleanup registration, region ownership, protected admission and activation remain unqualified; the [Entity runtime owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) defines the bounded contract. The current-membership correction prepares forward V1040.5 and SQL-maintained references to original unretired local operations. Projection, capacity, slot registration, ADD-mutation reads and retirement conflict checks use current ownership rather than enumerating lifetime immutable history; pending-retirement validation starts from the bounded partition heads. Existing immutable provenance and exact owner checks remain required. The native retirement proof now checks current membership through pending/lost-reply/completion rollback/exact retry and more than 256 lifetime cycles. Its migration fixture adapts only the historical pre-membership slot-count read, retaining actual old-schema guards and post-upgrade backfill/current reads; it does not qualify a new gate before its schema exists. R974 freshly passed 14 of its 15 selected native cases, including the 257-cycle turnover case, but failed aggregate validation on shared-layout fixture setup. R975 and R977 passed the historical-frontier upgrade/backfill case; their new negative-guard proof exposed assertion and SQL-qualification defects, corrected before R978 passed that guard case. V1040.5 passes the migration-frontier check after renumbering the unapplied correction above its parent. These passing executions cover 16 distinct membership-related native cases across the retained runs; the earlier failed aggregates remain failures. The combined receiving R981 then passes 159 of 160 selected methods, including both actual World–Game Session–Account settlement compositions, but fails one membership fixture bootstrap because two cases reuse layout 11 with different baseline data. It also fails the full-SHA migration-frontier argument guard and a primitive-array varargs static warning in the new snapshot test. The fixture now uses its own layout 17, the test passes a named two-dimensional byte array, and R983 passes all three former-collision/snapshot cases together with integration Checkstyle, SpotBugs and formatting. All 160 distinct selected methods therefore have passing execution across R981/R983; R981 remains a failed aggregate. The complete immutable-parent frontier and final documentation checks are separate publication checks. This does not establish registration, live issuer custody, activation or production admission. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index 827612ed42..4abd0abf14 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayOutputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; @@ -112,9 +113,13 @@ private CanonicalGameplayIssuerPartitionBuildPlan prepareInTransaction( bootstrapRequestId, currentInventoryRevision); + requireCurrentCohortMatches( + transaction, + intent.cohortRows(), + captureCurrentCohort(transaction, intent.inventorySnapshotRevision())); + // All plan identity, work references and digests remain derived from the original capture. List currentRows = - captureCurrentCohort(transaction, intent.inventorySnapshotRevision()); - requireSameCohort(intent.cohortRows(), currentRows); + intent.cohortRows().stream().map(IssuerCohortSourceRow::new).toList(); DerivedPlan derived = derivePlan(intent, currentRows); Record existing = @@ -216,9 +221,13 @@ CanonicalGameplayIssuerPartitionBuildPlan readPreparedPlanInTransaction( bootstrapOperationId, bootstrapRequestId, currentInventoryRevision); + requireCurrentCohortMatches( + transaction, + intent.cohortRows(), + captureCurrentCohort(transaction, intent.inventorySnapshotRevision())); + // All plan identity, work references and digests remain derived from the original capture. List currentRows = - captureCurrentCohort(transaction, intent.inventorySnapshotRevision()); - requireSameCohort(intent.cohortRows(), currentRows); + intent.cohortRows().stream().map(IssuerCohortSourceRow::new).toList(); DerivedPlan derived = derivePlan(intent, currentRows); Record buildPlanRow = transaction.fetchOne( @@ -606,6 +615,59 @@ private static List captureCurrentCohort( }); } + private static void requireCurrentCohortMatches( + DSLContext transaction, + List frozen, + List current) { + if (frozen.size() != current.size()) { + throw conflict( + "Current source inventory no longer equals its complete frozen bootstrap cohort"); + } + for (int index = 0; index < frozen.size(); index++) { + var expected = frozen.get(index); + var actual = current.get(index).cohortRow(); + Set frozenKeys = new HashSet<>(); + Set currentKeys = new HashSet<>(); + parseObject(expected.sourceRowJson()).fieldNames().forEachRemaining(frozenKeys::add); + parseObject(actual.sourceRowJson()).fieldNames().forEachRemaining(currentKeys::add); + if (expected.rowOrdinal() != index + || expected.kind() != actual.kind() + || !expected.sourceKey().equals(actual.sourceKey()) + || !expected.sourceInventoryRevision().equals(actual.sourceInventoryRevision()) + || !frozenKeys.equals(currentKeys)) { + throw conflict("Current source row differs from its exact original bootstrap cohort entry"); + } + // Use the authoritative table row type, including native bytea/timestamptz equality. + // Exact JSON key sets above prevent populate_record from hiding missing or added fields. + String sourceTable = + switch (expected.kind()) { + case BINDING, UNRESOLVED_LEGACY_BINDING -> + "game_session_canonical_gameplay_binding_inventory"; + case RESERVATION, UNRESOLVED_LEGACY_RESERVATION -> + "game_session_canonical_issuer_partition_reservation"; + case TRANSITION -> "game_session_canonical_binding_transition"; + case ACCOUNT_OBLIGATION -> "game_session_canonical_binding_account_index_obligation"; + case ISSUER_OBLIGATION -> "game_session_canonical_binding_issuer_index_obligation"; + case REGION_OBLIGATION -> "game_session_canonical_binding_region_bridge_obligation"; + }; + boolean sameValues = + Boolean.TRUE.equals( + transaction + .fetchSingle( + "SELECT jsonb_populate_record(NULL::" + + sourceTable + + ", ?::jsonb) IS NOT DISTINCT FROM jsonb_populate_record(NULL::" + + sourceTable + + ", ?::jsonb)", + expected.sourceRowJson(), + actual.sourceRowJson()) + .get(0, Boolean.class)); + if (!sameValues) { + throw conflict("Current source row differs from its exact original bootstrap cohort entry"); + } + } + } + private static void requireSameCohort( List frozen, List current) { @@ -1832,14 +1894,50 @@ private static UUID uuid(JsonNode json, String field) { private static byte[] bytea(JsonNode json, String field) { String value = text(json, field); - if (!value.startsWith("\\x") || (value.length() & 1) != 0) { - throw conflict("Cohort source row bytea field is not PostgreSQL hex text: " + field); + if (value.startsWith("\\x")) { + try { + return HexFormat.of().parseHex(value.substring(2)); + } catch (IllegalArgumentException malformed) { + throw conflict("Cohort source row bytea field is malformed: " + field); + } } - try { - return HexFormat.of().parseHex(value.substring(2)); - } catch (IllegalArgumentException malformed) { - throw conflict("Cohort source row bytea field is malformed: " + field); + // PostgreSQL escape output uses printable ASCII, doubled backslashes, or three octal digits. + // Decode bytes directly; a character-set conversion must not change binding reference identity. + ByteArrayOutputStream decoded = new ByteArrayOutputStream(value.length()); + for (int index = 0; index < value.length(); index++) { + char next = value.charAt(index); + if (next == '\\') { + if (++index >= value.length()) { + throw conflict("Cohort source row bytea field is malformed: " + field); + } + char escaped = value.charAt(index); + if (escaped == '\\') { + decoded.write('\\'); + } else { + if (index + 2 >= value.length() + || escaped < '0' + || escaped > '3' + || value.charAt(index + 1) < '0' + || value.charAt(index + 1) > '7' + || value.charAt(index + 2) < '0' + || value.charAt(index + 2) > '7') { + throw conflict("Cohort source row bytea field is malformed: " + field); + } + decoded.write( + (escaped - '0') * 64 + + (value.charAt(index + 1) - '0') * 8 + + value.charAt(index + 2) + - '0'); + index += 2; + } + } else { + if (next < 32 || next > 126) { + throw conflict("Cohort source row bytea field is malformed: " + field); + } + decoded.write(next); + } } + return decoded.toByteArray(); } private static BigInteger readBigInteger(Record row, String field) { diff --git a/services/game-session-service/src/main/resources/db/migration/V1040.5__current_issuer_local_operation_membership.sql b/services/game-session-service/src/main/resources/db/migration/V1040.5__current_issuer_local_operation_membership.sql index 070fce39a6..e9439ce771 100644 --- a/services/game-session-service/src/main/resources/db/migration/V1040.5__current_issuer_local_operation_membership.sql +++ b/services/game-session-service/src/main/resources/db/migration/V1040.5__current_issuer_local_operation_membership.sql @@ -248,8 +248,13 @@ BEGIN AND cohort.source_kind = 'RESERVATION' AND cohort.source_key = reservation_identity::text AND cohort.source_inventory_revision <= reservation.inventory_revision - AND (cohort.source_row_json::jsonb - 'lifecycle' - 'inventory_revision') - = (to_jsonb(reservation) - 'lifecycle' - 'inventory_revision')) THEN + -- Session rendering is not source identity: compare timestamp and binary values natively. + AND (cohort.source_row_json::jsonb ->> 'binding_ref')::bytea = reservation.binding_ref + AND (cohort.source_row_json::jsonb ->> 'created_at')::timestamptz = reservation.created_at + AND (cohort.source_row_json::jsonb - 'lifecycle' - 'inventory_revision' + - 'binding_ref' - 'created_at') + = (to_jsonb(reservation) - 'lifecycle' - 'inventory_revision' + - 'binding_ref' - 'created_at')) THEN RETURN; END IF; RAISE EXCEPTION 'Installed issuer reservation requires exact bootstrap or current local-operation membership' diff --git a/services/game-session-service/src/main/resources/db/migration/V1040.6__issuer_bootstrap_membership_frozen_columns.sql b/services/game-session-service/src/main/resources/db/migration/V1040.6__issuer_bootstrap_membership_frozen_columns.sql index 062ab0a0cd..37b0b043b0 100644 --- a/services/game-session-service/src/main/resources/db/migration/V1040.6__issuer_bootstrap_membership_frozen_columns.sql +++ b/services/game-session-service/src/main/resources/db/migration/V1040.6__issuer_bootstrap_membership_frozen_columns.sql @@ -60,8 +60,8 @@ BEGIN AND cohort.source_inventory_revision <= reservation.inventory_revision AND cohort.source_row_json::jsonb -> 'reservation_id' = to_jsonb(reservation.reservation_id) - AND cohort.source_row_json::jsonb -> 'binding_ref' - = to_jsonb(reservation.binding_ref) + AND (cohort.source_row_json::jsonb ->> 'binding_ref')::bytea + = reservation.binding_ref AND cohort.source_row_json::jsonb -> 'account_id' = to_jsonb(reservation.account_id) AND cohort.source_row_json::jsonb -> 'tenant_id' @@ -108,8 +108,8 @@ BEGIN = to_jsonb(reservation.coverage_fence) AND cohort.source_row_json::jsonb -> 'inventory_snapshot_revision' = to_jsonb(reservation.inventory_snapshot_revision) - AND cohort.source_row_json::jsonb -> 'created_at' - = to_jsonb(reservation.created_at)) THEN + AND (cohort.source_row_json::jsonb ->> 'created_at')::timestamptz + = reservation.created_at) THEN RETURN; END IF; RAISE EXCEPTION 'Installed issuer reservation requires exact bootstrap or current local-operation membership' diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 5d08abd380..80f279348d 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 @@ -22,6 +22,7 @@ import java.util.Objects; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; @@ -123,6 +124,26 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( RedisClient issuerRedisClient, int seedBootstrapMemberCount, MigrationVersion migrationTarget) { + this( + accountDataSource, + accountCandidate, + issuerRedisClient, + seedBootstrapMemberCount, + migrationTarget, + (data, intent) -> {}); + } + + /** + * Lets a populated-parent upgrade run after actual bootstrap and before current-only NEW code. + */ + public CanonicalGameplayAdmissionAbortCompositionFixture( + DriverManagerDataSource accountDataSource, + Candidate accountCandidate, + RedisClient issuerRedisClient, + int seedBootstrapMemberCount, + MigrationVersion migrationTarget, + BiConsumer + afterBootstrap) { if (seedBootstrapMemberCount < 0 || seedBootstrapMemberCount > 256) { throw new IllegalArgumentException("Bootstrap fixture member count must be within [0, 256]"); } @@ -216,6 +237,7 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( issuerRedisClient, issuerCatalog, issuerSource); new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) .completeInitialBootstrap(bootstrapIntent.operationId(), bootstrapRequestId); + Objects.requireNonNull(afterBootstrap, "afterBootstrap").accept(dataSource, bootstrapIntent); var request = new CanonicalGameplayIssuerBindingLocalOperation.Request( UUID.randomUUID(), transitionId, identity, null, null); @@ -584,10 +606,26 @@ public List migrationHistoryImage() { /** Applies pending Game Session migrations with Flyway's default version ordering. */ public int upgradeWithDefaultGameSessionMigrations(MigrationVersion migrationTarget) { + return upgradeWithDefaultGameSessionMigrations(migrationTarget, dataSource); + } + + /** Initializes rendering on every owned Flyway connection, not one unrelated SQL session. */ + public int upgradeWithDefaultGameSessionMigrations( + MigrationVersion migrationTarget, String timeZone, String byteaOutput) { + return upgradeWithDefaultGameSessionMigrations( + migrationTarget, dataSourceWithRendering(timeZone, byteaOutput)); + } + + static int upgradeWithDefaultGameSessionMigrations( + MigrationVersion migrationTarget, DriverManagerDataSource migrationDataSource) { + String schema = + DSL.using(migrationDataSource, SQLDialect.POSTGRES) + .fetchSingle("SELECT current_schema()") + .get(0, String.class); Flyway flyway = Flyway.configure() .target(Objects.requireNonNull(migrationTarget, "migrationTarget")) - .dataSource(dataSource) + .dataSource(migrationDataSource) .schemas(schema) .defaultSchema(schema) .placeholders(java.util.Map.of("serviceSchema", schema)) @@ -598,6 +636,33 @@ public int upgradeWithDefaultGameSessionMigrations(MigrationVersion migrationTar return result.migrationsExecuted; } + private DriverManagerDataSource dataSourceWithRendering(String timeZone, String byteaOutput) { + return CanonicalGameplayIssuerTestFixtures.withSessionRendering( + dataSource, timeZone, byteaOutput); + } + + /** + * Runs the real abort owner for one original bootstrap member using changed session rendering. + */ + public CanonicalGameplayAdmissionAbortSource recordBootstrapAccountAbort( + UUID reservationId, String timeZone, String byteaOutput) { + DSLContext configured = + DSL.using(dataSourceWithRendering(timeZone, byteaOutput), SQLDialect.POSTGRES); + UUID bootstrapTransition = + configured + .fetchSingle( + "SELECT transition_id FROM game_session_canonical_issuer_partition_reservation" + + " WHERE reservation_id = ?", + reservationId) + .get(0, UUID.class); + var owner = new CanonicalGameplayBindingInventoryRepository(configured); + var source = owner.readFirstNewAdmissionAbortSource(bootstrapTransition); + return owner.recordFirstNewAccountAbort( + source, + UUID.nameUUIDFromBytes( + ("bootstrap-controller-cleanup:" + reservationId).getBytes(StandardCharsets.UTF_8))); + } + /** * Exercises the deferred initial-abort SQL guard after the actual GS abort owner has written its * source, then advances Account control before the enclosing transaction commits. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java index 5b5b62d2bd..72e208abf5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java @@ -136,6 +136,16 @@ protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( Candidate candidate, int seedBootstrapMemberCount, MigrationVersion migrationTarget) { + return newFixture(candidate, seedBootstrapMemberCount, migrationTarget, (data, intent) -> {}); + } + + protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( + Candidate candidate, + int seedBootstrapMemberCount, + MigrationVersion migrationTarget, + java.util.function.BiConsumer< + DriverManagerDataSource, CanonicalGameplayIssuerLayoutBootstrapIntent> + afterBootstrap) { DriverManagerDataSource accountDataSource = new DriverManagerDataSource(); accountDataSource.setDriverClassName("org.postgresql.Driver"); String postgresJdbcUrl = postgres().getJdbcUrl(); @@ -144,7 +154,12 @@ protected CanonicalGameplayAdmissionAbortCompositionFixture newFixture( accountDataSource.setUsername(postgres().getUsername()); accountDataSource.setPassword(postgres().getPassword()); return new CanonicalGameplayAdmissionAbortCompositionFixture( - accountDataSource, candidate, issuerOwner, seedBootstrapMemberCount, migrationTarget); + accountDataSource, + candidate, + issuerOwner, + seedBootstrapMemberCount, + migrationTarget, + afterBootstrap); } protected static Candidate controlledCandidate() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java index 66b8cd7366..feebecb948 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java @@ -687,6 +687,135 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu } } + @Test + void frozenPlanPreservesNativeSourceValuesAcrossSessionRenderings() { + for (String captureFormat : List.of("hex", "escape")) { + TestSchema testSchema = newTestSchema("gs_build_native_"); + try { + var captureSchema = sessionSchema(testSchema, "UTC", captureFormat); + var fixture = pendingFixture(captureSchema); + var prepareSchema = + sessionSchema( + testSchema, "Pacific/Auckland", captureFormat.equals("hex") ? "escape" : "hex"); + var owner = new CanonicalGameplayIssuerPartitionBuildRepository(prepareSchema.dsl()); + List sourceBefore = + rowImagesWithXmin( + testSchema.dsl(), "game_session_canonical_issuer_partition_reservation"); + List intentCohortBefore = + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_cohort_row"); + var plan = + owner.prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId()); + assertThat(plan.state()) + .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.PREPARED); + assertThat(plan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowJson) + .containsExactlyElementsOf( + fixture.intent().cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowJson) + .toList()); + List planBefore = + rowImagesWithXmin( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_plan"); + List buildCohortBefore = + rowImagesWithXmin( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_cohort_row"); + List workBefore = + rowImagesWithXmin( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_member_work"); + var readSchema = sessionSchema(testSchema, "America/New_York", captureFormat); + var readPlan = + readSchema + .dsl() + .transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, fixture.intent().operationId(), fixture.requestId()); + }); + assertThat(readPlan.buildOperationId()).isEqualTo(plan.buildOperationId()); + assertThat(readPlan.planDigest()).isEqualTo(plan.planDigest()); + assertThat(readPlan.cohortRows()) + .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .containsExactlyElementsOf( + plan.cohortRows().stream() + .map(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) + .toList()); + var retry = + new CanonicalGameplayIssuerPartitionBuildRepository(captureSchema.dsl()) + .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId()); + assertThat(retry.buildOperationId()).isEqualTo(plan.buildOperationId()); + assertThat(retry.planDigest()).isEqualTo(plan.planDigest()); + assertThatThrownBy( + () -> + prepareSchema + .dsl() + .transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET coverage_fence = coverage_fence + 1" + + " WHERE reservation_id = ?", + fixture.reservationId())) + .isOne(); + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, + fixture.intent().operationId(), + fixture.requestId()); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current source row differs"); + for (String changedKeys : + List.of("ADD COLUMN unexpected_attribute text", "DROP COLUMN created_at")) { + assertThatThrownBy( + () -> + prepareSchema + .dsl() + .transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute( + "ALTER TABLE game_session_canonical_issuer_partition_reservation " + + changedKeys); + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, + fixture.intent().operationId(), + fixture.requestId()); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current source row differs"); + } + assertThat( + rowImagesWithXmin( + testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) + .containsExactlyElementsOf(sourceBefore); + assertThat( + rowImages( + testSchema.dsl(), "game_session_canonical_issuer_layout_bootstrap_cohort_row")) + .containsExactlyElementsOf(intentCohortBefore); + assertThat( + rowImagesWithXmin( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_plan")) + .containsExactlyElementsOf(planBefore); + assertThat( + rowImagesWithXmin( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_cohort_row")) + .containsExactlyElementsOf(buildCohortBefore); + assertThat( + rowImagesWithXmin( + testSchema.dsl(), "game_session_canonical_issuer_partition_build_member_work")) + .containsExactlyElementsOf(workBefore); + } finally { + dropSchema(testSchema.schema()); + } + } + } + @Test void exactOwnerRejectsMissingWrongRequestMissingControlAndChangedFrozenSources() { TestSchema testSchema = newTestSchema("gs_issuer_build_intent_fence_"); @@ -2160,6 +2289,19 @@ private static void insertLegacyReservationBeforeIssuerStringConversion(DSLConte + " SET inventory_revision = 1 WHERE singleton_id = 1 AND inventory_revision = 0"); } + private static TestSchema sessionSchema(TestSchema schema, String timeZone, String byteaOutput) { + DriverManagerDataSource sessionDataSource = + CanonicalGameplayIssuerTestFixtures.withSessionRendering( + dataSource(schema.schema()), timeZone, byteaOutput); + DSLContext sessionDsl = DSL.using(sessionDataSource, SQLDialect.POSTGRES); + var settings = + sessionDsl.fetchSingle( + "SELECT current_setting('TimeZone'), current_setting('bytea_output')"); + assertThat(settings.get(0, String.class)).isEqualTo(timeZone); + assertThat(settings.get(1, String.class)).isEqualTo(byteaOutput); + return new TestSchema(schema.schema(), sessionDataSource, sessionDsl); + } + private static DriverManagerDataSource dataSource(String schema) { return CanonicalGameplayIssuerTestFixtures.dataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), schema); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index 12ce95c3bc..7084a40fb0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -876,6 +876,198 @@ void bootstrapMembershipPreservesFrozenOwnershipAcrossAnUnrelatedAdditiveColumn( } } + @Test + void bootstrapMembershipPreservesNativeAttributesAcrossSessionRenderingChanges() { + try (var fixture = + newFixture( + controlledCandidate(BigInteger.valueOf(23), BigInteger.ONE), + 1, + MigrationVersion.fromVersion("1040.4"), + this::upgradeRetainedBootstrapWithChangedSession)) { + assertThat(fixture.originalBaselineReservationCount()).isOne(); + String baselineSourceSql = + " FROM game_session_canonical_issuer_installed_anchor anchor" + + " JOIN game_session_canonical_issuer_partition_build_cohort_row cohort" + + " ON cohort.build_operation_id = anchor.build_operation_id" + + " AND cohort.source_operation_id = anchor.bootstrap_operation_id" + + " AND cohort.issuer_id = anchor.issuer_id" + + " AND cohort.source_kind = 'RESERVATION'"; + UUID baselineReservationId = + fixture + .dsl() + .fetchSingle("SELECT cohort.source_key::uuid" + baselineSourceSql) + .get(0, UUID.class); + String retainedOwnerSql = + "SELECT jsonb_build_object('cohort', to_jsonb(cohort), 'anchor', to_jsonb(anchor))::text" + + baselineSourceSql; + String retainedOwnerBefore = fixture.dsl().fetchSingle(retainedOwnerSql).get(0, String.class); + String reservationBefore = reservationImage(fixture.dsl(), baselineReservationId); + String historyBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); + List migrationHistoryAfter = fixture.migrationHistoryImage(); + List membershipBefore = currentOperationIds(fixture.dsl()); + byte[] partitionBefore = physicalFieldSet(fixture.issuerPartitionKey()); + + Map timestampRenderings = new HashMap<>(); + Map binaryRenderings = new HashMap<>(); + for (String timeZone : List.of("UTC", "Pacific/Auckland", "America/New_York")) { + for (String byteaOutput : List.of("hex", "escape")) { + fixture + .dsl() + .transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + // LOCAL settings and the guard use this transaction's same owned connection. + transaction.execute("SET LOCAL TimeZone = '" + timeZone + "'"); + transaction.execute("SET LOCAL bytea_output = '" + byteaOutput + "'"); + var rendered = + transaction.fetchSingle( + "SELECT to_jsonb(created_at)::text, to_jsonb(binding_ref)::text FROM" + + " game_session_canonical_issuer_partition_reservation" + + " WHERE reservation_id = ?", + baselineReservationId); + timestampRenderings.put(timeZone, rendered.get(0, String.class)); + binaryRenderings.put(byteaOutput, rendered.get(1, String.class)); + transaction.fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", + baselineReservationId); + }); + } + } + assertThat(timestampRenderings.values()).doesNotHaveDuplicates(); + assertThat(binaryRenderings.values()).doesNotHaveDuplicates(); + assertThatThrownBy( + () -> + fixture + .dsl() + .transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET LOCAL TimeZone = 'Pacific/Auckland'"); + transaction.execute("SET LOCAL bytea_output = 'escape'"); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET coverage_fence = coverage_fence + 1" + + " WHERE reservation_id = ?", + baselineReservationId)) + .isOne(); + transaction.fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", + baselineReservationId); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining( + "Installed issuer reservation requires exact bootstrap or current local-operation membership"); + assertThat(fixture.migrationHistoryImage()).containsExactlyElementsOf(migrationHistoryAfter); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(historyBefore); + assertThat(fixture.dsl().fetchSingle(retainedOwnerSql).get(0, String.class)) + .isEqualTo(retainedOwnerBefore); + assertThat(reservationImage(fixture.dsl(), baselineReservationId)) + .isEqualTo(reservationBefore); + assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBefore); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(partitionBefore); + String immutableReservationSql = + "SELECT (to_jsonb(reservation) - 'lifecycle' - 'inventory_revision')::text FROM" + + " game_session_canonical_issuer_partition_reservation reservation" + + " WHERE reservation_id = ?"; + String immutableReservationBefore = + fixture + .dsl() + .fetchSingle(immutableReservationSql, baselineReservationId) + .get(0, String.class); + var aborted = + fixture.recordBootstrapAccountAbort(baselineReservationId, "Pacific/Auckland", "escape"); + assertThat(aborted.isAccountAborted()).isTrue(); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT lifecycle FROM game_session_canonical_issuer_partition_reservation WHERE reservation_id = ?", + baselineReservationId) + .get(0, String.class)) + .isEqualTo("RELEASE_PENDING"); + assertThat( + fixture + .dsl() + .fetchSingle(immutableReservationSql, baselineReservationId) + .get(0, String.class)) + .isEqualTo(immutableReservationBefore); + assertThat(fixture.dsl().fetchSingle(retainedOwnerSql).get(0, String.class)) + .isEqualTo(retainedOwnerBefore); + String afterAbort = reservationImage(fixture.dsl(), baselineReservationId); + String afterAbortHistory = durableHistoryImage(fixture.dsl(), NIL_UUID); + assertThat( + fixture + .recordBootstrapAccountAbort(baselineReservationId, "America/New_York", "hex") + .orphanCleanupId()) + .isEqualTo(aborted.orphanCleanupId()); + assertThat(reservationImage(fixture.dsl(), baselineReservationId)).isEqualTo(afterAbort); + assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(afterAbortHistory); + assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(partitionBefore); + } + } + + private void upgradeRetainedBootstrapWithChangedSession( + org.springframework.jdbc.datasource.DriverManagerDataSource dataSource, + CanonicalGameplayIssuerLayoutBootstrapIntent intent) { + DSLContext parent = DSL.using(dataSource, org.jooq.SQLDialect.POSTGRES); + assertThat( + parent + .fetchSingle( + "SELECT to_regclass('game_session_canonical_issuer_current_local_operation')::text") + .get(0, String.class)) + .isNull(); + String history = durableHistoryImage(parent, NIL_UUID); + String anchor = anchorAndPartitionProofImage(parent); + List cohort = + parent + .fetch( + "SELECT xmin::text || ':' || to_jsonb(retained_row)::text FROM" + + " game_session_canonical_issuer_partition_build_cohort_row retained_row ORDER BY source_row_ordinal") + .getValues(0, String.class); + List before = + parent + .fetch( + "SELECT to_jsonb(retained_row)::text FROM flyway_schema_history retained_row ORDER BY installed_rank") + .getValues(0, String.class); + byte[] partitionKey = + CanonicalGameplayIssuerRedisKeys.forPartition(intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII); + byte[] physical = physicalFieldSet(partitionKey); + var changed = + CanonicalGameplayIssuerTestFixtures.withSessionRendering( + dataSource, "America/New_York", "escape"); + var settings = + DSL.using(changed, org.jooq.SQLDialect.POSTGRES) + .fetchSingle("SELECT current_setting('TimeZone'), current_setting('bytea_output')"); + assertThat(settings.get(0, String.class)).isEqualTo("America/New_York"); + assertThat(settings.get(1, String.class)).isEqualTo("escape"); + assertThat( + CanonicalGameplayAdmissionAbortCompositionFixture + .upgradeWithDefaultGameSessionMigrations( + MigrationVersion.fromVersion("1040.6"), changed)) + .isEqualTo(2); + List after = + parent + .fetch( + "SELECT to_jsonb(retained_row)::text FROM flyway_schema_history retained_row ORDER BY installed_rank") + .getValues(0, String.class); + assertThat(after).hasSize(before.size() + 2); + assertThat(after.subList(0, before.size())).containsExactlyElementsOf(before); + assertThat(durableHistoryImage(parent, NIL_UUID)).isEqualTo(history); + assertThat(anchorAndPartitionProofImage(parent)).isEqualTo(anchor); + assertThat( + parent + .fetch( + "SELECT xmin::text || ':' || to_jsonb(retained_row)::text FROM" + + " game_session_canonical_issuer_partition_build_cohort_row retained_row ORDER BY source_row_ordinal") + .getValues(0, String.class)) + .containsExactlyElementsOf(cohort); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(physical); + } + @Test void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceMismatch() { // A seeded baseline needs its own physical layout; sibling cases retain their issuer hashes. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java index 2691789cc0..bc2e5ed1a1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerTestFixtures.java @@ -10,11 +10,13 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.SQLException; import java.time.Duration; import java.util.EnumSet; import java.util.List; import java.util.Map; +import java.util.Properties; import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; @@ -56,6 +58,42 @@ static DriverManagerDataSource dataSource( return dataSource; } + /** Initializes every owned test connection after JDBC has applied its own startup timezone. */ + static DriverManagerDataSource withSessionRendering( + DriverManagerDataSource original, String timeZone, String byteaOutput) { + if (!List.of("UTC", "Pacific/Auckland", "America/New_York").contains(timeZone) + || !List.of("hex", "escape").contains(byteaOutput)) { + throw new IllegalArgumentException("Unsupported fixture session rendering"); + } + var configured = + new DriverManagerDataSource() { + @Override + protected Connection getConnectionFromDriver(Properties properties) throws SQLException { + Connection connection = super.getConnectionFromDriver(properties); + try (PreparedStatement settings = + connection.prepareStatement( + "SELECT set_config('TimeZone', ?, false), set_config('bytea_output', ?, false)")) { + settings.setString(1, timeZone); + settings.setString(2, byteaOutput); + settings.execute(); + return connection; + } catch (SQLException | RuntimeException failure) { + try { + connection.close(); + } catch (SQLException cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + }; + configured.setDriverClassName("org.postgresql.Driver"); + configured.setUrl(original.getUrl()); + configured.setUsername(original.getUsername()); + configured.setPassword(original.getPassword()); + return configured; + } + static void migrateSchema( DriverManagerDataSource dataSource, String schema, From fbe5f7168e569021669dec9f17f120bf409f2444 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:22:00 +1300 Subject: [PATCH 8/9] fix(gameplay): batch frozen-source checks and consolidate settlement proof --- .../runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 4 +- .../player-access-and-session.md | 2 +- ...ameplayIssuerPartitionBuildRepository.java | 23 +- ...rtitionBuildRepositoryIntegrationTest.java | 68 +++++- ...ationOwnerCompositionCrossServiceTest.java | 220 ++++++++---------- 6 files changed, 178 insertions(+), 141 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 67857a10e7..2aa06e1167 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -389,7 +389,7 @@ The Entity-owned initial runtime projection is allocated only through the exact Allocation guarantees concurrent uniqueness, stable exact retry and restart, and nonreuse throughout the required runtime and retention lifetime. Reconnect alone does not replace the projection. Runtime replacement is target state: the replacement owner allocates a new projection generation and runtime ID while retaining and fencing the previous association. A controlled source cannot authorize production allocation. Allocation alone establishes neither World placement, an active lifecycle, a Game Session region lease nor admission. -The `entity_preseeded_actor_runtime_projections` runtime identity is S3 for instance-lifecycle partitioning. Its immutable assignment association and provenance remain recovery and nonreuse lineage subject to the canonical reference, hold, and retention rules; this classification grants no deletion permission or numeric retention horizon. V1022 currently permits initial projections only: its assignment and association uniqueness constraints and its update, delete, and truncate guards prevent replacement. Implementing the target replacement transition requires forward schema evolution and the qualified replacement-owner chain while preserving retained associations and nonreuse. Entity has not registered this family with World Management or defined its termination disposition and cleanup acknowledgement, so room-ground cleanup does not cover it and whole-instance `TERMINATED` remains blocked until lifecycle registration and retention/cleanup proof exist. See [Instance Termination Cleanup Contract](#instance-termination-cleanup-contract), [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md), [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md), and the [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#active-gaps). +The `entity_preseeded_actor_runtime_projections` runtime identity is S3 for instance-lifecycle partitioning. Its immutable assignment association and provenance remain recovery and nonreuse lineage subject to the canonical reference, hold, and retention rules; this classification grants no deletion permission or numeric retention horizon. Current replacement and lifecycle-registration limitations are recorded in the [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#active-gaps). See [Instance Termination Cleanup Contract](#instance-termination-cleanup-contract), [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md), [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md), and the [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#active-gaps). The existing assignment service exposes one separate purpose-specific runtime-reference read to the exact same-namespace Game Session workload. It selects the original assignment, complete target and character, loads the actual retained projection, and returns a closed bounded typed reference with its full owner-qualified association, original assignment provenance, projection fence and generation. The read never allocates or repairs missing projection state, and an unavailable, stale or contradictory source fails closed. The World-only immutable assignment-receipt read retains its distinct purpose and authority. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 4fcba94e4e..9732ff72d7 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -245,9 +245,9 @@ The next review correction at code checkpoint `ce02d51f608f199e531de32c1d15f63cb ## Active Gaps -The initial runtime projection has one retained Entity allocator, but legacy character, NPC and container allocation paths have not converged onto it. Their numeric row IDs are not interchangeable with the purpose-specific owner-qualified runtime reference. Unified producer allocation and generic actor lookup remain unimplemented; the [Entity runtime identity owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#runtime-actor-identity) defines the target precondition. +- The initial runtime projection has one retained Entity allocator, but legacy character, NPC and container allocation paths have not converged onto it. Their numeric row IDs are not interchangeable with the purpose-specific owner-qualified runtime reference. Unified producer allocation and generic actor lookup remain unimplemented; the [Entity runtime identity owner](../../architecture/microservices/entity-management-service/runtime-and-data.md#runtime-actor-identity) defines the target precondition. -- Entity has not registered `entity_preseeded_actor_runtime_projections` with the World instance-lifecycle cleanup owner or defined its termination disposition and acknowledgement. Room-ground cleanup does not cover this S3 family, so whole-instance `TERMINATED` remains blocked until owner registration and retention/cleanup proof exist; the [Entity runtime contract](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) records its lineage and deletion boundary. +- V1022 currently supports only initial runtime projections: assignment/association uniqueness and update, delete and truncate guards prevent replacement. Replacement needs forward schema evolution and qualified replacement-owner proof preserving retained associations and nonreuse. Entity has not registered `entity_preseeded_actor_runtime_projections` with the World instance-lifecycle cleanup owner or defined its termination disposition and acknowledgement. Room-ground cleanup does not cover this S3 family, so whole-instance `TERMINATED` remains blocked until owner registration and retention/cleanup proof exist; the [Entity runtime contract](../../architecture/microservices/entity-management-service/runtime-and-data.md#initial-runtime-actor-projection-and-reference) records its lineage and deletion boundary. - Accepted TICK-03 requires command-level required/optional effect classification and invariant-sensitive routing; current gameplay families do not yet provide complete classification or terminal-outcome proof. See [ADR 0053](../../architecture/decisions/adr-0053-command-atomicity-by-invariant-class.md) and its [tick failure/operations owner](../../architecture/system-architecture-tick-failures-and-operations.md). - Accepted TICK-04 remains an implementation and proof gap: current replay paths do not establish cross-service operation/target/request-digest-bound participant guards, causal read composition, stale-precondition handling, or mixed-floor handling. The canonical mutation identity, participant-guard, and root/child lineage rules are owned by [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and the [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); accepted generated-child allocation is defined in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); its implementation and proof remain incomplete. This tracker records implementation and proof status only. - [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md) accepts a causal floor plus actual opaque World/Entity component versions; current LOOK composition still has scope-marker compatibility behavior, bounded stale-floor retry, and final read-fence error mapping gaps. This tracker does not claim the accepted presentation identity is implemented. 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 df3fd3200a..8a72e26115 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -374,7 +374,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index 4abd0abf14..c313f550cd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import java.io.ByteArrayOutputStream; import java.math.BigDecimal; import java.math.BigInteger; @@ -623,6 +624,7 @@ private static void requireCurrentCohortMatches( throw conflict( "Current source inventory no longer equals its complete frozen bootstrap cohort"); } + Map comparisonsByTable = new HashMap<>(); for (int index = 0; index < frozen.size(); index++) { var expected = frozen.get(index); var actual = current.get(index).cohortRow(); @@ -650,17 +652,28 @@ private static void requireCurrentCohortMatches( case ISSUER_OBLIGATION -> "game_session_canonical_binding_issuer_index_obligation"; case REGION_OBLIGATION -> "game_session_canonical_binding_region_bridge_obligation"; }; + var pair = + comparisonsByTable + .computeIfAbsent(sourceTable, ignored -> JSON.createArrayNode()) + .addObject(); + pair.set("frozen", parseObject(expected.sourceRowJson())); + pair.set("current", parseObject(actual.sourceRowJson())); + } + // The inventory clock is held here. Round trips are bounded by the six source tables, + // independent of cohort size, including when the complete plan is rechecked per member. + for (var comparison : comparisonsByTable.entrySet()) { + String sourceTable = comparison.getKey(); boolean sameValues = Boolean.TRUE.equals( transaction .fetchSingle( - "SELECT jsonb_populate_record(NULL::" + "SELECT NOT EXISTS (SELECT 1 FROM jsonb_array_elements(?::jsonb) paired(value)" + + " WHERE jsonb_populate_record(NULL::" + sourceTable - + ", ?::jsonb) IS NOT DISTINCT FROM jsonb_populate_record(NULL::" + + ", value -> 'frozen') IS DISTINCT FROM jsonb_populate_record(NULL::" + sourceTable - + ", ?::jsonb)", - expected.sourceRowJson(), - actual.sourceRowJson()) + + ", value -> 'current'))", + comparison.getValue().toString()) .get(0, Boolean.class)); if (!sameValues) { throw conflict("Current source row differs from its exact original bootstrap cohort entry"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java index feebecb948..c565101ee0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java @@ -13,6 +13,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; @@ -27,9 +28,12 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.ExecuteContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.PostgreSQLContainer; @@ -693,7 +697,7 @@ void frozenPlanPreservesNativeSourceValuesAcrossSessionRenderings() { TestSchema testSchema = newTestSchema("gs_build_native_"); try { var captureSchema = sessionSchema(testSchema, "UTC", captureFormat); - var fixture = pendingFixture(captureSchema); + var fixture = pendingFixture(captureSchema, 24); var prepareSchema = sessionSchema( testSchema, "Pacific/Auckland", captureFormat.equals("hex") ? "escape" : "hex"); @@ -724,16 +728,41 @@ void frozenPlanPreservesNativeSourceValuesAcrossSessionRenderings() { rowImagesWithXmin( testSchema.dsl(), "game_session_canonical_issuer_partition_build_member_work"); var readSchema = sessionSchema(testSchema, "America/New_York", captureFormat); + AtomicInteger readQueries = new AtomicInteger(); + var measuredConfiguration = readSchema.dsl().configuration().derive(); + measuredConfiguration.set( + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeStart(ExecuteContext context) { + readQueries.incrementAndGet(); + } + })); + DSLContext measuredReader = DSL.using(measuredConfiguration); var readPlan = - readSchema - .dsl() - .transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readPreparedPlanInTransaction( - transaction, fixture.intent().operationId(), fixture.requestId()); - }); + measuredReader.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, fixture.intent().operationId(), fixture.requestId()); + }); + // Count all actual SQL executions, not query strings: even the complete owner read + // must use fewer round trips than this cohort has rows. + assertThat(plan.cohortRows().size()).isGreaterThan(24); + assertThat(readQueries.get()).isPositive().isLessThan(plan.cohortRows().size()); + readQueries.set(0); + var member = + measuredReader.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedMemberWorkInTransaction( + transaction, fixture.intent().operationId(), fixture.requestId(), 0); + }); + assertThat(member.work().memberOperationId()) + .isEqualTo(plan.memberWorks().get(0).memberOperationId()); + assertThat(readQueries.get()).isPositive().isLessThan(plan.cohortRows().size()); assertThat(readPlan.buildOperationId()).isEqualTo(plan.buildOperationId()); assertThat(readPlan.planDigest()).isEqualTo(plan.planDigest()); assertThat(readPlan.cohortRows()) @@ -1747,9 +1776,28 @@ private static CanonicalGameplayIssuerPartitionBuildPlan prepareAtGate( } private static Fixture pendingFixture(TestSchema testSchema) { + return pendingFixture(testSchema, 0); + } + + private static Fixture pendingFixture(TestSchema testSchema, int extraReservations) { establishActualLegacyDisposition(testSchema.dsl()); var prepared = prepareActualBinding(new CanonicalGameplayBindingInventoryRepository(testSchema.dsl())); + for (int index = 0; index < extraReservations; index++) { + insertReservationOnly( + testSchema.dsl(), + prepared.candidate(), + prepared.inventoryRevision(), + UUID.randomUUID(), + BigInteger.valueOf(17), + BigInteger.valueOf(19), + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + false, + "RESERVED", + UUID.randomUUID()); + } UUID requestId = UUID.randomUUID(); var intent = new CanonicalGameplayIssuerLayoutBootstrapRepository(testSchema.dsl()) diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index f8f8d607f3..4807d5abd7 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -2572,58 +2572,15 @@ private static void exerciseCoupledCanonicalInitialAdmission( assertThat(accountRowAfterAbortedOwnerBeforeSettlement) .isEqualTo(accountRowBeforeSourceWrite); - try (var accountTerminalRead = - new GrpcAccountInitialAdmissionSettlementReadClient( - gsEndpoints, pki.client("account-service"), factory, NAMESPACE)) { - accountTerminalRead.init(); - var accountOwnerRead = - accountTerminalRead.read( - new AccountInitialAdmissionSettlementReadInput( - UUID.randomUUID(), accountProtection)); - assertThat(accountOwnerRead.terminal()).isEqualTo(abortedWorldTerminal); - assertThat(accountOwnerRead.terminal().outcome()) - .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); - var accountSettlementOwner = - new AccountStartSessionAdmissionProtectionSettlementService( - new AccountStartSessionAdmissionProtectionRepository(issuer.sourceDsl()), - accountTerminalRead, - accountManager(issuer.sourceDsl()), - NAMESPACE); - var accountSettlement = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, gameSessionPeer) - .call( - () -> - accountSettlementOwner.settle( - accountProtection.accountProtectionId(), - accountProtection.accountProtectionFence())); - var accountSettlementReplay = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, gameSessionPeer) - .call( - () -> - accountSettlementOwner.settle( - accountProtection.accountProtectionId(), - accountProtection.accountProtectionFence())); - assertThat(accountSettlement.protection().canonicalBytes()) - .containsExactly(accountProtection.canonicalBytes()); - assertThat(accountSettlement.terminal()).isEqualTo(abortedWorldTerminal); - assertThat(accountSettlementReplay.canonicalBytes()) - .containsExactly(accountSettlement.canonicalBytes()); - var storedSettlement = - issuer - .sourceDsl() - .fetchSingle( - "SELECT outcome,terminal_bytes,terminal_digest " - + "FROM account_start_session_admission_protection_settlements " - + "WHERE protection_id=?", - accountProtection.accountProtectionId()); - assertThat(storedSettlement.get("outcome", String.class)).isEqualTo("ABORTED"); - assertThat(storedSettlement.get("terminal_bytes", byte[].class)) - .containsExactly(accountSettlement.canonicalBytes()); - assertThat(storedSettlement.get("terminal_digest", String.class)) - .isEqualTo(accountSettlement.digest()); - } + assertAccountAdmissionProtectionSettled( + issuer.sourceDsl(), + gsEndpoints, + pki, + factory, + gameSessionPeer, + accountProtection, + abortedWorldTerminal, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); var releasedAccount = Objects.requireNonNull( @@ -2778,82 +2735,101 @@ private static void exerciseCoupledCanonicalInitialAdmission( .containsExactly( GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(worldTerminal)); - try (var accountTerminalRead = - new GrpcAccountInitialAdmissionSettlementReadClient( - gsEndpoints, pki.client("account-service"), factory, NAMESPACE)) { - accountTerminalRead.init(); - var accountOwnerRead = - accountTerminalRead.read( - new AccountInitialAdmissionSettlementReadInput( - UUID.randomUUID(), accountProtection)); - assertThat(accountOwnerRead.terminal()).isEqualTo(worldTerminal); - var accountSettlementOwner = - new AccountStartSessionAdmissionProtectionSettlementService( - new AccountStartSessionAdmissionProtectionRepository(issuer.sourceDsl()), - accountTerminalRead, - accountManager(issuer.sourceDsl()), - NAMESPACE); - var accountSettlement = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, gameSessionPeer) - .call( - () -> - accountSettlementOwner.settle( - accountProtection.accountProtectionId(), - accountProtection.accountProtectionFence())); - assertThat(accountSettlement.protection().canonicalBytes()) - .containsExactly(accountProtection.canonicalBytes()); - assertThat(accountSettlement.terminal()).isEqualTo(worldTerminal); - var accountSettlementReplay = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, gameSessionPeer) - .call( - () -> - accountSettlementOwner.settle( - accountProtection.accountProtectionId(), - accountProtection.accountProtectionFence())); - assertThat(accountSettlementReplay.canonicalBytes()) - .containsExactly(accountSettlement.canonicalBytes()); - var storedSettlement = - issuer - .sourceDsl() - .fetchSingle( - "SELECT outcome,terminal_bytes,terminal_digest " - + "FROM account_start_session_admission_protection_settlements " - + "WHERE protection_id=?", - accountProtection.accountProtectionId()); - assertThat(storedSettlement.get("outcome", String.class)).isEqualTo("COMMITTED"); - assertThat(storedSettlement.get("terminal_bytes", byte[].class)) - .containsExactly(accountSettlement.canonicalBytes()); - assertThat(storedSettlement.get("terminal_digest", String.class)) - .isEqualTo(accountSettlement.digest()); - - String settledAccountPassword = accountPasswordBeforeSourceWrite + "-settled"; - var releasedAccount = - Objects.requireNonNull( - new TransactionTemplate(accountManager(issuer.sourceDsl())) - .execute( - ignored -> - updateAccountPasswordThroughOwner( - issuer.sourceDsl(), accountUuid, settledAccountPassword)), - "Settled Account owner update readback required"); - assertThat(releasedAccount.getAccountUuid()).isEqualTo(accountUuid); - String accountPasswordAfterSettlement = - issuer - .sourceDsl() - .fetchSingle("SELECT password_hash FROM accounts WHERE account_uuid=?", accountUuid) - .get("password_hash", String.class); - assertThat(accountPasswordAfterSettlement).isEqualTo(settledAccountPassword); - assertThat(accountPasswordAfterSettlement).isNotEqualTo(accountPasswordBeforeSourceWrite); - String accountRowAfterSettlement = accountRowSnapshot(issuer.sourceDsl(), accountUuid); - assertThat(accountRowAfterSettlement).isNotEqualTo(accountRowBeforeSourceWrite); - } + assertAccountAdmissionProtectionSettled( + issuer.sourceDsl(), + gsEndpoints, + pki, + factory, + gameSessionPeer, + accountProtection, + worldTerminal, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + + String settledAccountPassword = accountPasswordBeforeSourceWrite + "-settled"; + var releasedAccount = + Objects.requireNonNull( + new TransactionTemplate(accountManager(issuer.sourceDsl())) + .execute( + ignored -> + updateAccountPasswordThroughOwner( + issuer.sourceDsl(), accountUuid, settledAccountPassword)), + "Settled Account owner update readback required"); + assertThat(releasedAccount.getAccountUuid()).isEqualTo(accountUuid); + String accountPasswordAfterSettlement = + issuer + .sourceDsl() + .fetchSingle("SELECT password_hash FROM accounts WHERE account_uuid=?", accountUuid) + .get("password_hash", String.class); + assertThat(accountPasswordAfterSettlement).isEqualTo(settledAccountPassword); + assertThat(accountPasswordAfterSettlement).isNotEqualTo(accountPasswordBeforeSourceWrite); + String accountRowAfterSettlement = accountRowSnapshot(issuer.sourceDsl(), accountUuid); + assertThat(accountRowAfterSettlement).isNotEqualTo(accountRowBeforeSourceWrite); var finalWorldState = worldHoldOwner.readState(identity, lifecycleRequest).orElseThrow(); assertThat(finalWorldState.holdStatus().name()).isEqualTo("COMMITTED"); } } + private static void assertAccountAdmissionProtectionSettled( + DSLContext accountSql, + ServiceEndpointsProperties gsEndpoints, + WorldOriginalStartSessionPreparationProofPki pki, + GrpcChannelFactory factory, + GrpcPeerIdentity gameSessionPeer, + AccountStartSessionAdmissionProtectionEvidence accountProtection, + GameSessionCanonicalInitialAdmissionOwnerProof expectedTerminal, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome expectedOutcome) + throws Exception { + try (var accountTerminalRead = + new GrpcAccountInitialAdmissionSettlementReadClient( + gsEndpoints, pki.client("account-service"), factory, NAMESPACE)) { + accountTerminalRead.init(); + var accountOwnerRead = + accountTerminalRead.read( + new AccountInitialAdmissionSettlementReadInput(UUID.randomUUID(), accountProtection)); + assertThat(accountOwnerRead.terminal()).isEqualTo(expectedTerminal); + assertThat(accountOwnerRead.terminal().outcome()).isEqualTo(expectedOutcome); + var accountSettlementOwner = + new AccountStartSessionAdmissionProtectionSettlementService( + new AccountStartSessionAdmissionProtectionRepository(accountSql), + accountTerminalRead, + accountManager(accountSql), + NAMESPACE); + var accountSettlement = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, gameSessionPeer) + .call( + () -> + accountSettlementOwner.settle( + accountProtection.accountProtectionId(), + accountProtection.accountProtectionFence())); + assertThat(accountSettlement.protection().canonicalBytes()) + .containsExactly(accountProtection.canonicalBytes()); + assertThat(accountSettlement.terminal()).isEqualTo(expectedTerminal); + var accountSettlementReplay = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, gameSessionPeer) + .call( + () -> + accountSettlementOwner.settle( + accountProtection.accountProtectionId(), + accountProtection.accountProtectionFence())); + assertThat(accountSettlementReplay.canonicalBytes()) + .containsExactly(accountSettlement.canonicalBytes()); + var storedSettlement = + accountSql.fetchSingle( + "SELECT outcome,terminal_bytes,terminal_digest " + + "FROM account_start_session_admission_protection_settlements " + + "WHERE protection_id=?", + accountProtection.accountProtectionId()); + assertThat(storedSettlement.get("outcome", String.class)).isEqualTo(expectedOutcome.name()); + assertThat(storedSettlement.get("terminal_bytes", byte[].class)) + .containsExactly(accountSettlement.canonicalBytes()); + assertThat(storedSettlement.get("terminal_digest", String.class)) + .isEqualTo(accountSettlement.digest()); + } + } + private static WorldCanonicalInstancePreparation.Input preparationInputs( Database world, Database gs, From fe00ee8c4752a9f50f8d2c77592fdb6cba7c2620 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:42:07 +1300 Subject: [PATCH 9/9] fix(account): retain retryable settlement reader failures --- ...nAdmissionProtectionSettlementService.java | 10 ++++++- ...SessionAdmissionProtectionServiceTest.java | 30 ++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java index 689fc4549a..532b086185 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java @@ -95,11 +95,19 @@ public AccountStartSessionAdmissionProtectionSettlementEvidence settle( observed = gameSessionClient.read(readInput); } catch (StatusRuntimeException failure) { throw dependencyFailure(failure); - } catch (IllegalArgumentException | IllegalStateException malformed) { + } catch (IllegalArgumentException malformed) { throw Status.FAILED_PRECONDITION .withDescription("Game Session admission terminal response is malformed") .withCause(malformed) .asRuntimeException(); + } catch (IllegalStateException failure) { + Status status = + failure.getCause() instanceof IllegalArgumentException + ? Status.FAILED_PRECONDITION.withDescription( + "Game Session admission terminal response is malformed") + : Status.UNAVAILABLE.withDescription( + "Game Session admission terminal reader is unavailable"); + throw status.withCause(failure).asRuntimeException(); } requireNoAmbientTransaction(); requireExactOwnerRead(readInput, observed); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java index ca98aea3e3..60027ab521 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java @@ -358,7 +358,9 @@ void settlementRejectsChangedOwnerReadBeforeMutationAndClassifiesDependencyFailu for (RuntimeException malformed : List.of( new IllegalArgumentException("malformed direct owner read"), - new IllegalStateException("malformed decoded owner read"))) { + new IllegalStateException( + "malformed decoded owner read", + new IllegalArgumentException("invalid wire response")))) { var invalid = new SettlementHarness(); when(invalid.repository.findHistoricalExact( fixture.protection().accountProtectionId(), @@ -383,6 +385,32 @@ void settlementRejectsChangedOwnerReadBeforeMutationAndClassifiesDependencyFailu verify(invalid.repository, never()).settleExact(any()); } + var unavailable = new SettlementHarness(); + when(unavailable.repository.findHistoricalExact( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence())) + .thenReturn(Optional.of(new StoredProtection(fixture.protection(), 89L))); + when(unavailable.repository.findSettlementExact( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence())) + .thenReturn(Optional.empty()); + var localFailure = new IllegalStateException("closed local dependency reader"); + doThrow(localFailure).when(unavailable.client).read(any()); + var localStatusFailure = + statusFailure( + () -> + withGameSessionPeer( + () -> + unavailable.service.settle( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence()))); + assertThat(Status.fromThrowable(localStatusFailure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(localStatusFailure).getDescription()) + .isEqualTo("Game Session admission terminal reader is unavailable"); + assertThat(localStatusFailure.getCause()).isSameAs(localFailure); + verify(unavailable.repository, never()).settleExact(any()); + for (Status.Code code : Status.Code.values()) { var dependency = new SettlementHarness(); when(dependency.repository.findHistoricalExact(