From 940fa188a94723dab0662a2f3e2833fcc4ed9964 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:44:07 +1300 Subject: [PATCH 01/36] Prepare authenticated initial-room region observation and lifecycle revalidation --- .../game-session-service/api-contracts.md | 2 + .../world-management-service/api-contracts.md | 4 + .../runtime-and-data.md | 2 + .../world-runtime-and-movement.md | 2 + .../canonical_initial_player_location.proto | 28 ++ .../CanonicalInitialPlayerLocationClient.java | 114 ++++++ ...alInitialPlayerLocationRegionResolver.java | 89 +++++ ...alInitialPlayerLocationClientMtlsTest.java | 64 +++- ...onicalInitialPlayerLocationClientTest.java | 174 ++++++++- ...RegionBootstrapAssignmentResolverTest.java | 217 +++++++++++ ...nonicalInitialPlayerLocationGrpcCodec.java | 94 ++++- ...nicalInitialPlayerLocationGrpcService.java | 68 ++++ ...lInitialPlayerLocationPeerInterceptor.java | 8 +- ...CanonicalInitialPlayerLocationService.java | 20 ++ ...onicalInitialPlayerLocationRepository.java | 337 ++++++++++++++++++ ...tialPlayerLocationGrpcServiceMtlsTest.java | 18 +- ...tionRepositoryPostgresIntegrationTest.java | 12 + ...calInitialPlayerLocationGrpcCodecTest.java | 73 ++++ ...nicalInitialPlayerLocationServiceTest.java | 49 +++ 19 files changed, 1367 insertions(+), 8 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index fbbc34d7b0..87a5f64a11 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -10,6 +10,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat The local issuer-index model, codec and key helper carry the selected physical member schema v2; decoding validates shape, not current source, anchor, capacity or incarnation authority. This storage consequence adds no public or internal RPC. Retained physical v1 artifacts are unqualified and have no fallback, and Account acknowledgement schema v2 remains account-only. The separate owner-qualified issuer acknowledgement and final guarded controller CAS remain required before manual NEW consumers can admit; see the [issuer-index owner](../../system-architecture-redis.md#issuer-active-binding-index) and [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). +The manual initial-location client and `CanonicalInitialPlayerLocationRegionResolver` consume World’s [initial-room region consequence](../world-management-service/api-contracts.md#canonical-initial-player-location). The resolver compares that observation with a separate authenticated lifecycle read before returning a privately constructed resolved value. No default registration or player-binding gate composition is supplied by this component; its current proof and missing genuine placement prerequisites remain in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-initial-player-location-preparation). + The local [canonical NEW admission lease contract](../../system-architecture-session-behavior.md#canonical-public-production-new-admission) now has generated transport carriers and a manually composed `AccountGameplayAdmissionLeaseClient` for Account’s four purpose-specific methods. Its narrow candidate uses the exact Account issuer string at the original string wire tag; shape validation supplies no issuer authority. The [Account API](../account-service/api-contracts.md#canonical-public-production-new-admission-lease-source) owns caller authentication, acquisition, original finalization and read/abort recovery. The prepared Account-only reverse-read proto and closed codec preserve separate current published-target and exact provisional-decision purposes, with their finite transport bounds; this prerequisite does not supply their genuine Game Session owner composition or register a source receiver. The Account receiver’s focused physical-COMMIT and durable-ACK proof uses explicitly controlled reverse responses. These local components do not acknowledge issuer/region obligations or admit a binding; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records component proof and remaining composition. The initial-LOGIN PostgreSQL journal and exact original-attempt cleanup owner are unregistered source preparation, with no new Game Session endpoint or legacy LOGIN handler composition. Their unregistered Account client authenticates the exact same-namespace Account mTLS peer and validates the explicit initial delegation profile, signature, original request/context, token hash, claim/projection equality and bounded nonsecret evidence. Its one transient invocation permits at most one transport reload/retry under the unchanged deadline. It also uses the original-request retirement contract. The result retains compact private-token bytes only in process; validation supplies neither current registry authority nor live context installation. Journal snapshots and typed closure fixtures supply no authenticated caller custody or physical Redis closure; the separate Redis adapter remains outside runtime composition. See the [canonical coordination contract](../../system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination) and [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index d4e4693b0c..774a5b3961 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -309,6 +309,10 @@ Remote Entity and Game Session reads finish outside World SQL. World then serial The narrow read returns retained initial-placement evidence, not current occupancy or a lease. The response binds the placement, Account, actor and assignment identities; `APPLIED` includes the retained tenant/version/template and private runtime room ID, while `CONFLICT` carries its retained conflict code. World request/result digests identify its sealed owner bytes; clients validate their representation and echoed identities rather than recomputing them from incomplete network selectors. The manual reader also checks the exact immutable Entity receipt and remains unavailable when that owner cannot be read; this does not turn historical assignment evidence into fresh eligibility. Game Session must separately revalidate its current target and admission fences before consuming placement for `PLAY`. +`ReadInitialPlayerLocationRegion` is a separate read on the same service, restricted to that same Game Session workload and exact original placement selectors. It returns the retained `APPLIED` placement result together with a fresh initial-room region consequence. World uses one read-only repeatable-read snapshot to require that the actor remains in its original initial room and that the retained placement, current location and current `ACTIVE` lifecycle share the exact world, tenant, version, epoch, capture and preparation binding. The ROOM mapping must join the actual room, zone and region and the corresponding REGION mapping under that same capture and graph. The canonical region UUID comes from that runtime mapping; a template ID, first region or caller-selected operational region is not a substitute. Missing, moved, mismatched or unsupported evidence refuses the read. + +The closed region response retains the original placement bytes/digests and echoes the expected target, canonical and operational region UUIDs, private World/room keys and bounded lifecycle consequence. The request is bounded to 16 KiB, the response to 8 KiB, and its canonical lifecycle request bytes to 4 KiB. This fresh consequence neither changes the immutable placement result nor provides general current occupancy. Game Session independently rereads authenticated World lifecycle evidence and compares the exact request, state, epoch, row version, capture, graph, preparation digest and operational assignment before using the region; its binding gate must still revalidate the applicable current admission fences. + This preparation reuses existing owner schemas and terminal plumbing. It does not register those owners, release protections, create an `ACTIVE` fixture, seed SQL or bypass the separately held activation chain. Positive placement qualification still requires genuine authorized `ACTIVE`, hold and pointer prerequisites; a room marker or controlled transport response does not prove that chain or causal `LOOK`. ## Run-Owned World Launch Evidence diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 11cc5b95ce..49b9898de9 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -67,6 +67,8 @@ World templates follow the same stability rules as entity templates: World Management is the authoritative owner of character and NPC location for each game instance. The schema includes guarded `character_location` and immutable initial-location operation storage from V1019. The manually composed [initial-placement boundary](./api-contracts.md#canonical-initial-player-location) prepares owner writes and exact retained readback without changing those migrations. Registered execution and activation remain unavailable; the registered runtime does not write this family. Current proof and activation-dependent gaps belong to the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-initial-player-location-preparation). Live `room_instance` topology and a Game Session room-binding seam do not establish authoritative occupancy. +The region consequence joins the retained initial-placement operation and `character_location` to current ROOM, zone and REGION mappings in one read-only repeatable-read transaction. It requires the original room to remain current and exact lifecycle/capture/graph provenance, and performs no placement or topology write. Its public comparison and transport contract belongs to the [initial-location API](./api-contracts.md#canonical-initial-player-location). + - Only World-owned operations may write location as part of movement, instancing and world creation invoked by Game Session. The initial-placement storage preserves its exact admission hold and APPLIED operation binding. V1042.10 rejects DELETE and TRUNCATE on `character_location`, preserving the existing V1019 operation-history guard; it grants no placement, movement or cleanup authority. `npc_location` and generalized occupancy execution remain unimplemented. - Other services, including Entity Management and Game Session, treat World location storage as read-only and rely on World Management gRPC APIs or cached projections. Current room reads and the Game Session binding do not establish location authority. - Target rule: derived caches or denormalized views of location must be refreshed from World Management rather than persisting independent authoritative location fields. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 1fa4afa930..d6faf337b7 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical initial player location preparation +The selected initial-room region read is now local source preparation in the existing World service, with the matching Game Session client and independent lifecycle resolver. It preserves immutable placement storage/results, checks the actual room-to-zone-to-region mappings and current initial room, and keeps every owner manually composed and unregistered. The production query uses the current `room_instance_row_id` column. R584 freshly passes 44 focused unit, controlled mTLS and PostgreSQL cases with zero failures, errors or skips; the native case executes `EXPLAIN` on the exact production query after actual migrations and verifies refusal. That is schema/refusal proof, not a positive authorized region selection. Its aggregate failed solely on the Game Session immutable-protobuf getter exposure warning. R587 applies a narrow suppression justified by generated protobuf immutability and passes the affected enabled main Checkstyle, SpotBugs and formatting checks; it does not repeat or relabel the 44 passing R584 cases. Independent inspection confirms both exact R584 PostgreSQL/Ryuk containers absent. Positive multi-region placement/replay still requires genuine authorized `ACTIVE`, hold, pointer and Entity receipt sources, and the player-binding gate consumer remains unfinished. No original end-to-end Gate testing or admission completion is claimed. + The [initial-placement API](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-player-location) is prepared as an unregistered owner service, transport and immediate Game Session client over the existing V1019 storage boundary. It receives the necessary existing canonical hold reader, Game Session terminal client and Common response decoder; their donor source remains preserved. The distinct World-only Entity receipt read supplies persisted assignment provenance without widening the Game Session roster allowlists. The component checkpoint `eee4a18057411d74ed3d25ddf19f44c7a78391e0` passes 65 fresh focused cases across R337, R338 and R340: 53 unit cases, ten controlled physical TLS cases, one actual Entity assignment/receipt-to-current-PostgreSQL case and one current-PostgreSQL World refusal case. R336–R339 retain their failed aggregate and separately passing component attribution. Affected enabled static analysis and formatting checks pass. diff --git a/protos/world-management/v1/canonical_initial_player_location.proto b/protos/world-management/v1/canonical_initial_player_location.proto index dc72c86bf1..f3d7e83459 100644 --- a/protos/world-management/v1/canonical_initial_player_location.proto +++ b/protos/world-management/v1/canonical_initial_player_location.proto @@ -13,6 +13,8 @@ service CanonicalInitialPlayerLocationService { returns (CanonicalInitialPlayerLocationResponse); rpc ReadInitialPlayerLocation(CanonicalInitialPlayerLocationRequest) returns (CanonicalInitialPlayerLocationResponse); + rpc ReadInitialPlayerLocationRegion(CanonicalInitialPlayerLocationRequest) + returns (CanonicalInitialPlayerLocationRegionResponse); } // Closed selectors for one immutable Entity assignment, one World initial-admission hold, and @@ -63,3 +65,29 @@ message CanonicalInitialPlayerLocationRoom { string canonical_version_uuid = 2; string room_template_uuid = 3; } + +// Fresh, read-only initial-location consequence. This remains distinct from the immutable +// placement result above and does not establish current occupancy beyond confirming that the +// actor is still in its original initial room. +message CanonicalInitialPlayerLocationRegionResponse { + uint32 schema_version = 1; + CanonicalInitialPlayerLocationResponse placement_result = 2; + entity_management.v1.PreseededActorAssignmentExpectedTarget expected_target = 3; + string canonical_region_instance_uuid = 4; + string operational_region_uuid = 5; + int64 private_world_instance_key = 6; + int64 observed_runtime_room_key = 7; + CanonicalInitialPlayerLocationLifecycleConsequence lifecycle = 8; +} + +// Bounded closed subset of the current lifecycle read. It omits the graph, launch binding, and +// region assignment map; consumers can re-read the authenticated owner and compare exact values. +message CanonicalInitialPlayerLocationLifecycleConsequence { + bytes canonical_request_bytes = 1; + string lifecycle_status = 2; + int64 lifecycle_epoch = 3; + int64 row_version = 4; + string capture_uuid = 5; + string graph_sha256 = 6; + string preparation_input_digest = 7; +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java index 016bd68386..ad468a6133 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java @@ -2,7 +2,9 @@ import io.grpc.ManagedChannel; import java.io.IOException; +import java.nio.charset.StandardCharsets; 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; @@ -14,7 +16,9 @@ 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.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationServiceGrpc; @@ -26,6 +30,9 @@ public final class CanonicalInitialPlayerLocationClient .CanonicalInitialPlayerLocationServiceBlockingStub> { private static final int SCHEMA_VERSION = 1; private static final long CALL_DEADLINE_SECONDS = 20L; + private static final int MAX_REGION_REQUEST_BYTES = 16 * 1024; + private static final int MAX_REGION_RESPONSE_BYTES = 8 * 1024; + private static final int MAX_LIFECYCLE_REQUEST_BYTES = 4 * 1024; private static final int MAX_REQUEST_ID_LENGTH = 128; private static final int MAX_RELEASE_REF_LENGTH = 128; private static final Pattern RAW_SHA256 = Pattern.compile("[0-9a-f]{64}"); @@ -92,6 +99,26 @@ public CanonicalInitialPlayerLocationResponse readInitialPlayerLocation( return invoke(request, false); } + /** Reads the fresh current-room region consequence for an exact retained APPLIED placement. */ + public CanonicalInitialPlayerLocationRegionResponse readInitialPlayerLocationRegion( + CanonicalInitialPlayerLocationRequest request) { + requireNoAmbientSql("Initial player location region RPC requires no ambient SQL"); + requireRequest(request); + if (request.getSerializedSize() > MAX_REGION_REQUEST_BYTES) { + throw new IllegalArgumentException( + "Initial player location region request exceeds its bound"); + } + var stub = + requireInitializedStub("World initial player location client is unavailable") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withMaxInboundMessageSize(MAX_REGION_RESPONSE_BYTES) + .withMaxOutboundMessageSize(MAX_REGION_REQUEST_BYTES); + CanonicalInitialPlayerLocationRegionResponse response = + stub.readInitialPlayerLocationRegion(request); + requireRegionResponse(request, response); + return response; + } + private CanonicalInitialPlayerLocationResponse invoke( CanonicalInitialPlayerLocationRequest request, boolean place) { requireNoAmbientSql("Initial player location RPC requires no ambient SQL"); @@ -224,6 +251,86 @@ private static void requireResponse( } } + private void requireRegionResponse( + CanonicalInitialPlayerLocationRequest request, + CanonicalInitialPlayerLocationRegionResponse response) { + if (response == null + || response.getSerializedSize() > MAX_REGION_RESPONSE_BYTES + || response.getSchemaVersion() != SCHEMA_VERSION + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasPlacementResult() + || !response.hasExpectedTarget() + || !response.hasLifecycle() + || !request.getExpectedTarget().equals(response.getExpectedTarget()) + || !response.getExpectedTarget().getUnknownFields().asMap().isEmpty()) { + throw invalidResponse("Region response is not a bounded, closed echo of the selected target"); + } + CanonicalInitialPlayerLocationResponse placement = response.getPlacementResult(); + requireResponse(request, placement); + if (placement.getOutcome() + != net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome + .CANONICAL_INITIAL_PLAYER_LOCATION_OUTCOME_APPLIED) { + throw invalidResponse("Region resolution requires the exact APPLIED placement result"); + } + requireResponseUuid( + response.getCanonicalRegionInstanceUuid(), "canonical_region_instance_uuid"); + requireResponseUuid(response.getOperationalRegionUuid(), "operational_region_uuid"); + if (response.getCanonicalRegionInstanceUuid().equals(response.getOperationalRegionUuid()) + || response.getPrivateWorldInstanceKey() <= 0L + || response.getObservedRuntimeRoomKey() <= 0L) { + throw invalidResponse("Region response has an invalid World or runtime room identity"); + } + requirePositivePrivateRuntimeRoomKey(placement.getPrivateRuntimeRoomKey()); + if (Long.parseLong(placement.getPrivateRuntimeRoomKey()) + != response.getObservedRuntimeRoomKey()) { + throw invalidResponse("Region response changed the retained initial runtime room"); + } + + var lifecycle = response.getLifecycle(); + if (!lifecycle.getUnknownFields().asMap().isEmpty() + || lifecycle.getCanonicalRequestBytes().isEmpty() + || lifecycle.getCanonicalRequestBytes().size() > MAX_LIFECYCLE_REQUEST_BYTES + || !"ACTIVE".equals(lifecycle.getLifecycleStatus()) + || lifecycle.getLifecycleEpoch() != request.getActiveLifecycleEpoch() + || lifecycle.getRowVersion() < 0L) { + throw invalidResponse("Region lifecycle consequence is incomplete or stale"); + } + requireResponseUuid(lifecycle.getCaptureUuid(), "lifecycle.capture_uuid"); + if (lifecycle.getGraphSha256() == null + || !RAW_SHA256.matcher(lifecycle.getGraphSha256()).matches()) { + throw invalidResponse("lifecycle.graph_sha256 is not raw lowercase SHA-256"); + } + requireResponseDigest( + lifecycle.getPreparationInputDigest(), "lifecycle.preparation_input_digest"); + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest; + try { + lifecycleRequest = + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored( + lifecycle.getCanonicalRequestBytes().toByteArray()); + } catch (IllegalArgumentException invalid) { + throw invalidResponse( + "lifecycle.canonical_request_bytes is not a closed canonical request", invalid); + } + var target = request.getExpectedTarget(); + if (!lifecycleRequest.canonicalTenantId().toString().equals(target.getCanonicalTenantUuid()) + || !namespace.equals(lifecycleRequest.targetNamespace()) + || !lifecycleRequest.readRequestId().equals(lifecycleReadRequestId(request)) + || !lifecycleRequest.canonicalGameInstanceId().toString().equals(target.getGameInstanceId()) + || !lifecycleRequest + .playableStateNamespaceId() + .toString() + .equals(target.getPlayableStateNamespaceUuid()) + || !lifecycleRequest.playableStateScope().equals("SHARED") + || !lifecycleRequest.worldSlug().equals(target.getWorldSlug()) + || !lifecycleRequest + .canonicalVersionId() + .toString() + .equals(target.getCanonicalVersionUuid()) + || !lifecycleRequest.publicProduction()) { + throw invalidResponse("lifecycle request differs from the echoed canonical placement target"); + } + } + private static void requirePositivePrivateRuntimeRoomKey(String value) { if (value == null || !POSITIVE_PRIVATE_RUNTIME_ROOM_KEY.matcher(value).matches()) { throw invalidResponse("private_runtime_room_key must be a positive private room key"); @@ -307,6 +414,13 @@ private static void requireResponseUuid(String value, String field) { } } + private static UUID lifecycleReadRequestId(CanonicalInitialPlayerLocationRequest request) { + byte[] name = + ("firemud-world-initial-location-lifecycle-read/v1/" + request.getPlacementOperationUuid()) + .getBytes(StandardCharsets.US_ASCII); + return UUID.nameUUIDFromBytes(name); + } + private static IllegalStateException invalidResponse(String message) { return new IllegalStateException( "World initial player location response is invalid: " + message); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java new file mode 100644 index 0000000000..b779c2d7fb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClient; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; + +/** + * Joins World’s fresh initial-room region observation to an independent authenticated lifecycle + * owner read. The result is an initial-placement consequence only; it grants no admission or + * region-runtime ownership. + */ +public final class CanonicalInitialPlayerLocationRegionResolver { + private final CanonicalInitialPlayerLocationClient initialLocationClient; + private final CanonicalRegionBootstrapAssignmentResolver lifecycleResolver; + + public CanonicalInitialPlayerLocationRegionResolver( + CanonicalInitialPlayerLocationClient initialLocationClient, + CanonicalRegionBootstrapAssignmentResolver lifecycleResolver) { + this.initialLocationClient = + Objects.requireNonNull(initialLocationClient, "initialLocationClient"); + this.lifecycleResolver = Objects.requireNonNull(lifecycleResolver, "lifecycleResolver"); + } + + /** + * Reads the exact current initial-room consequence, then revalidates it through World lifecycle. + */ + public ResolvedRegion resolve(CanonicalInitialPlayerLocationRequest request) { + Objects.requireNonNull(request, "request"); + CanonicalInitialPlayerLocationRegionResponse observed = + initialLocationClient.readInitialPlayerLocationRegion(request); + var lifecycle = observed.getLifecycle(); + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest = + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored( + lifecycle.getCanonicalRequestBytes().toByteArray()); + UUID canonicalRegionId = UUID.fromString(observed.getCanonicalRegionInstanceUuid()); + CanonicalRegionBootstrapAssignmentResolver.Assignment current = + lifecycleResolver.resolve(lifecycleRequest, canonicalRegionId); + if (!request.getExpectedTarget().equals(observed.getExpectedTarget()) + || !lifecycleRequest.equals(current.request()) + || !lifecycle.getLifecycleStatus().equals(current.lifecycleStatus()) + || lifecycle.getLifecycleEpoch() != current.lifecycleEpoch() + || lifecycle.getRowVersion() != current.lifecycleRowVersion() + || !lifecycle.getCaptureUuid().equals(current.captureId().toString()) + || !lifecycle.getGraphSha256().equals(current.graphSha256()) + || !lifecycle.getPreparationInputDigest().equals(current.preparationInputDigest()) + || !observed.getOperationalRegionUuid().equals(current.operationalRegionId().toString())) { + throw new IllegalStateException( + "World initial-location region consequence changed during lifecycle revalidation"); + } + return new ResolvedRegion(observed, current); + } + + /** Immutable resolved observation; consumers must still revalidate at their binding gate. */ + public static final class ResolvedRegion { + private final CanonicalInitialPlayerLocationRegionResponse observation; + private final CanonicalRegionBootstrapAssignmentResolver.Assignment lifecycleAssignment; + + private ResolvedRegion( + CanonicalInitialPlayerLocationRegionResponse observation, + CanonicalRegionBootstrapAssignmentResolver.Assignment lifecycleAssignment) { + this.observation = Objects.requireNonNull(observation, "observation"); + this.lifecycleAssignment = Objects.requireNonNull(lifecycleAssignment, "lifecycleAssignment"); + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf messages are immutable; the validated observation cannot be changed by its consumer.") + public CanonicalInitialPlayerLocationRegionResponse observation() { + return observation; + } + + public CanonicalRegionBootstrapAssignmentResolver.Assignment lifecycleAssignment() { + return lifecycleAssignment; + } + + public UUID canonicalRegionInstanceId() { + return lifecycleAssignment.canonicalRegionId(); + } + + public UUID operationalRegionId() { + return lifecycleAssignment.operationalRegionId(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientMtlsTest.java index ef724600fd..4165860186 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientMtlsTest.java @@ -20,11 +20,14 @@ 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.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; import net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClient; import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationLifecycleConsequence; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRoom; @@ -105,6 +108,18 @@ public void placeInitialPlayer( observer.onNext(response); observer.onCompleted(); } + + @Override + public void readInitialPlayerLocationRegion( + CanonicalInitialPlayerLocationRequest request, + StreamObserver observer) { + handlerInvocations.incrementAndGet(); + observedRequest.set(request); + var peer = GrpcPeerIdentity.current(); + observedPeer.set(peer == null ? null : peer.uri()); + observer.onNext(regionResponse(request)); + observer.onCompleted(); + } }; Server server = server(identity, service); var endpoints = new ServiceEndpointsProperties(); @@ -118,7 +133,9 @@ public void placeInitialPlayer( client.init(); if (accepted) { assertThat(client.placeInitialPlayer(request)).isEqualTo(response); - assertThat(handlerInvocations).hasValue(1); + assertThat(client.readInitialPlayerLocationRegion(request)) + .isEqualTo(regionResponse(request)); + assertThat(handlerInvocations).hasValue(2); assertThat(observedRequest.get()).isEqualTo(request); assertThat(observedPeer.get()).isEqualTo(GAME_SESSION_PEER); } else { @@ -210,4 +227,49 @@ private static CanonicalInitialPlayerLocationResponse response( .setPrivateRuntimeRoomKey("9182") .build(); } + + private static CanonicalInitialPlayerLocationRegionResponse regionResponse( + CanonicalInitialPlayerLocationRequest request) { + var target = request.getExpectedTarget(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + java.util.UUID.nameUUIDFromBytes( + ("firemud-world-initial-location-lifecycle-read/v1/" + + request.getPlacementOperationUuid()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII)), + NAMESPACE, + java.util.UUID.fromString(target.getCanonicalTenantUuid()), + target.getWorldSlug(), + java.util.UUID.fromString(target.getGameInstanceId()), + java.util.UUID.fromString(target.getPlayableStateNamespaceUuid()), + "SHARED", + true, + "control-plane-request-12", + java.util.UUID.fromString(target.getCanonicalVersionUuid()), + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + var lifecycle = + CanonicalInitialPlayerLocationLifecycleConsequence.newBuilder() + .setCanonicalRequestBytes( + com.google.protobuf.ByteString.copyFrom(lifecycleRequest.canonicalBytes())) + .setLifecycleStatus("ACTIVE") + .setLifecycleEpoch(request.getActiveLifecycleEpoch()) + .setRowVersion(4L) + .setCaptureUuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc") + .setGraphSha256("4".repeat(64)) + .setPreparationInputDigest("sha256:" + "5".repeat(64)) + .build(); + return CanonicalInitialPlayerLocationRegionResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementResult(response(request)) + .setExpectedTarget(target) + .setCanonicalRegionInstanceUuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd") + .setOperationalRegionUuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee") + .setPrivateWorldInstanceKey(7L) + .setObservedRuntimeRoomKey(9182L) + .setLifecycle(lifecycle) + .build(); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java index 851f5a1226..2c7996e2ac 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java @@ -33,10 +33,13 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; import net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClient; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationLifecycleConsequence; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationServiceGrpc; @@ -92,17 +95,123 @@ void returnsOnlyCheckedAppliedAndConflictResponsesForBothMethods() throws Except var applied = appliedResponse(request); when(stub.placeInitialPlayer(request)).thenReturn(applied); when(stub.readInitialPlayerLocation(request)).thenReturn(applied); + var region = regionResponse(request); + when(stub.readInitialPlayerLocationRegion(request)).thenReturn(region); var client = clientWithStub(stub); assertThat(client.placeInitialPlayer(request)).isEqualTo(applied); assertThat(client.readInitialPlayerLocation(request)).isEqualTo(applied); - verify(stub, times(2)).withDeadlineAfter(20L, TimeUnit.SECONDS); + assertThat(client.readInitialPlayerLocationRegion(request)).isEqualTo(region); + verify(stub, times(3)).withDeadlineAfter(20L, TimeUnit.SECONDS); + verify(stub).withMaxInboundMessageSize(8 * 1024); + verify(stub).withMaxOutboundMessageSize(16 * 1024); var conflict = conflictResponse(request); when(stub.placeInitialPlayer(request)).thenReturn(conflict); assertThat(client.placeInitialPlayer(request)).isEqualTo(conflict); } + @Test + void rejectsRegionResultWithChangedPlacementTargetOrLifecycleFence() throws Exception { + var request = request(); + var stub = mockStub(); + var client = clientWithStub(stub); + + when(stub.readInitialPlayerLocationRegion(request)) + .thenReturn( + regionResponse(request).toBuilder() + .setExpectedTarget( + request.getExpectedTarget().toBuilder().setRealmSlug("other-realm")) + .build()); + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("echo of the selected target"); + + when(stub.readInitialPlayerLocationRegion(request)) + .thenReturn( + regionResponse(request).toBuilder() + .setLifecycle( + regionResponse(request).getLifecycle().toBuilder().setLifecycleEpoch(13L)) + .build()); + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("incomplete or stale"); + } + + @Test + void rejectsRegionResultAttributedToAnotherWorkloadNamespace() throws Exception { + var request = request(); + var stub = mockStub(); + when(stub.readInitialPlayerLocationRegion(request)) + .thenReturn(regionResponse(request, "other-workload-namespace")); + var client = clientWithStub(stub); + + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("canonical placement target"); + } + + @Test + void rejectsLifecycleReadRequestNotBoundToThePlacementOperation() throws Exception { + var request = request(); + var stub = mockStub(); + when(stub.readInitialPlayerLocationRegion(request)) + .thenReturn( + regionResponse( + request, + NAMESPACE, + java.util.UUID.fromString("99999999-9999-4999-8999-999999999999"))); + var client = clientWithStub(stub); + + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("canonical placement target"); + } + + @Test + void rejectsRegionResultWithSubstitutedActorRoomKeyOrMalformedPlacementDigest() throws Exception { + var request = request(); + var stub = mockStub(); + var client = clientWithStub(stub); + + when(stub.readInitialPlayerLocationRegion(request)) + .thenReturn( + regionResponse(request).toBuilder() + .setPlacementResult( + appliedResponse(request).toBuilder() + .setCharacterUuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) + .build()); + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("operation, scope, or assignment"); + + when(stub.readInitialPlayerLocationRegion(request)) + .thenReturn( + regionResponse(request).toBuilder() + .setPlacementResult( + appliedResponse(request).toBuilder().setResultDigest("bad-digest")) + .build()); + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("result_digest is not prefixed"); + + when(stub.readInitialPlayerLocationRegion(request)) + .thenReturn( + regionResponse(request).toBuilder() + .setPlacementResult( + appliedResponse(request).toBuilder().setRequestDigest("bad-digest")) + .build()); + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request_digest is not prefixed"); + + when(stub.readInitialPlayerLocationRegion(request)) + .thenReturn(regionResponse(request).toBuilder().setObservedRuntimeRoomKey(9183L).build()); + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed the retained initial runtime room"); + } + @Test void rejectsOpenMalformedOrUnsupportedRequestsBeforeEitherRpc() throws Exception { var request = request(); @@ -429,6 +538,8 @@ private CanonicalInitialPlayerLocationClient newClient() { CanonicalInitialPlayerLocationServiceGrpc .CanonicalInitialPlayerLocationServiceBlockingStub.class); when(stub.withDeadlineAfter(20L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withMaxInboundMessageSize(8 * 1024)).thenReturn(stub); + when(stub.withMaxOutboundMessageSize(16 * 1024)).thenReturn(stub); return stub; } @@ -504,4 +615,65 @@ private static CanonicalInitialPlayerLocationResponse conflictResponse( .setConflictCode("CHARACTER_ALREADY_PLACED") .build(); } + + private static CanonicalInitialPlayerLocationRegionResponse regionResponse( + CanonicalInitialPlayerLocationRequest request) { + return regionResponse(request, NAMESPACE, lifecycleReadRequestId(request)); + } + + private static CanonicalInitialPlayerLocationRegionResponse regionResponse( + CanonicalInitialPlayerLocationRequest request, String lifecycleTargetNamespace) { + return regionResponse(request, lifecycleTargetNamespace, lifecycleReadRequestId(request)); + } + + private static CanonicalInitialPlayerLocationRegionResponse regionResponse( + CanonicalInitialPlayerLocationRequest request, + String lifecycleTargetNamespace, + java.util.UUID lifecycleReadRequestId) { + var target = request.getExpectedTarget(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + lifecycleReadRequestId, + lifecycleTargetNamespace, + java.util.UUID.fromString(target.getCanonicalTenantUuid()), + target.getWorldSlug(), + java.util.UUID.fromString(target.getGameInstanceId()), + java.util.UUID.fromString(target.getPlayableStateNamespaceUuid()), + "SHARED", + true, + "control-plane-request-12", + java.util.UUID.fromString(target.getCanonicalVersionUuid()), + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + var lifecycle = + CanonicalInitialPlayerLocationLifecycleConsequence.newBuilder() + .setCanonicalRequestBytes( + com.google.protobuf.ByteString.copyFrom(lifecycleRequest.canonicalBytes())) + .setLifecycleStatus("ACTIVE") + .setLifecycleEpoch(request.getActiveLifecycleEpoch()) + .setRowVersion(4L) + .setCaptureUuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb") + .setGraphSha256("4".repeat(64)) + .setPreparationInputDigest("sha256:" + "5".repeat(64)) + .build(); + return CanonicalInitialPlayerLocationRegionResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementResult(appliedResponse(request)) + .setExpectedTarget(target) + .setCanonicalRegionInstanceUuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc") + .setOperationalRegionUuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd") + .setPrivateWorldInstanceKey(6L) + .setObservedRuntimeRoomKey(9182L) + .setLifecycle(lifecycle) + .build(); + } + + private static java.util.UUID lifecycleReadRequestId( + CanonicalInitialPlayerLocationRequest request) { + return java.util.UUID.nameUUIDFromBytes( + ("firemud-world-initial-location-lifecycle-read/v1/" + request.getPlacementOperationUuid()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java index f94a521971..01e7f94c6e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java @@ -13,6 +13,13 @@ import net.firedevops.firemud.common.testing.AuthoringFixtures; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClient; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,6 +33,7 @@ class CanonicalRegionBootstrapAssignmentResolverTest { private CanonicalRegionBootstrapAssignmentResolver resolver; private WorldCanonicalInstanceLifecycleEvidence.Request request; private WorldCanonicalInstanceLifecycleEvidence activeEvidence; + private CanonicalInitialPlayerLocationRequest initialLocationRequest; @BeforeEach void setUp() throws Exception { @@ -33,6 +41,7 @@ void setUp() throws Exception { resolver = new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient); activeEvidence = AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L); request = activeEvidence.request(); + initialLocationRequest = initialLocationRequest(request); } @Test @@ -110,6 +119,214 @@ void propagatesInvalidOwnerEvidenceFailure() { .isSameAs(invalidEvidence); } + @Test + void initialLocationRegionIsRevalidatedAgainstTheAuthenticatedLifecycleOwner() { + var initialClient = mock(CanonicalInitialPlayerLocationClient.class); + when(lifecycleClient.read(request)).thenReturn(activeEvidence); + var response = initialLocationRegionResponse(initialLocationRequest, activeEvidence); + when(initialClient.readInitialPlayerLocationRegion(initialLocationRequest)) + .thenReturn(response); + var resolver = + new CanonicalInitialPlayerLocationRegionResolver( + initialClient, new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); + + var resolved = resolver.resolve(initialLocationRequest); + + assertThat(resolved.canonicalRegionInstanceId()).isEqualTo(CANONICAL_REGION_ID); + assertThat(resolved.operationalRegionId()).isEqualTo(OPERATIONAL_REGION_ID); + assertThat(resolved.lifecycleAssignment().lifecycleEpoch()) + .isEqualTo(activeEvidence.lifecycleEpoch()); + verify(lifecycleClient).read(request); + } + + @Test + void initialLocationRegionRejectsLifecycleReadbackRace() { + var initialClient = mock(CanonicalInitialPlayerLocationClient.class); + when(lifecycleClient.read(request)).thenReturn(activeEvidence); + var response = initialLocationRegionResponse(initialLocationRequest, activeEvidence); + when(initialClient.readInitialPlayerLocationRegion(initialLocationRequest)) + .thenReturn( + response.toBuilder() + .setLifecycle(response.getLifecycle().toBuilder().setRowVersion(99L)) + .build()); + var resolver = + new CanonicalInitialPlayerLocationRegionResolver( + initialClient, new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); + + assertThatThrownBy(() -> resolver.resolve(initialLocationRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed during lifecycle revalidation"); + } + + @Test + void initialLocationRegionRejectsEpochCaptureGraphAndPreparationRaces() { + var initialClient = mock(CanonicalInitialPlayerLocationClient.class); + var response = initialLocationRegionResponse(initialLocationRequest, activeEvidence); + when(initialClient.readInitialPlayerLocationRegion(initialLocationRequest)) + .thenReturn(response); + var resolver = + new CanonicalInitialPlayerLocationRegionResolver( + initialClient, new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); + var changedEvidence = + new WorldCanonicalInstanceLifecycleEvidence[] { + changedEvidence( + activeEvidence, + activeEvidence.lifecycleEpoch() + 1, + activeEvidence.rowVersion(), + activeEvidence.captureId(), + activeEvidence.graphSha256(), + activeEvidence.preparationInputDigest()), + changedEvidence( + activeEvidence, + activeEvidence.lifecycleEpoch(), + activeEvidence.rowVersion(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + activeEvidence.graphSha256(), + activeEvidence.preparationInputDigest()), + changedEvidence( + activeEvidence, + activeEvidence.lifecycleEpoch(), + activeEvidence.rowVersion(), + activeEvidence.captureId(), + "9".repeat(64), + activeEvidence.preparationInputDigest()), + changedEvidence( + activeEvidence, + activeEvidence.lifecycleEpoch(), + activeEvidence.rowVersion(), + activeEvidence.captureId(), + activeEvidence.graphSha256(), + "sha256:" + "9".repeat(64)) + }; + + for (var raced : changedEvidence) { + when(lifecycleClient.read(request)).thenReturn(raced); + assertThatThrownBy(() -> resolver.resolve(initialLocationRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed during lifecycle revalidation"); + } + } + + @Test + void initialLocationRegionRejectsOperationalAssignmentSubstitution() { + var initialClient = mock(CanonicalInitialPlayerLocationClient.class); + when(lifecycleClient.read(request)).thenReturn(activeEvidence); + var response = initialLocationRegionResponse(initialLocationRequest, activeEvidence); + when(initialClient.readInitialPlayerLocationRegion(initialLocationRequest)) + .thenReturn( + response.toBuilder().setOperationalRegionUuid(UNKNOWN_REGION_ID.toString()).build()); + var resolver = + new CanonicalInitialPlayerLocationRegionResolver( + initialClient, new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); + + assertThatThrownBy(() -> resolver.resolve(initialLocationRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed during lifecycle revalidation"); + } + + private static CanonicalInitialPlayerLocationRequest initialLocationRequest( + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + var target = + PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid(lifecycleRequest.canonicalTenantId().toString()) + .setRealmUuid("33333333-3333-4333-8333-333333333333") + .setWorldSlug(lifecycleRequest.worldSlug()) + .setRealmSlug("test-realm") + .setGameInstanceId(lifecycleRequest.canonicalGameInstanceId().toString()) + .setCatalogRevision(1L) + .setCanonicalVersionUuid(lifecycleRequest.canonicalVersionId().toString()) + .setFrozenPolicyDigest("a".repeat(64)) + .setPlayableStateNamespaceUuid(lifecycleRequest.playableStateNamespaceId().toString()) + .setPublishedReleaseBundleRef("published/test/v1") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + return CanonicalInitialPlayerLocationRequest.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid("44444444-4444-4444-8444-444444444444") + .setExpectedTarget(target) + .setCanonicalAccountUuid("55555555-5555-4555-8555-555555555555") + .setCharacterUuid("66666666-6666-4666-8666-666666666666") + .setAssignmentUuid("77777777-7777-4777-8777-777777777777") + .setAssignmentIntentDigest("b".repeat(64)) + .setInitialAdmissionHoldUuid("88888888-8888-4888-8888-888888888888") + .setInitialAdmissionHoldFence("99999999-9999-4999-8999-999999999999") + .setInitialAdmissionRequestId("initial-attempt-1") + .setInitialAdmissionRequestDigest("c".repeat(64)) + .setActiveLifecycleEpoch(7L) + .setTerminalProofDigest("sha256:" + "d".repeat(64)) + .setCommittedPointerVersion(1L) + .setAuditEventId(1L) + .build(); + } + + private static CanonicalInitialPlayerLocationRegionResponse initialLocationRegionResponse( + CanonicalInitialPlayerLocationRequest request, + WorldCanonicalInstanceLifecycleEvidence evidence) { + var placement = + CanonicalInitialPlayerLocationResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(request.getPlacementOperationUuid()) + .setRequestDigest("sha256:" + "e".repeat(64)) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setCharacterUuid(request.getCharacterUuid()) + .setAssignmentUuid(request.getAssignmentUuid()) + .setAssignmentIntentDigest(request.getAssignmentIntentDigest()) + .setResultDigest("sha256:" + "f".repeat(64)) + .setOutcome( + CanonicalInitialPlayerLocationOutcome + .CANONICAL_INITIAL_PLAYER_LOCATION_OUTCOME_APPLIED) + .setStartLocation( + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRoom + .newBuilder() + .setCanonicalTenantUuid(request.getExpectedTarget().getCanonicalTenantUuid()) + .setCanonicalVersionUuid(request.getExpectedTarget().getCanonicalVersionUuid()) + .setRoomTemplateUuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) + .setPrivateRuntimeRoomKey("91") + .build(); + var lifecycle = + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationLifecycleConsequence + .newBuilder() + .setCanonicalRequestBytes( + com.google.protobuf.ByteString.copyFrom(evidence.request().canonicalBytes())) + .setLifecycleStatus(evidence.lifecycleStatus()) + .setLifecycleEpoch(evidence.lifecycleEpoch()) + .setRowVersion(evidence.rowVersion()) + .setCaptureUuid(evidence.captureId().toString()) + .setGraphSha256(evidence.graphSha256()) + .setPreparationInputDigest(evidence.preparationInputDigest()) + .build(); + return CanonicalInitialPlayerLocationRegionResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementResult(placement) + .setExpectedTarget(request.getExpectedTarget()) + .setCanonicalRegionInstanceUuid(CANONICAL_REGION_ID.toString()) + .setOperationalRegionUuid(OPERATIONAL_REGION_ID.toString()) + .setPrivateWorldInstanceKey(7L) + .setObservedRuntimeRoomKey(91L) + .setLifecycle(lifecycle) + .build(); + } + + private static WorldCanonicalInstanceLifecycleEvidence changedEvidence( + WorldCanonicalInstanceLifecycleEvidence original, + long epoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest) { + var changed = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(changed.request()).thenReturn(original.request()); + when(changed.lifecycleStatus()).thenReturn("ACTIVE"); + when(changed.lifecycleEpoch()).thenReturn(epoch); + when(changed.rowVersion()).thenReturn(rowVersion); + when(changed.captureId()).thenReturn(captureId); + when(changed.graphSha256()).thenReturn(graphSha256); + when(changed.preparationInputDigest()).thenReturn(preparationInputDigest); + when(changed.operationalRegionAssignments()) + .thenReturn(original.operationalRegionAssignments()); + return changed; + } + private static WorldCanonicalInstanceLifecycleEvidence.Request copyRequestWithDifferentTargetNamespace( WorldCanonicalInstanceLifecycleEvidence.Request source) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java index 1b64e781ce..9507565081 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java @@ -1,12 +1,18 @@ package net.firedevops.firemud.worldmanagement.tenant; +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository.Outcome; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository.RegionResult; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository.Result; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationLifecycleConsequence; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRoom; @@ -15,6 +21,9 @@ final class CanonicalInitialPlayerLocationGrpcCodec { static final int SCHEMA_VERSION = 1; static final int MAX_REQUEST_BYTES = 16 * 1024; + static final int MAX_REGION_REQUEST_BYTES = 16 * 1024; + static final int MAX_REGION_RESPONSE_BYTES = 8 * 1024; + static final int MAX_LIFECYCLE_REQUEST_BYTES = 4 * 1024; private static final int MAX_RELEASE_REF_LENGTH = 128; private static final Pattern RAW_SHA256 = Pattern.compile("[0-9a-f]{64}"); private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); @@ -22,8 +31,17 @@ final class CanonicalInitialPlayerLocationGrpcCodec { private CanonicalInitialPlayerLocationGrpcCodec() {} static Selection fromRequest(CanonicalInitialPlayerLocationRequest request) { + return fromRequest(request, MAX_REQUEST_BYTES); + } + + static Selection fromRegionRequest(CanonicalInitialPlayerLocationRequest request) { + return fromRequest(request, MAX_REGION_REQUEST_BYTES); + } + + private static Selection fromRequest( + CanonicalInitialPlayerLocationRequest request, int maximumRequestBytes) { if (request == null - || request.getSerializedSize() > MAX_REQUEST_BYTES + || request.getSerializedSize() > maximumRequestBytes || request.getSchemaVersion() != SCHEMA_VERSION || !request.getUnknownFields().asMap().isEmpty() || !request.hasExpectedTarget() @@ -154,6 +172,73 @@ static CanonicalInitialPlayerLocationResponse toResponse(Selection selection, Re return response.build(); } + static CanonicalInitialPlayerLocationRegionResponse toRegionResponse( + Selection selection, RegionResult result) { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(result, "result"); + var placement = toResponse(selection, result.placementResult()); + var lifecycle = result.lifecycleEvidence(); + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest = lifecycle.request(); + byte[] lifecycleRequestBytes = lifecycleRequest.canonicalBytes(); + long placementRoomKey; + try { + placementRoomKey = Long.parseLong(placement.getPrivateRuntimeRoomKey()); + } catch (NumberFormatException invalid) { + throw new IllegalStateException("Applied placement has an invalid private room key", invalid); + } + if (placement.getOutcome() + != CanonicalInitialPlayerLocationOutcome + .CANONICAL_INITIAL_PLAYER_LOCATION_OUTCOME_APPLIED + || placementRoomKey != result.runtimeRoomInstanceKey() + || result.lifecycleEvidence().runtimeRoomInstanceId() != result.runtimeRoomInstanceKey() + || !result.placementResult().startLocation().equals(lifecycle.startLocation()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != selection.activeLifecycleEpoch() + || !lifecycleRequest.canonicalTenantId().equals(selection.canonicalTenantId()) + || !lifecycleRequest.readRequestId().equals(lifecycleReadRequestId(selection)) + || !lifecycleRequest.canonicalGameInstanceId().equals(selection.canonicalGameInstanceId()) + || !lifecycleRequest.playableStateNamespaceId().equals(selection.playableStateNamespaceId()) + || !lifecycleRequest.playableStateScope().equals(selection.playableStateScope()) + || !lifecycleRequest.worldSlug().equals(selection.worldSlug()) + || !lifecycleRequest.canonicalVersionId().equals(selection.canonicalVersionId()) + || !lifecycleRequest.publicProduction() + || lifecycleRequestBytes.length > MAX_LIFECYCLE_REQUEST_BYTES + || result.canonicalRegionInstanceId().equals(new UUID(0L, 0L)) + || result.operationalRegionId().equals(new UUID(0L, 0L)) + || !result + .operationalRegionId() + .equals( + lifecycle.operationalRegionAssignments().get(result.canonicalRegionInstanceId()))) { + throw new IllegalStateException( + "Current World initial-location region evidence differs from the retained target or room"); + } + var consequence = + CanonicalInitialPlayerLocationLifecycleConsequence.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFrom(lifecycleRequestBytes)) + .setLifecycleStatus(lifecycle.lifecycleStatus()) + .setLifecycleEpoch(lifecycle.lifecycleEpoch()) + .setRowVersion(lifecycle.rowVersion()) + .setCaptureUuid(lifecycle.captureId().toString()) + .setGraphSha256(lifecycle.graphSha256()) + .setPreparationInputDigest(lifecycle.preparationInputDigest()) + .build(); + var response = + CanonicalInitialPlayerLocationRegionResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setPlacementResult(placement) + .setExpectedTarget(selection.expectedTarget()) + .setCanonicalRegionInstanceUuid(result.canonicalRegionInstanceId().toString()) + .setOperationalRegionUuid(result.operationalRegionId().toString()) + .setPrivateWorldInstanceKey(result.privateWorldInstanceKey()) + .setObservedRuntimeRoomKey(result.runtimeRoomInstanceKey()) + .setLifecycle(consequence) + .build(); + if (response.getSerializedSize() > MAX_REGION_RESPONSE_BYTES) { + throw new IllegalStateException("World initial-location region response exceeds its bound"); + } + return response; + } + private static UUID uuid(String value, String field) { try { UUID parsed = UUID.fromString(value); @@ -166,6 +251,13 @@ private static UUID uuid(String value, String field) { } } + private static UUID lifecycleReadRequestId(Selection selection) { + byte[] name = + ("firemud-world-initial-location-lifecycle-read/v1/" + selection.placementOperationId()) + .getBytes(StandardCharsets.US_ASCII); + return UUID.nameUUIDFromBytes(name); + } + private static String rawDigest(String value, String field) { if (!RAW_SHA256.matcher(value).matches()) { throw invalid(field + " must be a lowercase SHA-256 digest"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java index 6373e3e5e7..794feed246 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java @@ -7,6 +7,7 @@ import java.util.Optional; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository.Result; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationServiceGrpc; @@ -136,6 +137,73 @@ public void readInitialPlayerLocation( responseObserver.onCompleted(); } + @Override + public void readInitialPlayerLocationRegion( + CanonicalInitialPlayerLocationRequest request, + StreamObserver responseObserver) { + if (!requirePeer(responseObserver)) return; + CanonicalInitialPlayerLocationGrpcCodec.Selection selection; + try { + selection = CanonicalInitialPlayerLocationGrpcCodec.fromRegionRequest(request); + } catch (IllegalArgumentException invalid) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete closed region-placement selector is required"); + return; + } + final Optional response; + try { + response = + service + .readRegion(selection) + .map( + retained -> + CanonicalInitialPlayerLocationGrpcCodec.toRegionResponse( + selection, retained)); + } catch (StatusRuntimeException rejected) { + reportOwnerFailure( + responseObserver, rejected, "World initial-player region read is unavailable"); + return; + } catch (WorldCanonicalInitialPlayerLocationRepository.OperationBindingConflictException + | WorldCanonicalInitialPlayerLocationRepository.InvalidInitialLocationEvidenceException + | WorldCanonicalInitialPlayerLocationRepository.InvalidInitialLocationReadbackException + | WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldEvidenceException rejected) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Exact initial-placement region evidence is unavailable"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.UNAVAILABLE, "World initial-player region read is unavailable"); + return; + } + + if (response.isEmpty()) { + fail( + responseObserver, + Status.NOT_FOUND, + "No exact retained initial-placement region matches the selector"); + return; + } + CanonicalInitialPlayerLocationRegionResponse value = response.orElseThrow(); + if (value.getSerializedSize() + > CanonicalInitialPlayerLocationGrpcCodec.MAX_REGION_RESPONSE_BYTES) { + fail( + responseObserver, + Status.RESOURCE_EXHAUSTED, + "World initial-player region response exceeds its method bound"); + return; + } + try { + responseObserver.onNext(value); + } catch (RuntimeException observerFailure) { + responseObserver.onError(observerFailure); + return; + } + responseObserver.onCompleted(); + } + private boolean requirePeer(StreamObserver responseObserver) { if (CanonicalInitialPlayerLocationPeerInterceptor.currentVerifiedPeer() == null) { fail( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationPeerInterceptor.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationPeerInterceptor.java index 81d48576f5..af1da2a665 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationPeerInterceptor.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationPeerInterceptor.java @@ -11,12 +11,14 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; -/** Exact same-namespace Game Session certificate guard for the two initial-location RPCs. */ +/** Exact same-namespace Game Session certificate guard for initial-location owner RPCs. */ public final class CanonicalInitialPlayerLocationPeerInterceptor implements ServerInterceptor { public static final String PLACE_METHOD_NAME = "world_management.v1.CanonicalInitialPlayerLocationService/PlaceInitialPlayer"; public static final String READ_METHOD_NAME = "world_management.v1.CanonicalInitialPlayerLocationService/ReadInitialPlayerLocation"; + public static final String READ_REGION_METHOD_NAME = + "world_management.v1.CanonicalInitialPlayerLocationService/ReadInitialPlayerLocationRegion"; private static final Context.Key VERIFIED_GAME_SESSION_PEER = Context.key("firemud-canonical-initial-player-location-peer"); @@ -34,7 +36,9 @@ public CanonicalInitialPlayerLocationPeerInterceptor(String trustedNamespace) { public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { String methodName = call.getMethodDescriptor().getFullMethodName(); - if (!PLACE_METHOD_NAME.equals(methodName) && !READ_METHOD_NAME.equals(methodName)) { + if (!PLACE_METHOD_NAME.equals(methodName) + && !READ_METHOD_NAME.equals(methodName) + && !READ_REGION_METHOD_NAME.equals(methodName)) { return next.startCall(call, headers); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java index 2886477f2a..888b8e93d3 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java @@ -129,6 +129,26 @@ public Optional read(CanonicalInitialPlayerLocationGrpcCodec.Selection s return retained; } + /** + * Reads a fresh initial-room region consequence after revalidating the immutable Entity receipt. + * The repository performs the retained placement, current location, topology, and ACTIVE + * lifecycle checks together in one read-only owner snapshot. + */ + public Optional readRegion( + CanonicalInitialPlayerLocationGrpcCodec.Selection selection) { + Objects.requireNonNull(selection, "selection"); + requireNoAmbientTransaction("World initial-player location region read"); + RequestSelector selector = requestSelector(selection); + Optional retained = + locationRepository.readByOperationId(selection.placementOperationId(), selector); + if (retained.isEmpty()) return Optional.empty(); + if (retained.orElseThrow().outcome() != Outcome.APPLIED) { + throw failedPrecondition("Initial-player region resolution requires an APPLIED placement"); + } + requireExactEntityReceipt(selection); + return locationRepository.readInitialPlayerLocationRegion(selector); + } + private ReadPreseededActorAssignmentReceiptResponse requireExactEntityReceipt( CanonicalInitialPlayerLocationGrpcCodec.Selection selection) { // This is Entity's immutable historical assignment receipt, not current Account authority or diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java index 22b1adfb8f..dcc6a07d19 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java @@ -75,6 +75,95 @@ public final class WorldCanonicalInitialPlayerLocationRepository { .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .build(); + // Shared with focused native schema proof; it does not establish positive owner authority. + static final String INITIAL_REGION_MAPPING_SQL = + "SELECT o.operation_id,o.world_instance_id AS operation_world_instance_id," + + "o.request_digest AS operation_request_digest," + + "o.request_bytes,o.original_lifecycle_evidence_bytes,o.result_bytes,o.result_digest," + + "l.canonical_tenant_id AS location_tenant_id,l.realm_id AS location_realm_id," + + "l.playable_state_namespace_id AS location_namespace_id," + + "l.canonical_game_instance_id AS location_game_instance_id," + + "l.world_instance_id AS location_world_instance_id," + + "l.canonical_account_id,l.character_id,l.entity_assignment_operation_id," + + "l.entity_assignment_digest,l.canonical_version_id,l.active_lifecycle_epoch," + + "l.initial_room_template_id,l.initial_runtime_room_instance_id," + + "l.runtime_room_instance_id,l.initial_location_operation_id," + + "l.initial_location_request_digest,l.initial_lifecycle_evidence_bytes," + + "l.initial_lifecycle_evidence_digest," + + "w.id AS current_world_instance_id,w.tenant_id AS private_tenant_key," + + "w.game_instance_id AS private_game_instance_key,w.status AS current_lifecycle_status," + + "w.lifecycle_epoch AS current_lifecycle_epoch,w.row_version AS current_lifecycle_row_version," + + "rmi.id AS room_row_id,rmi.room_instance_row_id AS runtime_room_key," + + "rmi.template_room_id AS room_template_private_key,rmi.zone_instance_id AS room_zone_row_id," + + "rmi.region_instance_id AS room_region_row_id,rmi.tenant_id AS room_tenant_key," + + "rmi.game_instance_id AS room_game_instance_key,rt.zone_id AS room_template_zone_key," + + "zi.id AS zone_row_id,zi.zone_instance_id AS runtime_zone_key," + + "zi.template_zone_id AS zone_template_private_key,zi.region_instance_id AS zone_region_row_id," + + "zi.canonical_zone_instance_id,zi.tenant_id AS zone_tenant_key," + + "zi.game_instance_id AS zone_game_instance_key,z.region_id AS zone_template_region_key," + + "ri.id AS region_row_id,ri.canonical_region_instance_id,ri.operational_region_id," + + "ri.tenant_id AS region_tenant_key,ri.game_instance_id AS region_game_instance_key," + + "ri.world_instance_id AS region_world_instance_id," + + "room_map.id AS room_mapping_id,room_map.world_instance_id AS room_mapping_world_id," + + "room_map.canonical_game_instance_id AS room_mapping_game_instance_id," + + "room_map.template_id AS room_mapping_template_id," + + "room_map.template_private_row_key AS room_mapping_template_private_key," + + "room_map.runtime_row_id AS room_mapping_runtime_row_id," + + "room_map.runtime_room_instance_id AS room_mapping_runtime_room_key," + + "zone_map.id AS zone_mapping_id,zone_map.world_instance_id AS zone_mapping_world_id," + + "zone_map.canonical_game_instance_id AS zone_mapping_game_instance_id," + + "zone_map.template_id AS zone_mapping_template_id," + + "zone_map.template_private_row_key AS zone_mapping_template_private_key," + + "zone_map.runtime_row_id AS zone_mapping_runtime_row_id," + + "zone_map.runtime_identity AS zone_mapping_runtime_identity," + + "region_map.id AS region_mapping_id,region_map.world_instance_id AS region_mapping_world_id," + + "region_map.canonical_game_instance_id AS region_mapping_game_instance_id," + + "region_map.template_id AS region_mapping_template_id," + + "region_map.template_private_row_key AS region_mapping_template_private_key," + + "region_map.runtime_row_id AS region_mapping_runtime_row_id," + + "region_map.runtime_identity AS region_mapping_runtime_identity " + + "FROM world_canonical_initial_player_location_operation o " + + "JOIN character_location l ON l.initial_location_operation_id=o.operation_id " + + "JOIN world_instance w ON w.id=o.world_instance_id " + + "AND w.id=l.world_instance_id AND w.canonical_game_instance_id=l.canonical_game_instance_id " + + "JOIN room_instance rmi ON rmi.tenant_id=w.tenant_id " + + "AND rmi.game_instance_id=w.game_instance_id " + + "AND rmi.room_instance_row_id=l.runtime_room_instance_id " + + "JOIN room rt ON rt.id=rmi.template_room_id AND rt.tenant_id=w.tenant_id " + + "AND rt.version_id=w.version_id " + + "JOIN zone_instance zi ON zi.id=rmi.zone_instance_id " + + "AND zi.tenant_id=w.tenant_id AND zi.game_instance_id=w.game_instance_id " + + "AND zi.region_instance_id=rmi.region_instance_id " + + "JOIN zone z ON z.id=zi.template_zone_id AND z.id=rt.zone_id " + + "AND z.tenant_id=w.tenant_id AND z.version_id=w.version_id " + + "JOIN region_instance ri ON ri.id=zi.region_instance_id " + + "AND ri.id=rmi.region_instance_id AND ri.world_instance_id=w.id " + + "AND ri.tenant_id=w.tenant_id AND ri.game_instance_id=w.game_instance_id " + + "JOIN region template_region ON template_region.id=z.region_id " + + "AND template_region.tenant_id=w.tenant_id AND template_region.version_id=w.version_id " + + "JOIN world_canonical_instance_topology_identity room_map " + + "ON room_map.world_instance_id=w.id AND room_map.canonical_game_instance_id=w.canonical_game_instance_id " + + "AND room_map.family='ROOM' AND room_map.runtime_row_id=rmi.id " + + "AND room_map.runtime_room_instance_id=rmi.room_instance_row_id " + + "AND room_map.template_id=? AND room_map.template_private_row_key=rmi.template_room_id " + + "JOIN world_canonical_instance_topology_identity zone_map " + + "ON zone_map.world_instance_id=w.id AND zone_map.canonical_game_instance_id=w.canonical_game_instance_id " + + "AND zone_map.family='ZONE' AND zone_map.runtime_row_id=zi.id " + + "AND zone_map.template_private_row_key=zi.template_zone_id " + + "AND zone_map.runtime_identity=zi.canonical_zone_instance_id " + + "JOIN world_canonical_instance_topology_identity region_map " + + "ON region_map.world_instance_id=w.id AND region_map.canonical_game_instance_id=w.canonical_game_instance_id " + + "AND region_map.family='REGION' AND region_map.runtime_row_id=ri.id " + + "AND region_map.template_private_row_key=template_region.id " + + "AND region_map.runtime_identity=ri.canonical_region_instance_id " + + "WHERE o.operation_id=? AND o.outcome='APPLIED' AND l.canonical_tenant_id=? " + + "AND l.realm_id=? AND l.playable_state_namespace_id=? AND l.canonical_game_instance_id=? " + + "AND l.canonical_account_id=? AND l.character_id=? " + + "AND l.entity_assignment_operation_id=? AND l.entity_assignment_digest=? " + + "AND l.canonical_version_id=? AND l.active_lifecycle_epoch=? " + + "AND l.initial_room_template_id=? AND l.initial_runtime_room_instance_id=l.runtime_room_instance_id " + + "AND l.initial_runtime_room_instance_id=? AND w.status='ACTIVE' AND w.lifecycle_epoch=?"; + private final DSLContext dsl; private final TransactionTemplate readTransaction; private final TransactionTemplate writeTransaction; @@ -161,6 +250,216 @@ public Optional readByOperationId(UUID operationId, RequestSelector sele })); } + /** + * Reads the retained initial placement and its current same-room region consequence in one + * read-only repeatable-read World owner snapshot. The Entity receipt remains a caller-side + * authenticated read and must be completed before invoking this method. + */ + public Optional readInitialPlayerLocationRegion(RequestSelector selector) { + Objects.requireNonNull(selector, "selector"); + requireNoActiveTransaction("World canonical initial-location region read"); + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + Record operation = readOperation(selector.operationId()); + if (operation == null) return null; + Request retainedRequest = retainedRequest(operation, selector.operationId()); + ParsedRequest parsed = parseRequest(retainedRequest); + selector.requireMatches(parsed); + Result placement = + readInOwnerTransaction(retainedRequest) + .orElseThrow( + () -> + invalidReadback( + "Retained World initial-location operation disappeared during region read")); + if (placement.outcome() != Outcome.APPLIED + || placement.startLocation() == null + || placement.runtimeRoomInstanceId() == null) { + throw invalidReadback( + "Initial-location region consequence requires the retained APPLIED placement"); + } + + WorldCanonicalInstanceLifecycleEvidence retainedLifecycle = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + retainedRequest.originalLifecycleEvidenceBytes()); + WorldCanonicalInstanceLifecycleEvidence currentLifecycle; + try { + currentLifecycle = + lifecycleRepository + .readForCurrentLocationInOwnerTransaction(retainedLifecycle.request()) + .orElse(null); + } catch ( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException + invalid) { + throw invalidReadback( + "Current World lifecycle evidence is inconsistent with initial placement", + invalid); + } + requireCurrentLifecycle(retainedLifecycle, currentLifecycle, placement, parsed); + RegionMapping mapping = + readInitialRegionMapping(retainedRequest, placement, parsed, currentLifecycle); + return new RegionResult( + placement, + mapping.worldInstanceId(), + mapping.runtimeRoomInstanceId(), + mapping.canonicalRegionInstanceId(), + mapping.operationalRegionId(), + currentLifecycle); + })); + } + + private Request retainedRequest(Record operation, UUID operationId) { + return new Request( + operationId, + required(operation, "request_digest", String.class), + required(operation, "request_bytes", byte[].class), + required(operation, "original_lifecycle_evidence_bytes", byte[].class)); + } + + private void requireCurrentLifecycle( + WorldCanonicalInstanceLifecycleEvidence retained, + WorldCanonicalInstanceLifecycleEvidence current, + Result placement, + ParsedRequest parsed) { + if (current == null + || !"ACTIVE".equals(current.lifecycleStatus()) + || current.lifecycleEpoch() != parsed.activeLifecycleEvidence().lifecycleEpoch() + || !current.request().equals(retained.request()) + || !current.startLocation().equals(placement.startLocation()) + || current.runtimeRoomInstanceId() != placement.runtimeRoomInstanceId() + || !current.captureId().equals(retained.captureId()) + || !current.graphSha256().equals(retained.graphSha256()) + || !current.preparationInputDigest().equals(retained.preparationInputDigest()) + || !current + .operationalRegionAssignments() + .equals(retained.operationalRegionAssignments())) { + throw invalidReadback( + "Current World lifecycle, graph, room, or region assignments differ from retained initial placement"); + } + } + + private RegionMapping readInitialRegionMapping( + Request retainedRequest, + Result placement, + ParsedRequest parsed, + WorldCanonicalInstanceLifecycleEvidence currentLifecycle) { + var rows = + dsl.fetch( + INITIAL_REGION_MAPPING_SQL, + placement.startLocation().roomTemplateId(), + parsed.operationId(), + parsed.canonicalTenantId(), + parsed.realmId(), + parsed.playableStateNamespaceId(), + parsed.canonicalGameInstanceId(), + parsed.canonicalAccountId(), + parsed.characterId(), + parsed.entityAssignmentOperationId(), + parsed.entityAssignmentDigest(), + parsed.canonicalVersionId(), + parsed.activeLifecycleEvidence().lifecycleEpoch(), + placement.startLocation().roomTemplateId(), + placement.runtimeRoomInstanceId(), + currentLifecycle.lifecycleEpoch()); + if (rows.size() != 1) { + throw invalidReadback( + "Current initial room has no unique exact ROOM-to-ZONE-to-REGION mapping"); + } + Record row = rows.getFirst(); + long worldInstanceId = required(row, "current_world_instance_id", Long.class); + long runtimeRoomKey = required(row, "runtime_room_key", Long.class); + UUID canonicalRegionId = required(row, "canonical_region_instance_id", UUID.class); + UUID mappedCanonicalRegionId = required(row, "region_mapping_runtime_identity", UUID.class); + UUID operationalRegionId = required(row, "operational_region_id", UUID.class); + if (!required(row, "operation_id", UUID.class).equals(parsed.operationId()) + || required(row, "operation_world_instance_id", Long.class) != worldInstanceId + || !required(row, "operation_request_digest", String.class) + .equals(placement.requestDigest()) + || !Arrays.equals(required(row, "request_bytes", byte[].class), placement.requestBytes()) + || !Arrays.equals(required(row, "result_bytes", byte[].class), placement.resultBytes()) + || !required(row, "result_digest", String.class).equals(placement.resultDigest()) + || !Arrays.equals( + required(row, "original_lifecycle_evidence_bytes", byte[].class), + retainedRequest.originalLifecycleEvidenceBytes()) + || !required(row, "location_tenant_id", UUID.class).equals(parsed.canonicalTenantId()) + || !required(row, "location_realm_id", UUID.class).equals(parsed.realmId()) + || !required(row, "location_namespace_id", UUID.class) + .equals(parsed.playableStateNamespaceId()) + || !required(row, "location_game_instance_id", UUID.class) + .equals(parsed.canonicalGameInstanceId()) + || !required(row, "location_world_instance_id", Long.class).equals(worldInstanceId) + || !required(row, "canonical_account_id", UUID.class).equals(parsed.canonicalAccountId()) + || !required(row, "character_id", UUID.class).equals(parsed.characterId()) + || !required(row, "entity_assignment_operation_id", UUID.class) + .equals(parsed.entityAssignmentOperationId()) + || !required(row, "entity_assignment_digest", String.class) + .equals(parsed.entityAssignmentDigest()) + || !required(row, "canonical_version_id", UUID.class).equals(parsed.canonicalVersionId()) + || required(row, "active_lifecycle_epoch", Long.class) != currentLifecycle.lifecycleEpoch() + || !required(row, "initial_room_template_id", UUID.class) + .equals(placement.startLocation().roomTemplateId()) + || required(row, "initial_runtime_room_instance_id", Long.class) != runtimeRoomKey + || required(row, "runtime_room_instance_id", Long.class) != runtimeRoomKey + || !required(row, "initial_location_operation_id", UUID.class).equals(parsed.operationId()) + || !required(row, "initial_location_request_digest", String.class) + .equals(placement.requestDigest()) + || !Arrays.equals( + required(row, "initial_lifecycle_evidence_bytes", byte[].class), + retainedRequest.originalLifecycleEvidenceBytes()) + || !required(row, "initial_lifecycle_evidence_digest", String.class) + .equals(prefixedDigest(retainedRequest.originalLifecycleEvidenceBytes())) + || required(row, "current_lifecycle_row_version", Long.class) + != currentLifecycle.rowVersion() + || !sameLong(row, "private_tenant_key", "room_tenant_key") + || !sameLong(row, "private_game_instance_key", "room_game_instance_key") + || !sameLong(row, "private_tenant_key", "zone_tenant_key") + || !sameLong(row, "private_game_instance_key", "zone_game_instance_key") + || !sameLong(row, "private_tenant_key", "region_tenant_key") + || !sameLong(row, "private_game_instance_key", "region_game_instance_key") + || !sameLong(row, "current_world_instance_id", "region_world_instance_id") + || required(row, "room_mapping_world_id", Long.class) != worldInstanceId + || required(row, "zone_mapping_world_id", Long.class) != worldInstanceId + || required(row, "region_mapping_world_id", Long.class) != worldInstanceId + || !required(row, "room_mapping_game_instance_id", UUID.class) + .equals(parsed.canonicalGameInstanceId()) + || !required(row, "zone_mapping_game_instance_id", UUID.class) + .equals(parsed.canonicalGameInstanceId()) + || !required(row, "region_mapping_game_instance_id", UUID.class) + .equals(parsed.canonicalGameInstanceId()) + || !required(row, "room_mapping_template_id", UUID.class) + .equals(placement.startLocation().roomTemplateId()) + || !sameLong(row, "room_mapping_template_private_key", "room_template_private_key") + || !sameLong(row, "room_mapping_runtime_row_id", "room_row_id") + || required(row, "room_mapping_runtime_room_key", Long.class) != runtimeRoomKey + || !sameLong(row, "room_zone_row_id", "zone_row_id") + || !sameLong(row, "room_region_row_id", "region_row_id") + || !sameLong(row, "room_template_zone_key", "zone_template_private_key") + || !sameLong(row, "zone_mapping_template_private_key", "zone_template_private_key") + || !sameLong(row, "zone_mapping_runtime_row_id", "zone_row_id") + || !required(row, "zone_mapping_runtime_identity", UUID.class) + .equals(required(row, "canonical_zone_instance_id", UUID.class)) + || !sameLong(row, "zone_template_region_key", "region_mapping_template_private_key") + || !sameLong(row, "region_mapping_runtime_row_id", "region_row_id") + || canonicalRegionId.equals(operationalRegionId) + || !canonicalRegionId.equals(mappedCanonicalRegionId) + || !operationalRegionId.equals( + currentLifecycle.operationalRegionAssignments().get(canonicalRegionId))) { + throw invalidReadback( + "Current initial room, runtime topology, and canonical region assignment disagree"); + } + if (required(row, "room_mapping_id", Long.class) <= 0 + || required(row, "zone_mapping_id", Long.class) <= 0 + || required(row, "region_mapping_id", Long.class) <= 0 + || !"ACTIVE".equals(required(row, "current_lifecycle_status", String.class)) + || required(row, "current_lifecycle_epoch", Long.class) + != currentLifecycle.lifecycleEpoch()) { + throw invalidReadback("Current World region consequence has incomplete owner identity"); + } + return new RegionMapping( + worldInstanceId, runtimeRoomKey, canonicalRegionId, operationalRegionId); + } + private boolean storeInOwnerTransaction(Request request) { requireWritableOwnerTransaction(); lockOperationId(request.operationId()); @@ -876,6 +1175,11 @@ private static T required(Record row, String field, Class type) { return value; } + private static boolean sameLong(Record row, String left, String right) { + return required(row, left, Long.class).longValue() + == required(row, right, Long.class).longValue(); + } + private static void requireNoActiveTransaction(String label) { if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException(label + " requires an independent owner transaction"); @@ -934,6 +1238,39 @@ public enum Outcome { UNREGISTERED } + /** Fresh region consequence of one retained APPLIED initial placement. */ + public record RegionResult( + Result placementResult, + long privateWorldInstanceKey, + long runtimeRoomInstanceKey, + UUID canonicalRegionInstanceId, + UUID operationalRegionId, + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence) { + public RegionResult { + Objects.requireNonNull(placementResult, "placementResult"); + Objects.requireNonNull(canonicalRegionInstanceId, "canonicalRegionInstanceId"); + Objects.requireNonNull(operationalRegionId, "operationalRegionId"); + Objects.requireNonNull(lifecycleEvidence, "lifecycleEvidence"); + if (placementResult.outcome() != Outcome.APPLIED + || privateWorldInstanceKey <= 0 + || runtimeRoomInstanceKey <= 0 + || placementResult.runtimeRoomInstanceId() == null + || placementResult.runtimeRoomInstanceId() != runtimeRoomInstanceKey + || canonicalRegionInstanceId.equals(operationalRegionId) + || !operationalRegionId.equals( + lifecycleEvidence.operationalRegionAssignments().get(canonicalRegionInstanceId))) { + throw new IllegalArgumentException( + "World initial-location region consequence is inconsistent"); + } + } + } + + private record RegionMapping( + long worldInstanceId, + long runtimeRoomInstanceId, + UUID canonicalRegionInstanceId, + UUID operationalRegionId) {} + /** Exact original owner request and lifecycle proof bytes; the tuple is comparison input only. */ public record Request( UUID operationId, diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java index 09f0348f6b..2d0b47b0ed 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java @@ -91,6 +91,7 @@ void bothRpcMethodsRequireTheExactSameNamespaceGameSessionCertificate(@TempDir P .thenThrow(upstreamFailure) .thenThrow(Status.NOT_FOUND.withDescription("secret Entity absence").asRuntimeException()); when(service.read(any())).thenReturn(Optional.of(retained), Optional.empty()); + when(service.readRegion(any())).thenReturn(Optional.empty()); Server server = startServer(pki, service); try { ManagedChannel channel = channel(pki, "game-session", server.getPort()); @@ -113,6 +114,12 @@ void bothRpcMethodsRequireTheExactSameNamespaceGameSessionCertificate(@TempDir P failure -> assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.NOT_FOUND)); + assertThatThrownBy(() -> stub.readInitialPlayerLocationRegion(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); assertThatThrownBy(() -> stub.placeInitialPlayer(request)) .isInstanceOf(StatusRuntimeException.class) .satisfies( @@ -143,6 +150,8 @@ void bothRpcMethodsRequireTheExactSameNamespaceGameSessionCertificate(@TempDir P .place(CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request)); verify(service, times(2)) .read(CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request)); + verify(service) + .readRegion(CanonicalInitialPlayerLocationGrpcCodec.fromRegionRequest(request)); assertThatThrownBy( () -> @@ -163,11 +172,14 @@ void bothRpcMethodsRequireTheExactSameNamespaceGameSessionCertificate(@TempDir P var stub = CanonicalInitialPlayerLocationServiceGrpc.newBlockingStub(rejectedPeerChannel) .withDeadlineAfter(10, TimeUnit.SECONDS); - for (boolean read : new boolean[] {false, true}) { + for (int method : new int[] {0, 1, 2}) { assertThatThrownBy( () -> { - if (read) stub.readInitialPlayerLocation(request()); - else stub.placeInitialPlayer(request()); + switch (method) { + case 0 -> stub.placeInitialPlayer(request()); + case 1 -> stub.readInitialPlayerLocation(request()); + default -> stub.readInitialPlayerLocationRegion(request()); + } }) .isInstanceOf(StatusRuntimeException.class) .satisfies( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepositoryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepositoryPostgresIntegrationTest.java index 73be8a560a..f6b82efc64 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepositoryPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepositoryPostgresIntegrationTest.java @@ -81,6 +81,16 @@ void receiverRejectsInvalidIntentAndLeavesUnregisteredWorldUnchanged() throws Ex current.validate(); assertThat(current.info().pending()).isEmpty(); + // Plan the actual production join without inventing an ACTIVE owner or placement. This + // checks current-schema column references only; positive region/placement proof stays open. + var queryField = + WorldCanonicalInitialPlayerLocationRepository.class.getDeclaredField( + "INITIAL_REGION_MAPPING_SQL"); + queryField.setAccessible(true); + String regionMappingSql = java.util.Objects.requireNonNull((String) queryField.get(null)); + Object[] unboundSelectors = new Object[15]; + assertThat(dsl.fetch("EXPLAIN " + regionMappingSql, unboundSelectors)).isNotEmpty(); + var associationRepository = new WorldCanonicalInstanceAssociationRepository( dsl, @@ -115,6 +125,8 @@ void receiverRejectsInvalidIntentAndLeavesUnregisteredWorldUnchanged() throws Ex assertThat(repository.read(request)).isEmpty(); assertThat(repository.readByOperationId(request.operationId(), selector(request, lifecycle))) .isEmpty(); + assertThat(repository.readInitialPlayerLocationRegion(selector(request, lifecycle))) + .isEmpty(); var downgradedTransactionManager = new ReadCommittedPhysicalRepeatableReadTransactionManager(source); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java index 208d392e4c..c86d5ae6a6 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java @@ -2,13 +2,18 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import com.google.protobuf.UnknownFieldSet; +import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository.Outcome; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository.RegionResult; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository.Result; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; @@ -180,6 +185,74 @@ void rendersOnlyRetainedAppliedOrConflictOutcomes() { .isInstanceOf(IllegalStateException.class); } + @Test + void emitsFreshRegionConsequenceOutsideTheImmutablePlacementResult() { + var selection = CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request()); + var start = new RoomTemplateRef(TENANT, VERSION, uuid("12121212-1212-4212-8212-121212121212")); + var placement = + new Result( + Outcome.APPLIED, + null, + start, + 917L, + new byte[] {1}, + "sha256:" + "a".repeat(64), + new byte[] {2}, + "sha256:" + "b".repeat(64), + true); + UUID canonicalRegion = uuid("13131313-1313-4313-8313-131313131313"); + UUID operationalRegion = uuid("14141414-1414-4414-8414-141414141414"); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.nameUUIDFromBytes( + ("firemud-world-initial-location-lifecycle-read/v1/" + + selection.placementOperationId()) + .getBytes(java.nio.charset.StandardCharsets.US_ASCII)), + "world-management", + TENANT, + selection.worldSlug(), + GAME_INSTANCE, + NAMESPACE, + "SHARED", + true, + "control-plane-17", + VERSION, + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64), + "sha256:" + "e".repeat(64)); + var lifecycle = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(lifecycle.request()).thenReturn(lifecycleRequest); + when(lifecycle.startLocation()).thenReturn(start); + when(lifecycle.runtimeRoomInstanceId()).thenReturn(917L); + when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycle.lifecycleEpoch()).thenReturn(selection.activeLifecycleEpoch()); + when(lifecycle.rowVersion()).thenReturn(9L); + when(lifecycle.captureId()).thenReturn(uuid("16161616-1616-4616-8616-161616161616")); + when(lifecycle.graphSha256()).thenReturn("f".repeat(64)); + when(lifecycle.preparationInputDigest()).thenReturn("sha256:" + "1".repeat(64)); + when(lifecycle.operationalRegionAssignments()) + .thenReturn(Map.of(canonicalRegion, operationalRegion)); + + var response = + CanonicalInitialPlayerLocationGrpcCodec.toRegionResponse( + selection, + new RegionResult(placement, 4L, 917L, canonicalRegion, operationalRegion, lifecycle)); + + assertThat(response.getPlacementResult().getRequestDigest()) + .isEqualTo(placement.requestDigest()); + assertThat(response.getPlacementResult().getResultDigest()).isEqualTo(placement.resultDigest()); + assertThat(response.getExpectedTarget()).isEqualTo(selection.expectedTarget()); + assertThat(response.getCanonicalRegionInstanceUuid()).isEqualTo(canonicalRegion.toString()); + assertThat(response.getOperationalRegionUuid()).isEqualTo(operationalRegion.toString()); + assertThat(response.getObservedRuntimeRoomKey()).isEqualTo(917L); + assertThat(response.getPrivateWorldInstanceKey()).isEqualTo(4L); + assertThat(response.getLifecycle().getCanonicalRequestBytes().toByteArray()) + .containsExactly(lifecycleRequest.canonicalBytes()); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(CanonicalInitialPlayerLocationGrpcCodec.MAX_REGION_RESPONSE_BYTES); + } + private static void assertInvalid(CanonicalInitialPlayerLocationRequest request) { assertThatThrownBy(() -> CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request)) .isInstanceOf(IllegalArgumentException.class); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java index 7c20a63750..06d11b00b1 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java @@ -12,6 +12,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; @@ -141,6 +142,54 @@ void retainedReadUsesTheStoredPlacementAndImmutableEntityReceiptOnly() { verifyNoInteractions(associations, holds, gameSession); } + @Test + void regionReadRequiresRetainedAppliedPlacementAndFreshExactEntityReceipt() { + var selection = CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request()); + var placement = + new Result( + Outcome.APPLIED, + null, + new RoomTemplateRef(TENANT, VERSION, uuid("abababab-abab-4bab-8bab-abababababab")), + 9182L, + new byte[] {1}, + "sha256:" + "a".repeat(64), + new byte[] {2}, + "sha256:" + "b".repeat(64), + true); + var location = mock(WorldCanonicalInitialPlayerLocationRepository.class); + when(location.readByOperationId( + eq(selection.placementOperationId()), any(RequestSelector.class))) + .thenReturn(Optional.of(placement)); + UUID canonicalRegion = uuid("abababab-abab-4bab-8bab-abababababac"); + UUID operationalRegion = uuid("abababab-abab-4bab-8bab-abababababaf"); + var lifecycle = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(lifecycle.operationalRegionAssignments()) + .thenReturn(Map.of(canonicalRegion, operationalRegion)); + var region = + new WorldCanonicalInitialPlayerLocationRepository.RegionResult( + placement, 77L, 9182L, canonicalRegion, operationalRegion, lifecycle); + when(location.readInitialPlayerLocationRegion(any(RequestSelector.class))) + .thenReturn(Optional.of(region)); + var holds = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var gameSession = mock(GameSessionCanonicalInitialAdmissionOwnerClient.class); + var entityReads = new AtomicInteger(); + var service = + service( + selection, + location, + holds, + gameSession, + ignored -> { + entityReads.incrementAndGet(); + return entityReceipt(selection); + }); + + assertThat(service.readRegion(selection)).contains(region); + assertThat(entityReads.get()).isEqualTo(1); + verify(location).readInitialPlayerLocationRegion(any(RequestSelector.class)); + verifyNoInteractions(holds, gameSession); + } + @Test void mismatchedEntityReceiptStopsBeforeHoldOrPlacementWrite() { var selection = CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request()); From 750f9548dba82887c56ad9d5f74ac8c2146c0409 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:50:48 +1300 Subject: [PATCH 02/36] Add qualified manual region leases and Entity runtime actor reference --- .../v1/preseeded_actor_assignment.proto | 29 + .../repository/CharacterRepository.java | 21 + ...eededActorRuntimeProjectionRepository.java | 70 +++ ...eseededActorAssignmentPeerInterceptor.java | 27 +- ...reseededActorAssignmentReceiptService.java | 6 + .../PreseededActorRuntimeReference.java | 20 + .../service/RuntimeEntityId.java | 10 + ...alPreseededActorAssignmentGrpcService.java | 61 ++ .../PreseededActorAssignmentGrpcCodec.java | 39 ++ ...22__preseeded_runtime_actor_projection.sql | 50 ++ ...eseededActorAssignmentIntegrationTest.java | 229 ++++++- ...nerCompositionPostgresIntegrationTest.java | 124 ++++ .../RetainedActorIdentityIntegrationTest.java | 16 +- ...haracterCreatePostgresIntegrationTest.java | 6 +- ...ntakeMigrationPostgresIntegrationTest.java | 2 +- ...dedActorAssignmentPeerInterceptorTest.java | 39 ++ ...eseededActorAssignmentGrpcServiceTest.java | 116 ++++ ...lPreseededActorRuntimeReferenceClient.java | 344 ++++++++++ .../CanonicalGameplayRegionRuntimeStatus.java | 102 +++ .../CanonicalGameplayRegionLeaseOwner.java | 234 +++++++ ...onicalGameplayRegionLeaseOwnerFactory.java | 36 ++ ...anonicalGameplayRegionLeaseRedisOwner.java | 313 ++++++++++ .../CanonicalGameplayRegionRedisKeys.java | 32 + ...GameplayRegionRuntimeStatusRepository.java | 324 ++++++++++ ...layRegionLeaseRedisScriptContribution.java | 60 ++ .../V1037__canonical_region_runtime_owner.sql | 58 ++ .../lua/game-session-region-lease-acquire.lua | 23 + .../lua/game-session-region-lease-read.lua | 14 + .../lua/game-session-region-lease-renew.lua | 18 + .../game-session-region-lease-acquire.json | 24 + .../game-session-region-lease-read.json | 22 + .../game-session-region-lease-renew.json | 22 + ...meplayRegionLeaseOwnerIntegrationTest.java | 590 ++++++++++++++++++ ...yRegionLeaseRedisOwnerIntegrationTest.java | 230 +++++++ ...untimeStatusRepositoryIntegrationTest.java | 342 ++++++++++ .../CanonicalGameplayRegionRedisKeysTest.java | 47 ++ ...edActorRuntimeReferenceClientMtlsTest.java | 235 +++++++ ...seededActorRuntimeReferenceClientTest.java | 224 +++++++ 38 files changed, 4143 insertions(+), 16 deletions(-) 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/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1037__canonical_region_runtime_owner.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeysTest.java 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 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/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..48ade7e6f9 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,19 @@ 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; /** * Unregistered method-guarded assignment write and immutable receipt read. Assignment delegates @@ -160,6 +164,63 @@ 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 (RuntimeException unavailable) { + 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..0ea0fa7404 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)) { @@ -1510,6 +1511,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/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..24e60180de 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 @@ -39,7 +39,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 +50,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 +520,118 @@ 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); + } + + 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 Status.Code errorCode; + private int terminalCount; + + @Override + public void onNext(ReadPreseededActorRuntimeReferenceResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).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/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java new file mode 100644 index 0000000000..101b7b331d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.gamesession.entity; + +import java.math.BigInteger; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; + +/** Durable owner row for one exact canonical tenant, game-instance, and operational region. */ +public record CanonicalGameplayRegionRuntimeStatus( + UUID tenantId, + UUID gameInstanceId, + UUID canonicalRegionId, + UUID regionId, + String tenantRegionTag, + long lifecycleEpoch, + long lifecycleRowVersion, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + UUID captureId, + String graphSha256, + String preparationInputDigest, + long regionEpoch, + BigInteger executorFence, + String leaseTokenCorrelation, + String ownerService, + String ownerInstanceId, + boolean paused, + String lastCommittedTickBatchId, + long lastCommittedTickId, + Instant updatedAt) { + public CanonicalGameplayRegionRuntimeStatus { + requireId(tenantId, "tenantId"); + requireId(gameInstanceId, "gameInstanceId"); + requireId(canonicalRegionId, "canonicalRegionId"); + requireId(regionId, "regionId"); + Objects.requireNonNull(tenantRegionTag, "tenantRegionTag"); + if (!tenantRegionTag.equals( + "r1-" + + tenantId.toString().replace("-", "") + + "-" + + gameInstanceId.toString().replace("-", "") + + "-" + + regionId.toString().replace("-", ""))) { + throw new IllegalArgumentException("tenantRegionTag must derive from the exact owner scope"); + } + requireId(captureId, "captureId"); + Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); + if (!tenantId.equals(lifecycleRequest.canonicalTenantId()) + || !gameInstanceId.equals(lifecycleRequest.canonicalGameInstanceId())) { + throw new IllegalArgumentException("lifecycleRequest belongs to another runtime target"); + } + requireDigest(graphSha256, "graphSha256"); + requirePrefixedDigest(preparationInputDigest, "preparationInputDigest"); + requirePositive(regionEpoch, "regionEpoch"); + Objects.requireNonNull(executorFence, "executorFence"); + if (executorFence.signum() <= 0) { + throw new IllegalArgumentException("executorFence must be positive"); + } + requireDigest(leaseTokenCorrelation, "leaseTokenCorrelation"); + requireText(ownerService, "ownerService"); + requireText(ownerInstanceId, "ownerInstanceId"); + if (lifecycleEpoch <= 0L || lifecycleRowVersion < 0L) { + throw new IllegalArgumentException("World lifecycle evidence is invalid"); + } + if (lastCommittedTickId < -1L) { + throw new IllegalArgumentException("lastCommittedTickId cannot precede the initial tick"); + } + Objects.requireNonNull(updatedAt, "updatedAt"); + } + + private static void requireId(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be lowercase SHA-256 hex"); + } + } + + private static void requirePrefixedDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be prefixed lowercase SHA-256 hex"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank() || !value.equals(value.trim())) { + throw new IllegalArgumentException(name + " must be nonblank canonical text"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) throw new IllegalArgumentException(name + " must be positive"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java new file mode 100644 index 0000000000..4cd92958a6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -0,0 +1,234 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Manually composed owner for an authenticated initial-placement region assignment. It installs and + * revalidates region ownership only; the region session-binding bridge remains unavailable until + * its typed runtime-entity identity source is supplied. + */ +final class CanonicalGameplayRegionLeaseOwner { + private final CanonicalGameplayBindingInventoryRepository bindingInventory; + private final CanonicalGameplayRegionRuntimeStatusRepository statusRepository; + private final CanonicalGameplayRegionLeaseRedisOwner redisOwner; + private final CanonicalInitialPlayerLocationRegionResolver worldRegionResolver; + private final RuntimeIdentity runtimeIdentity; + private final Duration leaseTtl; + private final Clock clock; + + CanonicalGameplayRegionLeaseOwner( + CanonicalGameplayBindingInventoryRepository bindingInventory, + CanonicalGameplayRegionRuntimeStatusRepository statusRepository, + CanonicalGameplayRegionLeaseRedisOwner redisOwner, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock) { + this.bindingInventory = Objects.requireNonNull(bindingInventory, "bindingInventory"); + this.statusRepository = Objects.requireNonNull(statusRepository, "statusRepository"); + this.redisOwner = Objects.requireNonNull(redisOwner, "redisOwner"); + this.worldRegionResolver = Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"); + this.runtimeIdentity = Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"); + this.leaseTtl = Objects.requireNonNull(leaseTtl, "leaseTtl"); + if (leaseTtl.isZero() || leaseTtl.isNegative()) { + throw new IllegalArgumentException("leaseTtl must be positive"); + } + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * Installs a new per-region durable executor fence under a live Redis grant. No bridge ACK or + * admission capability is returned by this operation. + */ + Installation installForTransition( + UUID transitionId, CanonicalInitialPlayerLocationRequest worldRequest) { + requireNoAmbientTransaction(); + Objects.requireNonNull(transitionId, "transitionId"); + Objects.requireNonNull(worldRequest, "worldRequest"); + CanonicalGameplayBindingProvisionalCasEvidence evidence = + readCurrentProvisionalEvidence(transitionId); + CanonicalGameplayRegionRuntimeStatusRepository.Source source = + resolveExactSource(worldRequest, evidence); + long expectedRegionEpoch = + exactExpectedRegionEpoch(evidence.candidate().identity().regionEpoch()); + CanonicalGameplayRegionRuntimeStatus prior = statusRepository.find(source).orElse(null); + if (prior == null && expectedRegionEpoch != 1L) throw unavailable(); + if (prior != null && prior.regionEpoch() != expectedRegionEpoch) throw unavailable(); + + CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant = + redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); + redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); + CanonicalGameplayRegionRuntimeStatusRepository.Source afterAcquire = + resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); + requireSameSource(source, afterAcquire); + redisOwner.renew(grant, leaseTtl); + redisOwner.requireCurrent(grant); + + Instant installedAt = clock.instant(); + CanonicalGameplayRegionRuntimeStatus installed = + statusRepository.installOwner( + source, + expectedRegionEpoch, + prior, + grant.tokenCorrelation(), + grant.ownerService(), + grant.ownerInstanceId(), + installedAt); + + redisOwner.requireCurrent(grant); + CanonicalGameplayRegionRuntimeStatus observed = + statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); + if (!installed.equals(observed) || observed.paused()) throw unavailable(); + CanonicalGameplayRegionRuntimeStatusRepository.Source afterInstall = + resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); + requireSameSource(source, afterInstall); + redisOwner.requireCurrent(grant); + return new Installation(transitionId, worldRequest, evidence, source, grant, installed); + } + + /** + * Revalidates the same SQL source, World assignment and acquired lease before any later bridge. + */ + void revalidateBeforeBridge(Installation installation) { + requireNoAmbientTransaction(); + Objects.requireNonNull(installation, "installation"); + if (!installation.owner.equals(this)) throw unavailable(); + CanonicalGameplayBindingProvisionalCasEvidence evidence = + readCurrentProvisionalEvidence(installation.transitionId); + if (!installation.evidence.equals(evidence)) throw unavailable(); + CanonicalGameplayRegionRuntimeStatusRepository.Source currentSource = + resolveExactSource(installation.worldRequest, evidence); + requireSameSource(installation.source, currentSource); + redisOwner.renew(installation.grant, leaseTtl); + CanonicalGameplayRegionRuntimeStatus current = + statusRepository + .find(currentSource) + .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); + if (!installation.status.equals(current) || current.paused()) throw unavailable(); + redisOwner.requireCurrent(installation.grant); + } + + private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvidence( + UUID transitionId) { + requireNoAmbientTransaction(); + CanonicalGameplayBindingProvisionalCasEvidence evidence = + bindingInventory.readProvisionalCasEvidence(transitionId); + if (evidence.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || evidence.candidate().lifecycle() + != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL + || !evidence.transition().transitionId().equals(transitionId) + || !evidence.candidate().transitionId().equals(transitionId)) { + throw unavailable(); + } + return evidence; + } + + private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveExactSource( + CanonicalInitialPlayerLocationRequest request, + CanonicalGameplayBindingProvisionalCasEvidence evidence) { + requireNoAmbientTransaction(); + var identity = evidence.candidate().identity(); + var target = request.getExpectedTarget(); + if (!identity.accountId().toString().equals(request.getCanonicalAccountUuid()) + || !identity.characterId().toString().equals(request.getCharacterUuid()) + || !identity.tenantId().toString().equals(target.getCanonicalTenantUuid()) + || !identity.gameInstanceId().toString().equals(target.getGameInstanceId()) + || !identity + .playableStateNamespaceId() + .toString() + .equals(target.getPlayableStateNamespaceUuid()) + || !"SHARED".equals(identity.playableStateScope())) { + throw unavailable(); + } + + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolved = + worldRegionResolver.resolve(request); + var assignment = resolved.lifecycleAssignment(); + if (!identity.tenantId().equals(assignment.request().canonicalTenantId()) + || !identity.gameInstanceId().equals(assignment.request().canonicalGameInstanceId()) + || !identity.regionId().equals(assignment.operationalRegionId())) { + throw unavailable(); + } + return new CanonicalGameplayRegionRuntimeStatusRepository.Source( + identity.tenantId(), + identity.gameInstanceId(), + assignment.canonicalRegionId(), + assignment.operationalRegionId(), + assignment.lifecycleEpoch(), + assignment.lifecycleRowVersion(), + assignment.request(), + assignment.captureId(), + assignment.graphSha256(), + assignment.preparationInputDigest()); + } + + private static long exactExpectedRegionEpoch(BigInteger value) { + Objects.requireNonNull(value, "regionEpoch"); + try { + long result = value.longValueExact(); + if (result <= 0L) throw unavailable(); + return result; + } catch (ArithmeticException invalid) { + throw unavailable(); + } + } + + private static void requireSameSource( + CanonicalGameplayRegionRuntimeStatusRepository.Source expected, + CanonicalGameplayRegionRuntimeStatusRepository.Source actual) { + if (!expected.equals(actual)) throw unavailable(); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Canonical Game Session region owner requires current exact assignment and lease evidence"); + } + + /** Private construction prevents caller-created installation/readback objects. */ + final class Installation { + private final CanonicalGameplayRegionLeaseOwner owner; + private final UUID transitionId; + private final CanonicalInitialPlayerLocationRequest worldRequest; + private final CanonicalGameplayBindingProvisionalCasEvidence evidence; + private final CanonicalGameplayRegionRuntimeStatusRepository.Source source; + private final CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; + private final CanonicalGameplayRegionRuntimeStatus status; + + private Installation( + UUID transitionId, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatus status) { + this.owner = CanonicalGameplayRegionLeaseOwner.this; + this.transitionId = transitionId; + this.worldRequest = worldRequest; + this.evidence = evidence; + this.source = source; + this.grant = grant; + this.status = status; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java new file mode 100644 index 0000000000..957244c0f4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.time.Clock; +import java.time.Duration; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import org.jooq.DSLContext; + +/** Explicit manual composition; this factory is not registered with Spring or a default path. */ +final class CanonicalGameplayRegionLeaseOwnerFactory { + private CanonicalGameplayRegionLeaseOwnerFactory() {} + + static CanonicalGameplayRegionLeaseOwner compose( + DSLContext dsl, + RedisClient coordinationRedis, + RedisScriptCatalog scriptCatalog, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock) { + Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(coordinationRedis, "coordinationRedis"); + Objects.requireNonNull(scriptCatalog, "scriptCatalog"); + return new CanonicalGameplayRegionLeaseOwner( + new CanonicalGameplayBindingInventoryRepository(dsl), + new CanonicalGameplayRegionRuntimeStatusRepository(dsl), + new CanonicalGameplayRegionLeaseRedisOwner(coordinationRedis, scriptCatalog), + Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"), + Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"), + Objects.requireNonNull(leaseTtl, "leaseTtl"), + Objects.requireNonNull(clock, "clock")); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java new file mode 100644 index 0000000000..c193baaef9 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -0,0 +1,313 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Duration; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Manually composed region lease using the exact full-scope key, registered Lua, and readback. */ +final class CanonicalGameplayRegionLeaseRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String SCHEMA = "gs_region_lease/v1"; + private static final int MAX_SCRIPT_BYTES = 16 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000L; + private static final List LEASE_ARGUMENTS = List.of("schema", "token", "leaseTtlMs"); + private static final List READ_ARGUMENTS = List.of("schema", "token"); + private static final List EXPECTED_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "regionLease", + "tick-executor-lease:", + RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + + private final RedisClient redisClient; + private final RedisScriptCatalog catalog; + + CanonicalGameplayRegionLeaseRedisOwner(RedisClient redisClient, RedisScriptCatalog catalog) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Coordination Redis client"); + this.catalog = Objects.requireNonNull(catalog, "Installed region lease script catalog"); + } + + LeaseGrant acquire( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + long regionEpoch, + Duration leaseTtl, + RuntimeIdentity identity) { + requireNoAmbientTransaction(); + Objects.requireNonNull(source, "source"); + requirePositive(regionEpoch, "regionEpoch"); + long ttlMillis = ttlMillis(leaseTtl); + String ownerService = requireOwnerService(identity); + String ownerInstance = requireOwnerInstance(identity); + String token = UUID.randomUUID().toString(); + LeaseGrant grant = new LeaseGrant(source, regionEpoch, token, ownerService, ownerInstance); + long outcome = + execute( + CanonicalGameplayRegionLeaseRedisScriptContribution.ACQUIRE_ID, + CanonicalGameplayRegionLeaseRedisScriptContribution.ACQUIRE_PATH, + LEASE_ARGUMENTS, + grant, + ttlMillis, + true); + if (outcome != 1L && outcome != 2L) { + throw unavailable(new IllegalStateException("Region lease acquire outcome was " + outcome)); + } + return grant; + } + + void requireGrantScope( + LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + long regionEpoch, + RuntimeIdentity identity) { + Objects.requireNonNull(grant, "grant"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(identity, "runtimeIdentity"); + if (!grant.source.equals(source) + || grant.regionEpoch != regionEpoch + || !grant.ownerService.equals(requireOwnerService(identity)) + || !grant.ownerInstanceId.equals(requireOwnerInstance(identity))) { + throw unavailable(); + } + } + + void renew(LeaseGrant grant, Duration leaseTtl) { + requireNoAmbientTransaction(); + long outcome = + execute( + CanonicalGameplayRegionLeaseRedisScriptContribution.RENEW_ID, + CanonicalGameplayRegionLeaseRedisScriptContribution.RENEW_PATH, + LEASE_ARGUMENTS, + Objects.requireNonNull(grant, "grant"), + ttlMillis(leaseTtl), + true); + if (outcome != 1L) throw unavailable(); + } + + void requireCurrent(LeaseGrant grant) { + requireNoAmbientTransaction(); + long outcome = + execute( + CanonicalGameplayRegionLeaseRedisScriptContribution.READ_ID, + CanonicalGameplayRegionLeaseRedisScriptContribution.READ_PATH, + READ_ARGUMENTS, + Objects.requireNonNull(grant, "grant"), + 0L, + false); + if (outcome != 1L) throw unavailable(); + } + + private long execute( + String scriptId, + String resourcePath, + List expectedArguments, + LeaseGrant grant, + long ttlMillis, + boolean includeTtl) { + RedisScriptDescriptor descriptor = requireDescriptor(scriptId, resourcePath, expectedArguments); + byte[] source = scriptSource(descriptor); + byte[] key = ascii(grant.key()); + byte[][] arguments = grant.arguments(includeTtl ? ttlMillis : null); + if (arguments.length != expectedArguments.size()) throw unavailable(); + return executeInteger(source, key, arguments); + } + + private long executeInteger(byte[] script, byte[] key, byte[][] arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = connection.async(); + requirePrincipal(await(commands.aclWhoami())); + String loadedSha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); + Long result = + await( + commands.evalsha(loadedSha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (result == null) throw unavailable(); + return result; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private RedisScriptDescriptor requireDescriptor( + String id, String resourcePath, List arguments) { + try { + RedisScriptDescriptor descriptor = catalog.require(id); + if (!id.equals(descriptor.scriptId()) + || !resourcePath.equals(descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.TICK_LOCK + || !EXPECTED_KEYS.equals(descriptor.keys()) + || !arguments.equals( + descriptor.arguments().stream() + .map(RedisScriptDescriptor.ArgumentSpec::name) + .toList())) { + throw unavailable(); + } + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayRegionLeaseRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] source = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (source.length == 0 + || source.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", source))) { + throw unavailable(); + } + return source; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static long ttlMillis(Duration duration) { + Objects.requireNonNull(duration, "leaseTtl"); + long millis; + try { + millis = duration.toMillis(); + } catch (ArithmeticException overflow) { + throw unavailable(overflow); + } + if (millis <= 0L) throw unavailable(); + return millis; + } + + private static String requireOwnerService(RuntimeIdentity identity) { + Objects.requireNonNull(identity, "runtimeIdentity"); + if (!"game-session-service".equals(identity.service())) throw unavailable(); + return identity.service(); + } + + private static String requireOwnerInstance(RuntimeIdentity identity) { + String value = identity.serviceInstanceId(); + if (value == null || value.isBlank() || !value.equals(value.trim()) || value.length() > 120) { + throw unavailable(); + } + return value; + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static T await(RedisFuture future) { + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException | RuntimeException failure) { + future.cancel(true); + throw unavailable(failure); + } + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception impossible) { + throw unavailable(impossible); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable(); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) throw new IllegalArgumentException(name + " must be positive"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Canonical Game Session region lease is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("Canonical Game Session region lease is unavailable", cause); + } + + /** Ephemeral opaque grant; its token never appears in string form, SQL, or returned evidence. */ + static final class LeaseGrant { + private final CanonicalGameplayRegionRuntimeStatusRepository.Source source; + private final long regionEpoch; + private final String token; + private final String ownerService; + private final String ownerInstanceId; + private final String key; + + private LeaseGrant( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + long regionEpoch, + String token, + String ownerService, + String ownerInstanceId) { + this.source = Objects.requireNonNull(source, "source"); + this.regionEpoch = regionEpoch; + this.token = Objects.requireNonNull(token, "token"); + this.ownerService = Objects.requireNonNull(ownerService, "ownerService"); + this.ownerInstanceId = Objects.requireNonNull(ownerInstanceId, "ownerInstanceId"); + this.key = + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId()); + } + + String tokenCorrelation() { + return digest("SHA-256", ascii(token)); + } + + String ownerService() { + return ownerService; + } + + String ownerInstanceId() { + return ownerInstanceId; + } + + private byte[][] arguments(Long ttlMillis) { + if (ttlMillis == null) return new byte[][] {ascii(SCHEMA), ascii(token)}; + return new byte[][] {ascii(SCHEMA), ascii(token), ascii(ttlMillis.toString())}; + } + + String key() { + return key; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java new file mode 100644 index 0000000000..a58e6ae01e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.UUID; + +/** Exact region-scoped coordination keys for the manually composed region owner. */ +final class CanonicalGameplayRegionRedisKeys { + private CanonicalGameplayRegionRedisKeys() {} + + static String tenantRegionTag(UUID tenantId, UUID gameInstanceId, UUID regionId) { + requireCanonicalId(tenantId, "tenantId"); + requireCanonicalId(gameInstanceId, "gameInstanceId"); + requireCanonicalId(regionId, "regionId"); + return "r1-" + + tenantId.toString().replace("-", "") + + "-" + + gameInstanceId.toString().replace("-", "") + + "-" + + regionId.toString().replace("-", ""); + } + + static String lease(UUID tenantId, UUID gameInstanceId, UUID regionId) { + return "tick-executor-lease:{" + tenantRegionTag(tenantId, gameInstanceId, regionId) + "}"; + } + + private static void requireCanonicalId(UUID id, String name) { + Objects.requireNonNull(id, name); + if (id.equals(new UUID(0L, 0L)) || !UUID.fromString(id.toString()).equals(id)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java new file mode 100644 index 0000000000..e8bcd5504d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -0,0 +1,324 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Durable region timeline and owner-fence persistence, separate from the instance status row. */ +final class CanonicalGameplayRegionRuntimeStatusRepository { + private static final String TABLE = "game_session_region_runtime_status"; + private static final String FENCE_SEQUENCE = "game_session_region_executor_fence_seq"; + private final DSLContext dsl; + + CanonicalGameplayRegionRuntimeStatusRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + Optional find(Source source) { + requireNoAmbientTransaction(); + Objects.requireNonNull(source, "source"); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + if (row == null) return Optional.empty(); + CanonicalGameplayRegionRuntimeStatus status = toStatus(row); + if (!matchesSource(status, source) + || !CanonicalGameplayRegionRedisKeys.tenantRegionTag( + status.tenantId(), status.gameInstanceId(), status.regionId()) + .equals(status.tenantRegionTag())) { + throw unavailable(); + } + return Optional.of(status); + } + + /** Installs a new durable fence for an already acquired and source-bound Redis grant. */ + CanonicalGameplayRegionRuntimeStatus installOwner( + Source source, + long expectedRegionEpoch, + CanonicalGameplayRegionRuntimeStatus prior, + String leaseTokenCorrelation, + String ownerService, + String ownerInstanceId, + Instant now) { + requireNoAmbientTransaction(); + Objects.requireNonNull(source, "source"); + requireDigest(leaseTokenCorrelation); + requireText(ownerService); + requireText(ownerInstanceId); + Objects.requireNonNull(now, "now"); + if (expectedRegionEpoch <= 0L) throw unavailable(); + if ((prior == null && expectedRegionEpoch != 1L) + || (prior != null + && (prior.regionEpoch() != expectedRegionEpoch || !matchesSource(prior, source)))) { + throw unavailable(); + } + String expectedTag = + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId()); + if (prior != null && !expectedTag.equals(prior.tenantRegionTag())) throw unavailable(); + + try { + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + String scopeLockKey = "game-session-region-owner-install:v1:" + expectedTag; + transaction.fetch("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", scopeLockKey); + Record currentRow = + transaction.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + CanonicalGameplayRegionRuntimeStatus current = + currentRow == null ? null : toStatus(currentRow); + if (current != null) { + if (!matchesSource(current, source) + || !expectedTag.equals(current.tenantRegionTag())) { + throw unavailable(); + } + if (current.leaseTokenCorrelation().equals(leaseTokenCorrelation)) { + if (matchesLeaseGeneration( + current, + expectedRegionEpoch, + leaseTokenCorrelation, + ownerService, + ownerInstanceId)) { + return current; + } + throw unavailable(); + } + if (prior == null || !current.equals(prior)) throw unavailable(); + } else if (prior != null || expectedRegionEpoch != 1L) { + throw unavailable(); + } + + Record fenceRow = + transaction.fetchOne("SELECT nextval('" + FENCE_SEQUENCE + "') AS fence"); + Long fence = fenceRow == null ? null : fenceRow.get("fence", Long.class); + if (fence == null || fence <= 0L) throw unavailable(); + Record installed; + if (current == null) { + if (expectedRegionEpoch != 1L) throw unavailable(); + installed = + transaction.fetchOne( + "INSERT INTO " + + TABLE + + " (tenant_id, game_instance_id, canonical_region_id, region_id," + + " tenant_region_tag, lifecycle_epoch, lifecycle_row_version, capture_id," + + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," + + " region_epoch, executor_fence," + + " lease_token_correlation, owner_service, owner_instance_id, paused," + + " last_committed_tick_id, updated_at)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?)" + + " ON CONFLICT (tenant_id, game_instance_id, region_id) DO NOTHING" + + " RETURNING *", + source.tenantId(), + source.gameInstanceId(), + source.canonicalRegionId(), + source.regionId(), + expectedTag, + source.lifecycleEpoch(), + source.lifecycleRowVersion(), + source.captureId(), + source.lifecycleRequest().canonicalBytes(), + source.graphSha256(), + source.preparationInputDigest(), + fence, + leaseTokenCorrelation, + ownerService, + ownerInstanceId, + localDateTime(now)); + } else { + installed = + transaction.fetchOne( + "UPDATE " + + TABLE + + " SET executor_fence = ?, lease_token_correlation = ?," + + " owner_service = ?, owner_instance_id = ?, updated_at = ?" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " AND tenant_region_tag = ? AND canonical_region_id = ?" + + " AND lifecycle_epoch = ? AND lifecycle_row_version = ?" + + " AND capture_id = ? AND lifecycle_request_bytes = ?" + + " AND graph_sha256 = ?" + + " AND preparation_input_digest = ? AND region_epoch = ?" + + " AND executor_fence = ? AND lease_token_correlation = ?" + + " AND owner_service = ? AND owner_instance_id = ? AND paused = ?" + + " AND last_committed_tick_id = ?" + + " AND last_committed_tick_batch_id IS NOT DISTINCT FROM ?" + + " RETURNING *", + fence, + leaseTokenCorrelation, + ownerService, + ownerInstanceId, + localDateTime(now), + current.tenantId(), + current.gameInstanceId(), + current.regionId(), + current.tenantRegionTag(), + current.canonicalRegionId(), + current.lifecycleEpoch(), + current.lifecycleRowVersion(), + current.captureId(), + current.lifecycleRequest().canonicalBytes(), + current.graphSha256(), + current.preparationInputDigest(), + current.regionEpoch(), + current.executorFence().longValueExact(), + current.leaseTokenCorrelation(), + current.ownerService(), + current.ownerInstanceId(), + current.paused(), + current.lastCommittedTickId(), + current.lastCommittedTickBatchId()); + } + if (installed == null) throw unavailable(); + CanonicalGameplayRegionRuntimeStatus result = toStatus(installed); + if (!matchesSource(result, source) + || result.regionEpoch() != expectedRegionEpoch + || !result.executorFence().equals(BigInteger.valueOf(fence)) + || !result.leaseTokenCorrelation().equals(leaseTokenCorrelation) + || !result.tenantRegionTag().equals(expectedTag)) { + throw unavailable(); + } + return result; + }); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static CanonicalGameplayRegionRuntimeStatus toStatus(Record row) { + return new CanonicalGameplayRegionRuntimeStatus( + row.get("tenant_id", UUID.class), + row.get("game_instance_id", UUID.class), + row.get("canonical_region_id", UUID.class), + row.get("region_id", UUID.class), + row.get("tenant_region_tag", String.class), + row.get("lifecycle_epoch", Long.class), + row.get("lifecycle_row_version", Long.class), + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored( + row.get("lifecycle_request_bytes", byte[].class)), + row.get("capture_id", UUID.class), + row.get("graph_sha256", String.class), + row.get("preparation_input_digest", String.class), + row.get("region_epoch", Long.class), + BigInteger.valueOf(row.get("executor_fence", Long.class)), + row.get("lease_token_correlation", String.class), + row.get("owner_service", String.class), + row.get("owner_instance_id", String.class), + Boolean.TRUE.equals(row.get("paused", Boolean.class)), + row.get("last_committed_tick_batch_id", String.class), + row.get("last_committed_tick_id", Long.class), + row.get("updated_at", LocalDateTime.class).toInstant(ZoneOffset.UTC)); + } + + private static boolean matchesSource(CanonicalGameplayRegionRuntimeStatus status, Source source) { + return status.tenantId().equals(source.tenantId()) + && status.gameInstanceId().equals(source.gameInstanceId()) + && status.canonicalRegionId().equals(source.canonicalRegionId()) + && status.regionId().equals(source.regionId()) + && status.lifecycleEpoch() == source.lifecycleEpoch() + && status.lifecycleRowVersion() == source.lifecycleRowVersion() + && status.lifecycleRequest().equals(source.lifecycleRequest()) + && status.captureId().equals(source.captureId()) + && status.graphSha256().equals(source.graphSha256()) + && status.preparationInputDigest().equals(source.preparationInputDigest()); + } + + private static boolean matchesLeaseGeneration( + CanonicalGameplayRegionRuntimeStatus status, + long regionEpoch, + String leaseTokenCorrelation, + String ownerService, + String ownerInstanceId) { + return status.regionEpoch() == regionEpoch + && status.leaseTokenCorrelation().equals(leaseTokenCorrelation) + && status.ownerService().equals(ownerService) + && status.ownerInstanceId().equals(ownerInstanceId); + } + + private static LocalDateTime localDateTime(Instant instant) { + return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); + } + + private static void requireDigest(String value) { + if (value == null || !value.matches("[0-9a-f]{64}")) throw unavailable(); + } + + private static void requirePrefixedDigest(String value) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) throw unavailable(); + } + + private static void requireText(String value) { + if (value == null || value.isBlank() || !value.equals(value.trim())) throw unavailable(); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Canonical Game Session region ownership is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException( + "Canonical Game Session region ownership is unavailable", cause); + } + + /** Fresh authenticated World assignment supplied by the closed resolver, never caller fields. */ + record Source( + UUID tenantId, + UUID gameInstanceId, + UUID canonicalRegionId, + UUID regionId, + long lifecycleEpoch, + long lifecycleRowVersion, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + UUID captureId, + String graphSha256, + String preparationInputDigest) { + Source { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(gameInstanceId, "gameInstanceId"); + Objects.requireNonNull(canonicalRegionId, "canonicalRegionId"); + Objects.requireNonNull(regionId, "regionId"); + Objects.requireNonNull(captureId, "captureId"); + Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); + requireNonNil(canonicalRegionId); + requireNonNil(captureId); + CanonicalGameplayRegionRedisKeys.tenantRegionTag(tenantId, gameInstanceId, regionId); + if (!tenantId.equals(lifecycleRequest.canonicalTenantId()) + || !gameInstanceId.equals(lifecycleRequest.canonicalGameInstanceId())) { + throw unavailable(); + } + requireDigest(graphSha256); + requirePrefixedDigest(preparationInputDigest); + if (lifecycleEpoch <= 0L || lifecycleRowVersion < 0L) throw unavailable(); + } + } + + private static void requireNonNil(UUID value) { + if (value.equals(new UUID(0L, 0L))) throw unavailable(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java new file mode 100644 index 0000000000..fd2e684b36 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive descriptor contribution for the manually composed region lease scripts. */ +public final class CanonicalGameplayRegionLeaseRedisScriptContribution + implements RedisScriptContribution { + public static final String ACQUIRE_ID = "game-session.region-lease-acquire.v1"; + public static final String RENEW_ID = "game-session.region-lease-renew.v1"; + public static final String READ_ID = "game-session.region-lease-read.v1"; + public static final String ACQUIRE_PATH = "redis/lua/game-session-region-lease-acquire.lua"; + public static final String RENEW_PATH = "redis/lua/game-session-region-lease-renew.lua"; + public static final String READ_PATH = "redis/lua/game-session-region-lease-read.lua"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + return List.of( + read("/redis/scripts/game-session-region-lease-acquire.json", ACQUIRE_ID), + read("/redis/scripts/game-session-region-lease-renew.json", RENEW_ID), + read("/redis/scripts/game-session-region-lease-read.json", READ_ID)); + } + + private RedisScriptDescriptor read(String path, String id) { + try (InputStream input = getClass().getResourceAsStream(path)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !id.equals(descriptor.scriptId())) { + throw unavailable(); + } + return descriptor; + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Canonical region lease descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1037__canonical_region_runtime_owner.sql b/services/game-session-service/src/main/resources/db/migration/V1037__canonical_region_runtime_owner.sql new file mode 100644 index 0000000000..e46f49ef61 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1037__canonical_region_runtime_owner.sql @@ -0,0 +1,58 @@ +CREATE SEQUENCE game_session_region_executor_fence_seq + AS bigint + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + NO CYCLE; + +CREATE TABLE game_session_region_runtime_status ( + tenant_id uuid NOT NULL, + game_instance_id uuid NOT NULL, + canonical_region_id uuid NOT NULL, + region_id uuid NOT NULL, + tenant_region_tag character varying(104) NOT NULL, + lifecycle_epoch bigint NOT NULL, + lifecycle_row_version bigint NOT NULL, + lifecycle_request_bytes bytea NOT NULL, + capture_id uuid NOT NULL, + graph_sha256 character varying(64) NOT NULL, + preparation_input_digest character varying(71) NOT NULL, + region_epoch bigint NOT NULL, + executor_fence bigint NOT NULL, + lease_token_correlation character varying(64) NOT NULL, + owner_service character varying(80) NOT NULL, + owner_instance_id character varying(120) NOT NULL, + paused boolean NOT NULL, + last_committed_tick_batch_id character varying(64), + last_committed_tick_id bigint NOT NULL, + updated_at timestamp without time zone NOT NULL, + CONSTRAINT pk_game_session_region_runtime_status + PRIMARY KEY (tenant_id, game_instance_id, region_id), + CONSTRAINT ux_game_session_region_runtime_tenant_tag + UNIQUE (tenant_region_tag), + CONSTRAINT ux_game_session_region_runtime_executor_fence + UNIQUE (executor_fence), + CONSTRAINT ck_game_session_region_runtime_ids CHECK ( + tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND capture_id <> '00000000-0000-0000-0000-000000000000'::uuid), + CONSTRAINT ck_game_session_region_runtime_tag CHECK ( + tenant_region_tag ~ '^r1-[0-9a-f]{32}-[0-9a-f]{32}-[0-9a-f]{32}$'), + CONSTRAINT ck_game_session_region_runtime_world_source CHECK ( + lifecycle_epoch > 0 + AND lifecycle_row_version >= 0 + AND octet_length(lifecycle_request_bytes) BETWEEN 1 AND 4096 + AND graph_sha256 ~ '^[0-9a-f]{64}$' + AND preparation_input_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_game_session_region_runtime_fence CHECK ( + region_epoch > 0 + AND executor_fence > 0 + AND lease_token_correlation ~ '^[0-9a-f]{64}$'), + CONSTRAINT ck_game_session_region_runtime_owner CHECK ( + owner_service <> '' + AND owner_instance_id <> '' + AND last_committed_tick_id >= -1) +); diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua new file mode 100644 index 0000000000..ee0ef12cf4 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua @@ -0,0 +1,23 @@ +-- The region lease contains only its opaque liveness token and Redis TTL. +local key = KEYS[1] +if #KEYS ~= 1 or #ARGV ~= 3 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end +local token = ARGV[2] +local ttl = ARGV[3] +if not string.match(ttl, '^[1-9][0-9]*$') or string.len(ttl) > 19 + or (string.len(ttl) == 19 and ttl > '9223372036854775807') then return -1 end +if string.len(token) ~= 36 + or string.sub(token, 9, 9) ~= '-' + or string.sub(token, 14, 14) ~= '-' + or string.sub(token, 19, 19) ~= '-' + or string.sub(token, 24, 24) ~= '-' + or not string.match(string.gsub(token, '%-', ''), '^[0-9a-f]+$') then return -1 end +local keyType = redis.call('TYPE', key).ok +if keyType ~= 'none' and keyType ~= 'string' then return -2 end +if keyType == 'string' then + if redis.call('PTTL', key) <= 0 then return 0 end + if redis.call('GET', key) == token then return 2 end + return 0 +end +local result = redis.call('SET', key, token, 'PX', ttl, 'NX') +if result and result.ok == 'OK' then return 1 end +return 0 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua new file mode 100644 index 0000000000..0059a7d190 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua @@ -0,0 +1,14 @@ +-- Exact atomic readback for one live opaque liveness token. +local key = KEYS[1] +if #KEYS ~= 1 or #ARGV ~= 2 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end +local token = ARGV[2] +if string.len(token) ~= 36 + or string.sub(token, 9, 9) ~= '-' + or string.sub(token, 14, 14) ~= '-' + or string.sub(token, 19, 19) ~= '-' + or string.sub(token, 24, 24) ~= '-' + or not string.match(string.gsub(token, '%-', ''), '^[0-9a-f]+$') then return -1 end +local keyType = redis.call('TYPE', key).ok +if keyType ~= 'string' or redis.call('PTTL', key) <= 0 + or redis.call('GET', key) ~= token then return 0 end +return 1 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua new file mode 100644 index 0000000000..b9a8939717 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua @@ -0,0 +1,18 @@ +-- Extends only the exact opaque liveness token and never advances the durable executor fence. +local key = KEYS[1] +if #KEYS ~= 1 or #ARGV ~= 3 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end +local token = ARGV[2] +local ttl = ARGV[3] +if string.len(token) ~= 36 + or string.sub(token, 9, 9) ~= '-' + or string.sub(token, 14, 14) ~= '-' + or string.sub(token, 19, 19) ~= '-' + or string.sub(token, 24, 24) ~= '-' + or not string.match(string.gsub(token, '%-', ''), '^[0-9a-f]+$') then return -1 end +if not string.match(ttl, '^[1-9][0-9]*$') or string.len(ttl) > 19 + or (string.len(ttl) == 19 and ttl > '9223372036854775807') then return -1 end +local keyType = redis.call('TYPE', key).ok +if keyType ~= 'string' or redis.call('PTTL', key) <= 0 + or redis.call('GET', key) ~= token then return 0 end +redis.call('PEXPIRE', key, ttl) +return 1 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json new file mode 100644 index 0000000000..5dc87d52af --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json @@ -0,0 +1,24 @@ +{ + "scriptId": "game-session.region-lease-acquire.v1", + "resourcePath": "redis/lua/game-session-region-lease-acquire.lua", + "sha256": "69aa93ce55c5ade188e60bfe71f21c7f54c569016d845abf79e0887999bc8b9d", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [{"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}], + "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "leaseTtlMs"}], + "category": "TICK_LOCK", + "outcomes": [ + {"code": "LEASE_ACQUIRED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "LEASE_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "LEASE_BUSY", "category": "CONTENTION", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "TYPE_OR_LEASE_STATE_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "REGION", + "lossClass": "STAGED_EFFECT_OR_RETRY", + "tailLossBehavior": "Lease loss or expiry ends the current owner attempt. The durable region timeline remains authoritative and a successor must acquire a new lease, install a new durable fence, and revalidate that exact grant before any bridge or tick work.", + "compatibilityLevel": "COMPATIBLE", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "none"}], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json new file mode 100644 index 0000000000..1a46ba2ca0 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json @@ -0,0 +1,22 @@ +{ + "scriptId": "game-session.region-lease-read.v1", + "resourcePath": "redis/lua/game-session-region-lease-read.lua", + "sha256": "564267ce5acd15cab89ade66466e5d1b959aaadee432cc20ec097915e138acf0", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [{"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}], + "arguments": [{"name": "schema"}, {"name": "token"}], + "category": "TICK_LOCK", + "outcomes": [ + {"code": "LEASE_CURRENT", "category": "SUCCESS", "effect": "NON_MUTATING"}, + {"code": "STALE_OR_EXPIRED", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "REGION", + "lossClass": "STAGED_EFFECT_OR_RETRY", + "tailLossBehavior": "Only exact physical readback of the live grant may support later owner checks. Missing or mismatched fields fail closed; lease possession is not a substitute for the durable executor fence or World assignment.", + "compatibilityLevel": "COMPATIBLE", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "none"}], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json new file mode 100644 index 0000000000..015ecf7a66 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json @@ -0,0 +1,22 @@ +{ + "scriptId": "game-session.region-lease-renew.v1", + "resourcePath": "redis/lua/game-session-region-lease-renew.lua", + "sha256": "322963204c4d5290fa31354dd71c2d20d3dd9f2185deb4644185427345eee4f4", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [{"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}], + "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "leaseTtlMs"}], + "category": "TICK_LOCK", + "outcomes": [ + {"code": "LEASE_RENEWED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "STALE_OR_EXPIRED", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "REGION", + "lossClass": "STAGED_EFFECT_OR_RETRY", + "tailLossBehavior": "Renewal compares the exact grant, scope, source, owner, and epoch. A missing, expired, or changed lease does not renew and ends the current owner attempt; renewal never advances the durable executor fence.", + "compatibilityLevel": "COMPATIBLE", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "none"}], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java new file mode 100644 index 0000000000..e1a3a42ac0 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -0,0 +1,590 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClient; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.gamesession.service.CanonicalRegionBootstrapAssignmentResolver; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Controlled source protocol proof; fixture World evidence is not production activation proof. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayRegionLeaseOwnerIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String PASSWORD = UUID.randomUUID().toString(); + private static final int REDIS_PORT = 6379; + private static final UUID TRANSITION_ID = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID ACCOUNT_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID CHARACTER_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID CANONICAL_REGION_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OPERATIONAL_REGION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final Instant NOW = Instant.parse("2026-10-26T00:00:00Z"); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(REDIS_PORT); + + @Test + void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + DriverManagerDataSource dataSource = dataSource(); + Flyway.configure() + .dataSource(dataSource) + .locations( + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(dsl); + + try (RedisFixture redis = RedisFixture.open()) { + var redisOwner = + new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + WorldFixture world = WorldFixture.open(); + var bindingEvidence = provisionalEvidence(world.request()); + var bindingInventory = mock(CanonicalGameplayBindingInventoryRepository.class); + when(bindingInventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(bindingEvidence); + + var firstOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-a"); + var qualifiedSource = source(world.originalEvidence()); + byte[] redisKey = + ascii( + CanonicalGameplayRegionRedisKeys.lease( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId())); + + try { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(redis.admin().type(redisKey)).isEqualTo("none"); + assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + + var wrongTargetInventory = mock(CanonicalGameplayBindingInventoryRepository.class); + var wrongTargetEvidence = + provisionalEvidence( + world.request(), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + BigInteger.ONE); + when(wrongTargetInventory.readProvisionalCasEvidence(TRANSITION_ID)) + .thenReturn(wrongTargetEvidence); + var wrongTargetOwner = + owner(wrongTargetInventory, statusRepository, redisOwner, world, "wrong-target"); + assertThatThrownBy( + () -> wrongTargetOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().type(redisKey)).isEqualTo("none"); + assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + + var wrongEpochInventory = mock(CanonicalGameplayBindingInventoryRepository.class); + var wrongEpochEvidence = + provisionalEvidence(world.request(), qualifiedSource.tenantId(), BigInteger.TWO); + when(wrongEpochInventory.readProvisionalCasEvidence(TRANSITION_ID)) + .thenReturn(wrongEpochEvidence); + var wrongEpochOwner = + owner(wrongEpochInventory, statusRepository, redisOwner, world, "wrong-epoch"); + assertThatThrownBy(() -> wrongEpochOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().type(redisKey)).isEqualTo("none"); + assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(redis.admin().type(redisKey)).isEqualTo("none"); + assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + + var firstInstallation = firstOwner.installForTransition(TRANSITION_ID, world.request()); + var firstStatus = statusRepository.find(qualifiedSource).orElseThrow(); + assertThat(firstStatus.regionEpoch()).isEqualTo(1L); + assertThat(firstStatus.lifecycleEpoch()).isEqualTo(7L); + assertThat(firstStatus.lastCommittedTickId()).isEqualTo(-1L); + Long sequenceAfterInstall = fenceSequenceValue(dsl); + + firstOwner.revalidateBeforeBridge(firstInstallation); + firstOwner.revalidateBeforeBridge(firstInstallation); + + assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); + assertThat(fenceSequenceValue(dsl)).isEqualTo(sequenceAfterInstall); + + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(firstInstallation)) + .isInstanceOf(IllegalStateException.class); + assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); + + var secondOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-b"); + secondOwner.installForTransition(TRANSITION_ID, world.request()); + var secondStatus = statusRepository.find(qualifiedSource).orElseThrow(); + assertThat(secondStatus.executorFence()).isGreaterThan(firstStatus.executorFence()); + assertThat(secondStatus.regionEpoch()).isEqualTo(firstStatus.regionEpoch()); + assertThat(secondStatus.lastCommittedTickId()).isEqualTo(-1L); + assertThat(secondStatus.ownerInstanceId()).isEqualTo("instance-b"); + assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(firstInstallation)) + .isInstanceOf(IllegalStateException.class); + assertThat(statusRepository.find(qualifiedSource)).contains(secondStatus); + + dsl.execute( + "UPDATE game_session_region_runtime_status" + + " SET last_committed_tick_batch_id = 'batch-8', last_committed_tick_id = 8" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId()); + var progressed = statusRepository.find(qualifiedSource).orElseThrow(); + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + + var thirdOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-c"); + var thirdInstallation = thirdOwner.installForTransition(TRANSITION_ID, world.request()); + var thirdStatus = statusRepository.find(qualifiedSource).orElseThrow(); + assertThat(thirdStatus.executorFence()).isGreaterThan(progressed.executorFence()); + assertThat(thirdStatus.regionEpoch()).isEqualTo(1L); + assertThat(thirdStatus.lastCommittedTickId()).isEqualTo(8L); + assertThat(thirdStatus.lastCommittedTickBatchId()).isEqualTo("batch-8"); + assertThat(thirdStatus.ownerInstanceId()).isEqualTo("instance-c"); + assertThat(thirdInstallation).isNotNull(); + + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + WorldCanonicalInstanceLifecycleEvidence changed = changedEvidence(world.originalEvidence()); + world.replaceOnRead(2, changed); + var fourthOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-d"); + assertThatThrownBy(() -> fourthOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); + + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + world.resetReads(); + world.replaceOnRead(3, changed); + var fifthOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-e"); + assertThatThrownBy(() -> fifthOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + var installedBeforeChangedSourceGate = statusRepository.find(qualifiedSource).orElseThrow(); + assertThat(installedBeforeChangedSourceGate.executorFence()) + .isGreaterThan(thirdStatus.executorFence()); + assertThat(installedBeforeChangedSourceGate.lastCommittedTickId()).isEqualTo(8L); + assertThat(installedBeforeChangedSourceGate.ownerInstanceId()).isEqualTo("instance-e"); + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + + world.resetReads(); + world.setAfterRead(2, POSTGRES::stop); + var sixthOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-f"); + assertThatThrownBy(() -> sixthOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(RuntimeException.class); + assertThat(redis.admin().type(redisKey)).isEqualTo("string"); + assertThat(redis.admin().pttl(redisKey)).isPositive(); + } + } + + private static DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(POSTGRES.getDriverClassName()); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + private static CanonicalGameplayRegionLeaseOwner owner( + CanonicalGameplayBindingInventoryRepository bindingInventory, + CanonicalGameplayRegionRuntimeStatusRepository statusRepository, + CanonicalGameplayRegionLeaseRedisOwner redisOwner, + WorldFixture world, + String instanceId) { + return new CanonicalGameplayRegionLeaseOwner( + bindingInventory, + statusRepository, + redisOwner, + world.resolver(), + new RuntimeIdentity( + "game-session-service", + instanceId, + "localhost", + NOW, + "controlled-test", + "controlled-sha", + "controlled-image"), + Duration.ofSeconds(30), + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence( + CanonicalInitialPlayerLocationRequest request) { + return provisionalEvidence( + request, + UUID.fromString(request.getExpectedTarget().getCanonicalTenantUuid()), + BigInteger.ONE); + } + + private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence( + CanonicalInitialPlayerLocationRequest request, UUID tenantId, BigInteger regionEpoch) { + var evidence = mock(CanonicalGameplayBindingProvisionalCasEvidence.class); + var transition = mock(CanonicalGameplayBindingTransitionSnapshot.class); + var candidate = mock(CanonicalGameplayBindingInventoryEntry.class); + var identity = mock(CanonicalGameplayBindingIdentity.class); + var target = request.getExpectedTarget(); + when(evidence.transition()).thenReturn(transition); + when(evidence.candidate()).thenReturn(candidate); + when(transition.status()) + .thenReturn(CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL); + when(transition.transitionId()).thenReturn(TRANSITION_ID); + when(candidate.lifecycle()) + .thenReturn(CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL); + when(candidate.transitionId()).thenReturn(TRANSITION_ID); + when(candidate.identity()).thenReturn(identity); + when(identity.accountId()).thenReturn(UUID.fromString(request.getCanonicalAccountUuid())); + when(identity.characterId()).thenReturn(UUID.fromString(request.getCharacterUuid())); + when(identity.tenantId()).thenReturn(tenantId); + when(identity.gameInstanceId()).thenReturn(UUID.fromString(target.getGameInstanceId())); + when(identity.playableStateNamespaceId()) + .thenReturn(UUID.fromString(target.getPlayableStateNamespaceUuid())); + when(identity.playableStateScope()).thenReturn("SHARED"); + when(identity.regionId()).thenReturn(OPERATIONAL_REGION_ID); + when(identity.regionEpoch()).thenReturn(regionEpoch); + return evidence; + } + + private static CanonicalGameplayRegionRuntimeStatusRepository.Source source( + WorldCanonicalInstanceLifecycleEvidence evidence) { + return new CanonicalGameplayRegionRuntimeStatusRepository.Source( + evidence.request().canonicalTenantId(), + evidence.request().canonicalGameInstanceId(), + CANONICAL_REGION_ID, + OPERATIONAL_REGION_ID, + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.request(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence changedEvidence( + WorldCanonicalInstanceLifecycleEvidence original) { + var changed = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(changed.request()).thenReturn(original.request()); + when(changed.lifecycleStatus()).thenReturn("ACTIVE"); + when(changed.lifecycleEpoch()).thenReturn(original.lifecycleEpoch()); + when(changed.rowVersion()).thenReturn(original.rowVersion() + 1L); + when(changed.captureId()).thenReturn(UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + when(changed.graphSha256()).thenReturn(original.graphSha256()); + when(changed.preparationInputDigest()).thenReturn(original.preparationInputDigest()); + when(changed.operationalRegionAssignments()) + .thenReturn(original.operationalRegionAssignments()); + return changed; + } + + private static CanonicalInitialPlayerLocationRequest initialLocationRequest( + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + var target = + PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid(lifecycleRequest.canonicalTenantId().toString()) + .setRealmUuid("33333333-3333-4333-8333-333333333333") + .setWorldSlug(lifecycleRequest.worldSlug()) + .setRealmSlug("test-realm") + .setGameInstanceId(lifecycleRequest.canonicalGameInstanceId().toString()) + .setCatalogRevision(1L) + .setCanonicalVersionUuid(lifecycleRequest.canonicalVersionId().toString()) + .setFrozenPolicyDigest("a".repeat(64)) + .setPlayableStateNamespaceUuid(lifecycleRequest.playableStateNamespaceId().toString()) + .setPublishedReleaseBundleRef("published/test/v1") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + return CanonicalInitialPlayerLocationRequest.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid("44444444-4444-4444-8444-444444444444") + .setExpectedTarget(target) + .setCanonicalAccountUuid(ACCOUNT_ID.toString()) + .setCharacterUuid(CHARACTER_ID.toString()) + .setAssignmentUuid("77777777-7777-4777-8777-777777777777") + .setAssignmentIntentDigest("b".repeat(64)) + .setInitialAdmissionHoldUuid("88888888-8888-4888-8888-888888888888") + .setInitialAdmissionHoldFence("99999999-9999-4999-8999-999999999999") + .setInitialAdmissionRequestId("initial-attempt-1") + .setInitialAdmissionRequestDigest("c".repeat(64)) + .setActiveLifecycleEpoch(7L) + .setTerminalProofDigest("sha256:" + "d".repeat(64)) + .setCommittedPointerVersion(1L) + .setAuditEventId(1L) + .build(); + } + + private static CanonicalInitialPlayerLocationRegionResponse regionResponse( + CanonicalInitialPlayerLocationRequest request, + WorldCanonicalInstanceLifecycleEvidence evidence) { + var placement = + CanonicalInitialPlayerLocationResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(request.getPlacementOperationUuid()) + .setRequestDigest("sha256:" + "e".repeat(64)) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setCharacterUuid(request.getCharacterUuid()) + .setAssignmentUuid(request.getAssignmentUuid()) + .setAssignmentIntentDigest(request.getAssignmentIntentDigest()) + .setResultDigest("sha256:" + "f".repeat(64)) + .setOutcome( + CanonicalInitialPlayerLocationOutcome + .CANONICAL_INITIAL_PLAYER_LOCATION_OUTCOME_APPLIED) + .setStartLocation( + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRoom + .newBuilder() + .setCanonicalTenantUuid(request.getExpectedTarget().getCanonicalTenantUuid()) + .setCanonicalVersionUuid(request.getExpectedTarget().getCanonicalVersionUuid()) + .setRoomTemplateUuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) + .setPrivateRuntimeRoomKey("91") + .build(); + var lifecycle = + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationLifecycleConsequence + .newBuilder() + .setCanonicalRequestBytes( + com.google.protobuf.ByteString.copyFrom(evidence.request().canonicalBytes())) + .setLifecycleStatus(evidence.lifecycleStatus()) + .setLifecycleEpoch(evidence.lifecycleEpoch()) + .setRowVersion(evidence.rowVersion()) + .setCaptureUuid(evidence.captureId().toString()) + .setGraphSha256(evidence.graphSha256()) + .setPreparationInputDigest(evidence.preparationInputDigest()) + .build(); + return CanonicalInitialPlayerLocationRegionResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementResult(placement) + .setExpectedTarget(request.getExpectedTarget()) + .setCanonicalRegionInstanceUuid(CANONICAL_REGION_ID.toString()) + .setOperationalRegionUuid(OPERATIONAL_REGION_ID.toString()) + .setPrivateWorldInstanceKey(7L) + .setObservedRuntimeRoomKey(91L) + .setLifecycle(lifecycle) + .build(); + } + + private static long fenceSequenceValue(DSLContext dsl) { + Record row = dsl.fetchOne("SELECT last_value FROM game_session_region_executor_fence_seq"); + if (row == null) throw new AssertionError("Region fence sequence row was missing"); + Long value = row.get("last_value", Long.class); + if (value == null || value <= 0L) throw new AssertionError("Region fence sequence was invalid"); + return value; + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static final class WorldFixture { + private final WorldCanonicalInstanceLifecycleEvidence original; + private final CanonicalInitialPlayerLocationRequest request; + private final CanonicalInitialPlayerLocationClient initialClient; + private final WorldCanonicalInstanceLifecycleClient lifecycleClient; + private final AtomicReference current; + private final AtomicInteger reads = new AtomicInteger(); + private volatile int replaceOnRead = -1; + private volatile WorldCanonicalInstanceLifecycleEvidence replacement; + private volatile int callbackOnRead = -1; + private volatile Runnable afterRead = () -> {}; + private final CanonicalInitialPlayerLocationRegionResolver resolver; + + private WorldFixture(WorldCanonicalInstanceLifecycleEvidence original) { + this.original = original; + this.current = new AtomicReference<>(original); + this.request = initialLocationRequest(original.request()); + this.initialClient = mock(CanonicalInitialPlayerLocationClient.class); + this.lifecycleClient = mock(WorldCanonicalInstanceLifecycleClient.class); + when(initialClient.readInitialPlayerLocationRegion(request)) + .thenAnswer( + invocation -> { + int read = reads.incrementAndGet(); + if (read == replaceOnRead) current.set(replacement); + CanonicalInitialPlayerLocationRegionResponse response = + regionResponse(request, current.get()); + if (read == callbackOnRead) afterRead.run(); + return response; + }); + when(lifecycleClient.read(original.request())).thenAnswer(invocation -> current.get()); + this.resolver = + new CanonicalInitialPlayerLocationRegionResolver( + initialClient, new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); + } + + static WorldFixture open() throws Exception { + return new WorldFixture(AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L)); + } + + CanonicalInitialPlayerLocationRegionResolver resolver() { + return resolver; + } + + CanonicalInitialPlayerLocationRequest request() { + return request; + } + + WorldCanonicalInstanceLifecycleEvidence originalEvidence() { + return original; + } + + void replaceOnRead(int read, WorldCanonicalInstanceLifecycleEvidence evidence) { + resetReads(); + this.replaceOnRead = read; + this.replacement = evidence; + } + + void setAfterRead(int read, Runnable action) { + resetReads(); + this.callbackOnRead = read; + this.afterRead = action; + } + + void resetReads() { + reads.set(0); + current.set(original); + replaceOnRead = -1; + replacement = null; + callbackOnRead = -1; + afterRead = () -> {}; + } + } + + private static final class RedisFixture implements AutoCloseable { + private final RedisClient administrator; + private final RedisClient ownerClient; + private final StatefulRedisConnection adminConnection; + private final RedisCommands admin; + private final RedisScriptCatalog catalog; + + private RedisFixture( + RedisClient administrator, + RedisClient ownerClient, + StatefulRedisConnection adminConnection, + RedisCommands admin, + RedisScriptCatalog catalog) { + this.administrator = administrator; + this.ownerClient = ownerClient; + this.adminConnection = adminConnection; + this.admin = admin; + this.catalog = catalog; + } + + static RedisFixture open() { + RedisClient administrator = createClient(null, null); + StatefulRedisConnection adminConnection = + administrator.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + admin.flushdb(); + admin.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern("tick-executor-lease:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRE)); + RedisClient ownerClient = createClient(PRINCIPAL, PASSWORD); + RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayRegionLeaseRedisScriptContribution())); + return new RedisFixture(administrator, ownerClient, adminConnection, admin, catalog); + } + + private static RedisClient createClient(String username, String password) { + RedisURI.Builder builder = + RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(REDIS_PORT)) + .withTimeout(Duration.ofSeconds(3)); + if (username != null) builder.withAuthentication(username, password); + RedisClient client = RedisClient.create(builder.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + RedisClient ownerClient() { + return ownerClient; + } + + RedisCommands admin() { + return admin; + } + + RedisScriptCatalog catalog() { + return catalog; + } + + @Override + public void close() { + adminConnection.close(); + ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java new file mode 100644 index 0000000000..90f4d3ba9a --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java @@ -0,0 +1,230 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String PASSWORD = UUID.randomUUID().toString(); + private static final int PORT = 6379; + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(PORT); + + @Test + void exactOpaqueLeaseGrantIsScopedRenewableAndFailsClosedAfterExpiry() { + try (RedisFixture redis = RedisFixture.open()) { + var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + RuntimeIdentity firstIdentity = identity("instance-a"); + var firstSource = source(GAME_INSTANCE_ID_A); + try { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy( + () -> owner.acquire(firstSource, 7L, Duration.ofSeconds(10), firstIdentity)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat( + redis + .admin() + .type( + ascii( + CanonicalGameplayRegionRedisKeys.lease( + TENANT_ID, GAME_INSTANCE_ID_A, OPERATIONAL_REGION_ID)))) + .isEqualTo("none"); + var firstGrant = owner.acquire(firstSource, 7L, Duration.ofSeconds(10), firstIdentity); + byte[] firstKey = ascii(firstGrant.key()); + byte[] firstValue = redis.admin().get(firstKey); + + assertThat(redis.admin().type(firstKey)).isEqualTo("string"); + assertThat(new String(firstValue, StandardCharsets.US_ASCII)) + .matches("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + assertThat(redis.admin().pttl(firstKey)).isPositive(); + owner.requireCurrent(firstGrant); + owner.renew(firstGrant, Duration.ofSeconds(10)); + assertThat(redis.admin().get(firstKey)).containsExactly(firstValue); + + assertThatThrownBy( + () -> owner.acquire(firstSource, 7L, Duration.ofSeconds(10), identity("instance-b"))) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().get(firstKey)).containsExactly(firstValue); + + var secondGameGrant = + owner.acquire(source(GAME_INSTANCE_ID_B), 7L, Duration.ofSeconds(10), firstIdentity); + assertThat(secondGameGrant.key()).isNotEqualTo(firstGrant.key()); + owner.requireCurrent(secondGameGrant); + + assertThat(redis.admin().pexpire(firstKey, 0L)).isTrue(); + assertThatThrownBy(() -> owner.requireCurrent(firstGrant)) + .isInstanceOf(IllegalStateException.class); + var successor = + owner.acquire(firstSource, 7L, Duration.ofSeconds(10), identity("instance-b")); + assertThat(redis.admin().get(firstKey)).isNotEqualTo(firstValue); + owner.requireCurrent(successor); + } + } + + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID GAME_INSTANCE_ID_A = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID GAME_INSTANCE_ID_B = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID CANONICAL_REGION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID OPERATIONAL_REGION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + + private static RuntimeIdentity identity(String instanceId) { + return new RuntimeIdentity( + "game-session-service", + instanceId, + "localhost", + Instant.parse("2026-10-26T00:00:00Z"), + "test", + "test-sha", + "test-image"); + } + + private static CanonicalGameplayRegionRuntimeStatusRepository.Source source(UUID gameInstanceId) { + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "firemud", + TENANT_ID, + "test-world", + gameInstanceId, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + "SHARED", + true, + "control-plane-request", + UUID.fromString("88888888-8888-4888-8888-888888888888"), + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new CanonicalGameplayRegionRuntimeStatusRepository.Source( + TENANT_ID, + gameInstanceId, + CANONICAL_REGION_ID, + OPERATIONAL_REGION_ID, + 9L, + 12L, + request, + UUID.fromString("99999999-9999-4999-8999-999999999999"), + "a".repeat(64), + "sha256:" + "b".repeat(64)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static final class RedisFixture implements AutoCloseable { + private final RedisClient administrator; + private final RedisClient ownerClient; + private final StatefulRedisConnection adminConnection; + private final RedisCommands admin; + private final RedisScriptCatalog catalog; + + private RedisFixture( + RedisClient administrator, + RedisClient ownerClient, + StatefulRedisConnection adminConnection, + RedisCommands admin, + RedisScriptCatalog catalog) { + this.administrator = administrator; + this.ownerClient = ownerClient; + this.adminConnection = adminConnection; + this.admin = admin; + this.catalog = catalog; + } + + static RedisFixture open() { + RedisClient administrator = createClient(null, null); + StatefulRedisConnection adminConnection = + administrator.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + admin.flushdb(); + admin.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern("tick-executor-lease:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRE)); + RedisClient ownerClient = createClient(PRINCIPAL, PASSWORD); + RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + java.util.List.of(new CanonicalGameplayRegionLeaseRedisScriptContribution())); + return new RedisFixture(administrator, ownerClient, adminConnection, admin, catalog); + } + + private static RedisClient createClient(String username, String password) { + RedisURI.Builder builder = + RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(PORT)) + .withTimeout(Duration.ofSeconds(3)); + if (username != null) builder.withAuthentication(username, password); + RedisClient client = RedisClient.create(builder.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private RedisClient ownerClient() { + return ownerClient; + } + + private RedisCommands admin() { + return admin; + } + + private RedisScriptCatalog catalog() { + return catalog; + } + + @Override + public void close() { + adminConnection.close(); + ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java new file mode 100644 index 0000000000..b2c3c0be23 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -0,0 +1,342 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID OTHER_GAME_INSTANCE_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID CANONICAL_REGION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATIONAL_REGION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID CAPTURE_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String GRAPH_DIGEST = "a".repeat(64); + private static final String PREPARATION_DIGEST = "sha256:" + "b".repeat(64); + private static final String FIRST_LEASE_CORRELATION = "c".repeat(64); + private static final String SECOND_LEASE_CORRELATION = "d".repeat(64); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private DSLContext dsl; + private CanonicalGameplayRegionRuntimeStatusRepository repository; + private CanonicalGameplayRegionRuntimeStatusRepository.Source source; + + @BeforeAll + void setUpRepository() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(POSTGRES.getDriverClassName()); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + + Flyway.configure() + .dataSource(dataSource) + .locations( + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + .load() + .migrate(); + + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = new CanonicalGameplayRegionRuntimeStatusRepository(dsl); + source = source(GAME_INSTANCE_ID, CAPTURE_ID); + } + + @BeforeEach + void clearOwnerRows() { + dsl.execute("TRUNCATE TABLE game_session_region_runtime_status"); + } + + @Test + void initializesOnlyAnAbsentRegionAtItsFirstEpochAndFirstTick() { + assertThatThrownBy( + () -> + repository.installOwner( + source, + 2L, + null, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:00Z"))) + .isInstanceOf(IllegalStateException.class); + assertThat(repository.find(source)).isEmpty(); + + var installed = + repository.installOwner( + source, + 1L, + null, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:01Z")); + + assertThat(installed.tenantRegionTag()) + .isEqualTo( + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + TENANT_ID, GAME_INSTANCE_ID, OPERATIONAL_REGION_ID)); + assertThat(installed.regionEpoch()).isEqualTo(1L); + assertThat(installed.lifecycleEpoch()).isEqualTo(4L); + assertThat(installed.lastCommittedTickId()).isEqualTo(-1L); + assertThat(installed.executorFence()).isPositive(); + assertThat(repository.find(source)).contains(installed); + } + + @Test + void ownerReadRejectsAnAmbientSynchronizationContext() { + try { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> repository.find(source)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void exactOwnerRetryReplacesFenceWithoutResettingRegionTimeline() { + var initial = + repository.installOwner( + source, + 1L, + null, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:01Z")); + long sequenceAfterInstall = fenceSequenceValue(); + var sameGrantRetry = + repository.installOwner( + source, + 1L, + initial, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:01Z")); + + assertThat(sameGrantRetry).isEqualTo(initial); + assertThat(fenceSequenceValue()).isEqualTo(sequenceAfterInstall); + + dsl.execute( + "UPDATE game_session_region_runtime_status" + + " SET last_committed_tick_batch_id = 'batch-7', last_committed_tick_id = 7" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + TENANT_ID, + GAME_INSTANCE_ID, + OPERATIONAL_REGION_ID); + var current = repository.find(source).orElseThrow(); + + var retry = + repository.installOwner( + source, + 1L, + current, + SECOND_LEASE_CORRELATION, + "game-session-service", + "instance-b", + Instant.parse("2026-10-26T00:00:02Z")); + + assertThat(retry.regionEpoch()).isEqualTo(1L); + assertThat(retry.executorFence()).isGreaterThan(initial.executorFence()); + assertThat(retry.leaseTokenCorrelation()).isEqualTo(SECOND_LEASE_CORRELATION); + assertThat(retry.ownerInstanceId()).isEqualTo("instance-b"); + assertThat(retry.lastCommittedTickId()).isEqualTo(7L); + assertThat(retry.lastCommittedTickBatchId()).isEqualTo("batch-7"); + assertThatThrownBy( + () -> + repository.installOwner( + source, + 1L, + initial, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:03Z"))) + .isInstanceOf(IllegalStateException.class); + assertThat(repository.find(source)).contains(retry); + } + + @Test + void sameNaturalScopeRejectsChangedWorldCaptureEvidence() { + repository.installOwner( + source, + 1L, + null, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:01Z")); + + assertThatThrownBy( + () -> + repository.find( + source(GAME_INSTANCE_ID, new UUID(0x6666666666666666L, 0x8666666666666666L)))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void sameRegionInDifferentGameInstancesHasDistinctPersistedOwnerTags() { + var first = + repository.installOwner( + source, + 1L, + null, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:01Z")); + var otherGameSource = source(OTHER_GAME_INSTANCE_ID, CAPTURE_ID); + var otherGame = + repository.installOwner( + otherGameSource, + 1L, + null, + SECOND_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:02Z")); + + assertThat(first.regionId()).isEqualTo(otherGame.regionId()); + assertThat(first.tenantRegionTag()).isNotEqualTo(otherGame.tenantRegionTag()); + assertThat(repository.find(source)).contains(first); + assertThat(repository.find(otherGameSource)).contains(otherGame); + } + + @Test + void concurrentNewGrantsFromOnePriorOwnerInstallOnlyOneNewFence() throws Exception { + var prior = + repository.installOwner( + source, + 1L, + null, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-prior", + Instant.parse("2026-10-26T00:00:01Z")); + long sequenceBefore = fenceSequenceValue(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> installAfterBarrier(prior, "e".repeat(64), "instance-a", ready, start)); + Future + second = + executor.submit( + () -> installAfterBarrier(prior, "f".repeat(64), "instance-b", ready, start)); + + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstResult = first.get(10, TimeUnit.SECONDS); + var secondResult = second.get(10, TimeUnit.SECONDS); + assertThat((firstResult == null) ^ (secondResult == null)).isTrue(); + + var committed = repository.find(source).orElseThrow(); + assertThat(committed.executorFence()).isGreaterThan(prior.executorFence()); + assertThat(committed.regionEpoch()).isEqualTo(prior.regionEpoch()); + assertThat(fenceSequenceValue()).isEqualTo(sequenceBefore + 1L); + assertThat(committed).isEqualTo(firstResult == null ? secondResult : firstResult); + } + } + + private CanonicalGameplayRegionRuntimeStatus installAfterBarrier( + CanonicalGameplayRegionRuntimeStatus prior, + String correlation, + String ownerInstanceId, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + assertThat(start.await(5, TimeUnit.SECONDS)).isTrue(); + try { + return repository.installOwner( + source, + 1L, + prior, + correlation, + "game-session-service", + ownerInstanceId, + Instant.parse("2026-10-26T00:00:02Z")); + } catch (IllegalStateException staleGrant) { + return null; + } + } + + private long fenceSequenceValue() { + Record row = dsl.fetchOne("SELECT last_value FROM game_session_region_executor_fence_seq"); + assertThat(row).isNotNull(); + Long value = row.get("last_value", Long.class); + assertThat(value).isPositive(); + return value; + } + + private static CanonicalGameplayRegionRuntimeStatusRepository.Source source( + UUID gameInstanceId, UUID captureId) { + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + "firemud", + TENANT_ID, + "test-world", + gameInstanceId, + UUID.fromString("88888888-8888-4888-8888-888888888888"), + "SHARED", + true, + "control-plane-request", + UUID.fromString("99999999-9999-4999-8999-999999999999"), + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new CanonicalGameplayRegionRuntimeStatusRepository.Source( + TENANT_ID, + gameInstanceId, + CANONICAL_REGION_ID, + OPERATIONAL_REGION_ID, + 4L, + 12L, + request, + captureId, + GRAPH_DIGEST, + PREPARATION_DIGEST); + } +} diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeysTest.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeysTest.java new file mode 100644 index 0000000000..90231c1bf7 --- /dev/null +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeysTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayRegionRedisKeysTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID FIRST_GAME_INSTANCE_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SECOND_GAME_INSTANCE_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REGION_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void projectionIsStableAndIncludesTheFullOwnerScope() { + String first = + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + TENANT_ID, FIRST_GAME_INSTANCE_ID, REGION_ID); + String exactRetry = + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + TENANT_ID, FIRST_GAME_INSTANCE_ID, REGION_ID); + String secondGame = + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + TENANT_ID, SECOND_GAME_INSTANCE_ID, REGION_ID); + + assertThat(first) + .isEqualTo( + "r1-11111111111141118111111111111111-22222222222242228222222222222222-44444444444444448444444444444444"); + assertThat(exactRetry).isEqualTo(first); + assertThat(secondGame).isNotEqualTo(first); + assertThat(CanonicalGameplayRegionRedisKeys.lease(TENANT_ID, FIRST_GAME_INSTANCE_ID, REGION_ID)) + .isEqualTo("tick-executor-lease:{" + first + "}"); + } + + @Test + void projectionRejectsNilScopeIdentifiers() { + assertThatThrownBy( + () -> + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + TENANT_ID, new UUID(0L, 0L), REGION_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("gameInstanceId"); + } +} 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(); + } +} From 5309afe4c975a96ead3321d1d00e140cb1df61b2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:59:12 +1300 Subject: [PATCH 03/36] Prepare nonadmitting region timeline and durable binding bridge owner --- .../api-contracts.md | 6 + .../runtime-and-data.md | 12 +- ...system-architecture-identifier-glossary.md | 4 +- .../architecture/system-architecture-redis.md | 6 + design/project-management/ai-observations.md | 11 + ...GameplayBindingRegionBridgeObligation.java | 150 +++- ...calGameplayBindingInventoryRepository.java | 593 ++++++++++++- ...lGameplayIssuerBootstrapCoverageOwner.java | 18 +- ...playIssuerBootstrapCoverageRepository.java | 265 ++++-- ...anonicalGameplayIssuerInstalledAnchor.java | 204 +++-- ...nicalGameplayRegionBindingBridgeOwner.java | 122 +++ ...meplayRegionBindingBridgeOwnerFactory.java | 40 + ...icalGameplayRegionBindingBridgeProofs.java | 165 ++++ ...onicalGameplayRegionIncarnationSource.java | 349 ++++++++ .../CanonicalGameplayRegionLeaseOwner.java | 308 ++++++- ...onicalGameplayRegionLeaseOwnerFactory.java | 3 + ...anonicalGameplayRegionLeaseRedisOwner.java | 522 +++++++++++- .../CanonicalGameplayRegionRedisKeys.java | 13 + ...GameplayRegionRuntimeStatusRepository.java | 790 ++++++++++++++++++ ...nBindingBridgeRedisScriptContribution.java | 55 ++ ...layRegionLeaseRedisScriptContribution.java | 6 +- ...ical_region_session_binding_bridge_ack.sql | 230 +++++ .../lua/game-session-region-lease-acquire.lua | 78 +- .../lua/game-session-region-lease-read.lua | 68 +- .../lua/game-session-region-lease-renew.lua | 75 +- ...-session-region-session-binding-bridge.lua | 105 +++ ...ame-session-region-timeline-initialize.lua | 106 +++ .../game-session-region-lease-acquire.json | 9 +- .../game-session-region-lease-read.json | 9 +- .../game-session-region-lease-renew.json | 9 +- ...session-region-session-binding-bridge.json | 37 + ...me-session-region-timeline-initialize.json | 32 + ...BootstrapCoverageOwnerIntegrationTest.java | 276 +++--- ...indingBridgeRedisOwnerIntegrationTest.java | 523 ++++++++++++ ...meplayRegionLeaseOwnerIntegrationTest.java | 252 +++++- ...yRegionLeaseRedisOwnerIntegrationTest.java | 52 +- 36 files changed, 5155 insertions(+), 348 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionIncarnationSource.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-region-session-binding-bridge.lua create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-region-session-binding-bridge.json create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java 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..1d39ee759b 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,16 @@ 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. The runtime ID comes from the canonical runtime allocator, or a narrow Entity-owned durable allocation when that allocator is unavailable; 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. Runtime replacement allocates a new projection generation and runtime ID while retaining and fencing the previous association; reconnect alone does not replace the projection. A controlled source cannot authorize production allocation. Allocation alone establishes neither World placement, an active lifecycle, a Game Session region lease nor admission. + +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: diff --git a/design/architecture/system-architecture-identifier-glossary.md b/design/architecture/system-architecture-identifier-glossary.md index 1f51496309..36e32dc8c9 100644 --- a/design/architecture/system-architecture-identifier-glossary.md +++ b/design/architecture/system-architecture-identifier-glossary.md @@ -44,7 +44,7 @@ The live Game Session pin/convergence proto/runtime carries the exact API observ - Intentional legacy numeric-as-string contracts are narrow, explicit migration exceptions and do not relax the UUID rule for UUID-governed identifiers. The Logging & Admin game-session-pin reads are one such exception: REST path values and the internal Game Session pin-read request fields use positive decimal text; the target convergence response fields likewise use positive decimal text, while the current `GameSessionPinConvergenceDto` serializes its identifier fields as JSON numbers. That current representation is an unsafe implementation gap and must migrate to decimal strings for JavaScript-safe exactness; see [Logging & Admin API Contracts](./microservices/logging-admin-service/api-contracts.md). This is tracked migration status, not canonical permission to expose other UUID-governed identifiers as decimal strings. - Services may maintain numeric primary and join keys internally. Private database keys never replace or appear as reversible encodings of the canonical UUID identity in public or cross-service contracts. - `regionInstanceId` and `zoneInstanceId` remain UUID-governed runtime identifiers. Live `roomInstanceId`, `entityId`, and `itemInstanceId` are deliberate typed scoped-numeric runtime identifiers: they may be stable numbers allocated within `(tenantId, gameInstanceId)` when the owning runtime guarantees concurrency safety and non-reuse for the required lifetime. They are not interchangeable with one another or with a UUID-governed logical identifier. `itemInstanceId` is the distinct concrete-item identity used by containment and equipment contracts; it is not an alias for `entityId` or `entityTemplateId`. Extending that exception to region or zone instances requires a future accepted architecture decision. -- Redis and other operational key builders use `tenantRegionTag` as the canonical normalized hash-tag projection of the complete `{tenantId, gameInstanceId, regionId}` scope. A region tag must include the game-instance dimension; a bare `{tenantId, regionId}` projection is not collision-safe when two instances use the same region ID. +- Redis and other operational key builders use `tenantRegionTag` as the canonical normalized hash-tag projection of the complete `{tenantId, gameInstanceId, regionId}` scope. A region tag must include the game-instance dimension; a bare `{tenantId, regionId}` projection is not collision-safe when two instances use the same region ID. The exact physical versioned projection is owned by [Redis: Canonical Region Key Projection](./system-architecture-redis.md#canonical-region-key-projection). - `tenantSlug` is the stable Game Design-owned player-facing selector for one tenant. Its canonical form is a lowercase ASCII hyphenated slug matching `[a-z0-9]+(?:-[a-z0-9]+)*`; resolve it against current catalog authority to opaque `tenantId`, and never persist or authorize from the slug as though it were durable tenant identity. [Multi-Tenancy](./system-architecture-multi-tenancy.md#core-concepts) and [ADR 0168](./decisions/adr-0168-snapshot-bound-lobby-selectors-and-stable-realm-identity.md) own its selector, re-resolution, and rename semantics. - `worldSlug` is a stable tenant-scoped selector for an authored world. Resolve `tenantSlug` to `tenantId` first, then resolve `worldSlug` within that tenant; `worldSlug` is neither globally unique nor durable tenant identity. - `realmId` is the opaque UUID identity of a durable player-addressable realm. `realmSlug` is unique within its tenant and resolves server-side to `realmId`. @@ -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/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index d1a17addc8..256a67a3c5 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -81,6 +81,12 @@ When this hub introduces or sharpens canonical coordination contracts, keep the --- +## Canonical Region Key Projection + +The physical `tenantRegionTag` projects the complete canonical `{tenantId, gameInstanceId, regionId}` scope defined by [Tick System](./system-architecture-ticks.md#region-authority-and-tick-executor). Version 1 is `r1---`: each component is the exact lowercase 32-hex-digit spelling of its canonical non-nil UUID with UUID separators removed. The resulting 101-byte value contains no braces or colons; braces belong only to the enclosing Redis key’s hash-tag syntax. Inputs are validated canonical identities, never normalized caller text. Reusing a region UUID in two game instances produces different tags. + +The actual region-status owner derives and retains this projection from its qualified complete region identity and exact-compares it on retry. A caller-supplied tag, tenant-only gameplay tag, content-region row ID or instance-scoped ownership record cannot supply that identity. The projection is a key address, not World assignment, region-epoch, lease or executor-fence authority. All region-scoped lease, metadata and binding keys use this same projection; it does not introduce a separate registry or authorize a timeline reset. + ## Redis Coordination Invariants FireMUD uses Redis as a **transient, high‑performance coordination layer**, not as a primary source of truth. The following invariants apply to all coordination designs: diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8a0f63bdf6..6ce58bea32 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -411,3 +411,14 @@ Entry format: - Context: `staleSerializableGenuineAckCreatorRetriesAndRetainsOneExactWinner` failed in `finalized()` after 1.292 seconds, before the serializable race began. - Observation: The SQL guard message `storage deadline expired` covers either `evaluatedAt >` the database clock or `expiresAt <=` the database clock, so the branch and clock cause are unknown. Retain the failed result; an unchanged future retry cannot recover the original failure-time clock evidence. - Expected pattern: Capture the original evidence timestamps, JVM and database wall clocks, and monotonic elapsed time only after a failure, without delaying the original COMMIT or changing its lifetime or guard. + +- `2026-10-26`: Inspect default registration separately from a manual owner implementation + - Context: A delegated region-lease source implementation added its Redis contribution to the default ServiceLoader list despite an explicit manually composed, unregistered scope. Main detected and removed only that new registration before validation or publication; the existing registered contributions were preserved. + - Observation: A passive descriptor class and a factory do not establish that the owner remains unregistered; the ServiceLoader resource can change that boundary independently. No default runtime activation was performed or proved. + - Expected pattern: Inspect registration resources against the assigned scope at integration, reject unrequested registration, and make focused fixtures compose their manual descriptor catalog explicitly. + +- `2026-10-26`: Expose the current review configuration after a guarded conflict + - Context: The published #3310 comparison refresh returned generic `review_conflict` and identity advice without a current configuration revision or operation receipt, despite a verified Gameplay binding. Ordinary worker help did not expose a supported way to obtain the missing guard. + - Observation: The worker could not distinguish a stale configuration guard from scoped-access failure. FireController's owner confirmed the missing conflict detail and ordinary configuration read as a product defect and is repairing the supported path; review allocations remain unchanged. + - Expected pattern: Retain the exact request and idempotency key, report both the error and the missing recovery guidance to the tool owner, and continue independent work. Do not guess revisions, repeat provider requests or debug the service from a product lane. Record the supported recovery outcome when supplied. + - Recovery outcome: The owner confirmed that the rejected request queued no operation and identified revision 9 as stale. The ordinary `review_execution_read` became discoverable, returned revision 15 with execution enabled, and a new source refresh using that observed guard was accepted. This unblocked the worker; deployment of precise conflict diagnostics and discoverable help remained with the tool owner. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java index 17ba59d994..ee68ab1a9d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java @@ -4,7 +4,7 @@ import java.util.Objects; import java.util.UUID; -/** Exact intended region-lease bridge tuple; it contains no acknowledgement or success claim. */ +/** Durable region bridge obligation projection; a private repository receipt carries ACK authority. */ public record CanonicalGameplayBindingRegionBridgeObligation( UUID transitionId, CanonicalGameplayBindingRef bindingRef, @@ -17,7 +17,76 @@ public record CanonicalGameplayBindingRegionBridgeObligation( UUID regionId, BigInteger regionEpoch, Status status, - BigInteger inventoryRevision) { + BigInteger inventoryRevision, + UUID bridgeOperationId, + String bridgePreimageState, + Long runtimeEntityId, + Long entityProjectionGeneration, + Long entityProjectionFence, + String entityWorkloadNamespace, + UUID assignmentId, + String assignmentIntentDigest, + String entityReferenceDigest, + String worldSourceDigest, + UUID canonicalRegionId, + Long worldLifecycleEpoch, + Long worldLifecycleRowVersion, + UUID worldCaptureId, + String worldGraphSha256, + String worldPreparationInputDigest, + BigInteger executorFence, + String leaseTokenCorrelation, + String redisReadbackDigest, + java.time.Instant acknowledgedAt) { + + /** Retains the V29 required-only constructor used by non-ACK inventory projections. */ + public CanonicalGameplayBindingRegionBridgeObligation( + UUID transitionId, + CanonicalGameplayBindingRef bindingRef, + BigInteger bindingGeneration, + UUID accountId, + UUID tenantId, + UUID gameInstanceId, + long runtimeGameInstanceId, + String sessionId, + UUID regionId, + BigInteger regionEpoch, + Status status, + BigInteger inventoryRevision) { + this( + transitionId, + bindingRef, + bindingGeneration, + accountId, + tenantId, + gameInstanceId, + runtimeGameInstanceId, + sessionId, + regionId, + regionEpoch, + status, + inventoryRevision, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null); + } public CanonicalGameplayBindingRegionBridgeObligation { requireNonNil(transitionId, "transitionId"); Objects.requireNonNull(bindingRef, "bindingRef"); @@ -33,6 +102,60 @@ public record CanonicalGameplayBindingRegionBridgeObligation( requirePositive(regionEpoch, "regionEpoch"); Objects.requireNonNull(status, "status"); requirePositive(inventoryRevision, "inventoryRevision"); + boolean prepared = bridgeOperationId != null; + if (prepared != (bridgePreimageState != null) + || prepared != (runtimeEntityId != null) + || prepared != (entityProjectionGeneration != null) + || prepared != (entityProjectionFence != null) + || prepared != (entityWorkloadNamespace != null) + || prepared != (assignmentId != null) + || prepared != (assignmentIntentDigest != null) + || prepared != (entityReferenceDigest != null) + || prepared != (worldSourceDigest != null) + || prepared != (canonicalRegionId != null) + || prepared != (worldLifecycleEpoch != null) + || prepared != (worldLifecycleRowVersion != null) + || prepared != (worldCaptureId != null) + || prepared != (worldGraphSha256 != null) + || prepared != (worldPreparationInputDigest != null)) { + throw new IllegalArgumentException("Region bridge operation provenance is incomplete"); + } + if (prepared) { + if (!"ABSENT".equals(bridgePreimageState)) { + throw new IllegalArgumentException("First-NEW bridge preimage must be ABSENT"); + } + requirePositive(runtimeEntityId, "runtimeEntityId"); + requirePositive(entityProjectionGeneration, "entityProjectionGeneration"); + requirePositive(entityProjectionFence, "entityProjectionFence"); + requireNonNil(assignmentId, "assignmentId"); + requireNonNil(canonicalRegionId, "canonicalRegionId"); + requireNonNil(worldCaptureId, "worldCaptureId"); + requireDigest(assignmentIntentDigest, "assignmentIntentDigest"); + requireDigest(entityReferenceDigest, "entityReferenceDigest"); + requireDigest(worldSourceDigest, "worldSourceDigest"); + requireDigest(worldGraphSha256, "worldGraphSha256"); + requirePrefixedDigest(worldPreparationInputDigest, "worldPreparationInputDigest"); + if (entityWorkloadNamespace.isBlank() + || !entityWorkloadNamespace.equals(entityWorkloadNamespace.trim()) + || worldLifecycleEpoch <= 0L + || worldLifecycleRowVersion < 0L) { + throw new IllegalArgumentException("Region bridge source provenance is invalid"); + } + } + boolean acknowledged = status == Status.ACKNOWLEDGED; + if ((executorFence != null) != (leaseTokenCorrelation != null) + || (acknowledged != (redisReadbackDigest != null)) + || (acknowledged != (acknowledgedAt != null)) + || (acknowledged && (!prepared || executorFence == null))) { + throw new IllegalArgumentException("Region bridge acknowledgement provenance is incomplete"); + } + if (executorFence != null) { + requirePositive(executorFence, "executorFence"); + requireDigest(leaseTokenCorrelation, "leaseTokenCorrelation"); + } + if (acknowledged) { + requireDigest(redisReadbackDigest, "redisReadbackDigest"); + } } private static void requireNonNil(UUID value, String name) { @@ -49,7 +172,28 @@ private static void requirePositive(BigInteger value, String name) { } } + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0L) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be lowercase SHA-256 hex"); + } + } + + private static void requirePrefixedDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be prefixed lowercase SHA-256 hex"); + } + } + public enum Status { - REQUIRED + REQUIRED, + ACKNOWLEDGED } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 88f98af39a..52b9906ec1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -3,6 +3,7 @@ import java.math.BigDecimal; import java.math.BigInteger; import java.time.OffsetDateTime; +import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; @@ -10,6 +11,10 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; @@ -34,6 +39,7 @@ import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Game Session-owned durable preparation ledger. @@ -200,6 +206,552 @@ CanonicalGameplayBindingProvisionalCasEvidence readProvisionalCasEvidence(UUID t }); } + void requireSameProvisionalSource( + CanonicalGameplayBindingProvisionalCasEvidence expected, + CanonicalGameplayBindingProvisionalCasEvidence current) { + requireSameProvisionalOperation( + Objects.requireNonNull(expected, "expected"), Objects.requireNonNull(current, "current")); + } + + /** + * Persists the exact selected first-NEW bridge operation and current region fence before Redis + * can be changed. A retry reuses its operation identity and refuses changed Entity or World + * provenance. + */ + CanonicalGameplayBindingRegionBridgeObligation prepareRegionBridge( + CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolvedRegion, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference runtimeReference, + CanonicalGameplayRegionRuntimeStatus ownerStatus, + CanonicalGameplayRegionLeaseRedisOwner.BindingPreimage preimage) { + requireNoAmbientTransaction(); + Objects.requireNonNull(expectedEvidence, "expectedEvidence"); + Objects.requireNonNull(preimage, "preimage"); + BridgeInputs inputs = + requireBridgeInputs( + expectedEvidence, worldRequest, resolvedRegion, runtimeReference, ownerStatus); + requireExactBridgePreimage(preimage, inputs, expectedEvidence, ownerStatus); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = + loadProvisionalCasEvidence( + transaction, expectedEvidence.transition().transitionId(), true); + requireSameProvisionalOperation(expectedEvidence, currentEvidence); + BridgeInputs currentInputs = + requireBridgeInputs( + currentEvidence, worldRequest, resolvedRegion, runtimeReference, ownerStatus); + if (!inputs.equals(currentInputs) || currentEvidence.expectedPrior() != null) { + throw conflict("Region bridge source changed or is not a first-NEW transition"); + } + requireCurrentRegionOwner(transaction, ownerStatus); + Record regionRow = + transaction.fetchOne( + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE", + currentEvidence.transition().transitionId()); + if (regionRow == null) throw conflict("Region bridge obligation is missing"); + CanonicalGameplayBindingRegionBridgeObligation existing = toRegionObligation(regionRow); + if (existing.bridgeOperationId() != null) { + if (!matchesPreparedOperation(existing, inputs)) { + throw conflict("A retry changed the retained Entity or World bridge source"); + } + boolean sameGrant = + Objects.equals(existing.executorFence(), ownerStatus.executorFence()) + && Objects.equals( + existing.leaseTokenCorrelation(), ownerStatus.leaseTokenCorrelation()); + if (sameGrant) return existing; + return rewritePreparedBridgeForCurrentGrant( + transaction, currentRevision, currentEvidence, regionRow, existing, inputs, ownerStatus); + } + if (preimage.state() != CanonicalGameplayRegionLeaseRedisOwner.PreimageState.ABSENT) { + throw conflict("First region bridge operation requires a proven absent Redis preimage"); + } + UUID operationId = UUID.randomUUID(); + return writePreparedBridge( + transaction, + currentRevision, + currentEvidence, + inputs, + ownerStatus, + operationId); + }); + } + + /** + * Records a binding-local ACK only after the bridge owner's separate Lua readback capability, + * current World/Entity sources, and current durable region owner have all been revalidated. + */ + RegionBridgeAcknowledgement acknowledgeRegionBridge( + CanonicalGameplayBindingRegionBridgeObligation prepared, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolvedRegion, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference runtimeReference, + CanonicalGameplayRegionRuntimeStatus ownerStatus, + CanonicalGameplayRegionLeaseRedisOwner.BindingReadback readback, + Instant acknowledgedAt) { + requireNoAmbientTransaction(); + Objects.requireNonNull(prepared, "prepared"); + Objects.requireNonNull(readback, "readback"); + Objects.requireNonNull(acknowledgedAt, "acknowledgedAt"); + CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence = + readProvisionalCasEvidence(prepared.transitionId()); + BridgeInputs inputs = + requireBridgeInputs( + expectedEvidence, worldRequest, resolvedRegion, runtimeReference, ownerStatus); + if (!matchesPreparedOperation(prepared, inputs) + || !readback.runtimeEntityId().equals(runtimeReference.runtimeEntityId()) + || !readback.sessionId().equals(expectedEvidence.candidate().identity().sessionId()) + || !readback.bindingGeneration() + .equals(expectedEvidence.candidate().bindingGeneration()) + || readback.regionEpoch() != ownerStatus.regionEpoch() + || !readback.executorFence().equals(ownerStatus.executorFence()) + || !readback.leaseTokenCorrelation().equals(ownerStatus.leaseTokenCorrelation())) { + throw conflict("Exact fenced bridge readback does not match the prepared operation"); + } + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = + loadProvisionalCasEvidence(transaction, prepared.transitionId(), true); + requireSameProvisionalOperation(expectedEvidence, currentEvidence); + BridgeInputs currentInputs = + requireBridgeInputs( + currentEvidence, worldRequest, resolvedRegion, runtimeReference, ownerStatus); + if (!inputs.equals(currentInputs) || currentEvidence.expectedPrior() != null) { + throw conflict("Region bridge sources changed before durable acknowledgement"); + } + requireCurrentRegionOwner(transaction, ownerStatus); + Record regionRow = + transaction.fetchOne( + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE", + prepared.transitionId()); + if (regionRow == null) throw conflict("Region bridge obligation is missing"); + CanonicalGameplayBindingRegionBridgeObligation current = toRegionObligation(regionRow); + if (!matchesPreparedOperation(current, inputs) + || !current.bridgeOperationId().equals(prepared.bridgeOperationId()) + || !Objects.equals(current.executorFence(), ownerStatus.executorFence()) + || !Objects.equals( + current.leaseTokenCorrelation(), ownerStatus.leaseTokenCorrelation())) { + throw conflict("Prepared region bridge grant or source changed before acknowledgement"); + } + if (current.status() + == CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { + if (!ownerStatus.executorFence().equals(readback.executorFence()) + || !current.redisReadbackDigest().equals(readback.digest())) { + throw conflict("A completed region acknowledgement has different readback provenance"); + } + return new RegionBridgeAcknowledgement(current); + } + BigInteger oldRevision = currentEvidence.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + writeRevisionRows(transaction, currentEvidence, oldRevision, nextRevision); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET status = 'ACKNOWLEDGED', redis_readback_digest = ?," + + " acknowledged_at = ?, inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'REQUIRED'" + + " AND bridge_operation_id = ? AND executor_fence = ?" + + " AND lease_token_correlation = ? AND inventory_revision = ?", + readback.digest(), + OffsetDateTime.ofInstant(acknowledgedAt, ZoneOffset.UTC), + decimal(nextRevision), + prepared.transitionId(), + prepared.bridgeOperationId(), + decimal(ownerStatus.executorFence()), + ownerStatus.leaseTokenCorrelation(), + decimal(oldRevision)), + "Region bridge obligation changed before acknowledgement commit"); + bumpInventoryClock(transaction, currentRevision, nextRevision); + Record acknowledgedRow = + transaction.fetchOne( + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", + prepared.transitionId()); + CanonicalGameplayBindingRegionBridgeObligation acknowledged = + acknowledgedRow == null ? null : toRegionObligation(acknowledgedRow); + if (acknowledged == null + || acknowledged.status() + != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED + || !acknowledged.bridgeOperationId().equals(prepared.bridgeOperationId()) + || !acknowledged.executorFence().equals(ownerStatus.executorFence()) + || !acknowledged.leaseTokenCorrelation().equals(ownerStatus.leaseTokenCorrelation()) + || !acknowledged.redisReadbackDigest().equals(readback.digest()) + || !acknowledged.acknowledgedAt().equals(acknowledgedAt) + || !acknowledged.inventoryRevision().equals(nextRevision)) { + throw conflict("Region bridge acknowledgement did not survive exact SQL readback"); + } + return new RegionBridgeAcknowledgement(acknowledged); + }); + } + + private CanonicalGameplayBindingRegionBridgeObligation rewritePreparedBridgeForCurrentGrant( + DSLContext transaction, + BigInteger currentRevision, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + Record regionRow, + CanonicalGameplayBindingRegionBridgeObligation existing, + BridgeInputs inputs, + CanonicalGameplayRegionRuntimeStatus ownerStatus) { + BigInteger oldRevision = evidence.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + writeRevisionRows(transaction, evidence, oldRevision, nextRevision); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET status = 'REQUIRED', executor_fence = ?, lease_token_correlation = ?," + + " redis_readback_digest = NULL, acknowledged_at = NULL, inventory_revision = ?" + + " WHERE transition_id = ? AND bridge_operation_id = ?" + + " AND inventory_revision = ?", + decimal(ownerStatus.executorFence()), + ownerStatus.leaseTokenCorrelation(), + decimal(nextRevision), + evidence.transition().transitionId(), + existing.bridgeOperationId(), + decimal(oldRevision)), + "Prepared region bridge changed before current-grant revalidation"); + bumpInventoryClock(transaction, currentRevision, nextRevision); + return toRegionObligation( + Objects.requireNonNull( + transaction.fetchOne( + "SELECT * FROM " + + REGION_OBLIGATION + + " WHERE transition_id = ? AND bridge_operation_id = ?", + evidence.transition().transitionId(), + existing.bridgeOperationId()), + "prepared region bridge row must survive current-grant readback")); + } + + private CanonicalGameplayBindingRegionBridgeObligation writePreparedBridge( + DSLContext transaction, + BigInteger currentRevision, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + BridgeInputs inputs, + CanonicalGameplayRegionRuntimeStatus ownerStatus, + UUID operationId) { + BigInteger oldRevision = evidence.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + writeRevisionRows(transaction, evidence, oldRevision, nextRevision); + Object[] args = + new Object[] { + operationId, + inputs.runtimeEntityId().value(), + inputs.projectionGeneration(), + inputs.projectionFence(), + inputs.workloadNamespace(), + inputs.assignmentId(), + inputs.assignmentIntentDigest(), + inputs.entityReferenceDigest(), + inputs.worldSourceDigest(), + inputs.canonicalRegionId(), + inputs.lifecycleEpoch(), + inputs.lifecycleRowVersion(), + inputs.captureId(), + inputs.graphSha256(), + inputs.preparationInputDigest(), + decimal(ownerStatus.executorFence()), + ownerStatus.leaseTokenCorrelation(), + decimal(nextRevision), + evidence.transition().transitionId(), + decimal(oldRevision) + }; + String sql = + "UPDATE " + + REGION_OBLIGATION + + " SET bridge_operation_id = ?, bridge_preimage_state = 'ABSENT'," + + " runtime_entity_id = ?," + + " entity_projection_generation = ?, entity_projection_fence = ?," + + " entity_workload_namespace = ?, assignment_uuid = ?," + + " assignment_intent_digest = ?, entity_reference_digest = ?," + + " world_source_digest = ?, canonical_region_id = ?," + + " world_lifecycle_epoch = ?, world_lifecycle_row_version = ?," + + " world_capture_id = ?, world_graph_sha256 = ?," + + " world_preparation_input_digest = ?, executor_fence = ?," + + " lease_token_correlation = ?, inventory_revision = ?" + + " WHERE transition_id = ? AND " + + "bridge_operation_id IS NULL" + + " AND inventory_revision = ?"; + requireOne( + transaction.execute(sql, args), + "Region bridge operation compare-and-set lost its exact obligation"); + bumpInventoryClock(transaction, currentRevision, nextRevision); + Record row = + transaction.fetchOne( + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", + evidence.transition().transitionId()); + CanonicalGameplayBindingRegionBridgeObligation result = + row == null ? null : toRegionObligation(row); + if (result == null || !matchesPreparedOperation(result, inputs)) { + throw conflict("Region bridge operation did not survive durable SQL readback"); + } + return result; + } + + private static void writeRevisionRows( + DSLContext transaction, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + BigInteger oldRevision, + BigInteger nextRevision) { + UUID transitionId = evidence.transition().transitionId(); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET inventory_revision = ? WHERE transition_id = ?" + + " AND status = 'PROVISIONAL' AND inventory_revision = ?" + + " AND candidate_binding_ref = ? AND candidate_binding_generation = ?", + decimal(nextRevision), + transitionId, + decimal(oldRevision), + evidence.candidate().bindingRef().bytes(), + decimal(evidence.candidate().bindingGeneration())), + "Provisional transition changed before region bridge revision"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET inventory_revision = ? WHERE binding_ref = ? AND transition_id = ?" + + " AND lifecycle = 'PROVISIONAL' AND binding_generation = ?" + + " AND inventory_revision = ?", + decimal(nextRevision), + evidence.candidate().bindingRef().bytes(), + transitionId, + decimal(evidence.candidate().bindingGeneration()), + decimal(oldRevision)), + "Provisional candidate changed before region bridge revision"); + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(oldRevision)), + "Candidate account obligation changed before region bridge revision"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(oldRevision)), + "Issuer obligation changed before region bridge revision"); + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET inventory_revision = ? WHERE reservation_id = ? AND transition_id = ?" + + " AND lifecycle = 'RESERVED' AND inventory_revision = ?", + decimal(nextRevision), + evidence.candidateReservation().reservationId(), + transitionId, + decimal(oldRevision)), + "Candidate issuer reservation changed before region bridge revision"); + } + + private static void bumpInventoryClock( + DSLContext transaction, BigInteger currentRevision, BigInteger nextRevision) { + requireOne( + transaction.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = ? WHERE singleton_id = 1 AND inventory_revision = ?", + decimal(nextRevision), + decimal(currentRevision)), + "Inventory revision compare-and-set lost during region bridge operation"); + } + + private static boolean matchesPreparedOperation( + CanonicalGameplayBindingRegionBridgeObligation obligation, BridgeInputs inputs) { + return obligation.bridgeOperationId() != null + && "ABSENT".equals(obligation.bridgePreimageState()) + && obligation.runtimeEntityId() == inputs.runtimeEntityId().value() + && obligation.entityProjectionGeneration() == inputs.projectionGeneration() + && obligation.entityProjectionFence() == inputs.projectionFence() + && obligation.entityWorkloadNamespace().equals(inputs.workloadNamespace()) + && obligation.assignmentId().equals(inputs.assignmentId()) + && obligation.assignmentIntentDigest().equals(inputs.assignmentIntentDigest()) + && obligation.entityReferenceDigest().equals(inputs.entityReferenceDigest()) + && obligation.worldSourceDigest().equals(inputs.worldSourceDigest()) + && obligation.canonicalRegionId().equals(inputs.canonicalRegionId()) + && obligation.worldLifecycleEpoch() == inputs.lifecycleEpoch() + && obligation.worldLifecycleRowVersion() == inputs.lifecycleRowVersion() + && obligation.worldCaptureId().equals(inputs.captureId()) + && obligation.worldGraphSha256().equals(inputs.graphSha256()) + && obligation.worldPreparationInputDigest().equals(inputs.preparationInputDigest()); + } + + private static void requireExactBridgePreimage( + CanonicalGameplayRegionLeaseRedisOwner.BindingPreimage preimage, + BridgeInputs inputs, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayRegionRuntimeStatus ownerStatus) { + if (!preimage.runtimeEntityId().equals(inputs.runtimeEntityId()) + || !preimage.sessionId().equals(evidence.candidate().identity().sessionId()) + || !preimage.bindingGeneration().equals(evidence.candidate().bindingGeneration()) + || preimage.regionEpoch() != ownerStatus.regionEpoch() + || !preimage.executorFence().equals(ownerStatus.executorFence()) + || !preimage.leaseTokenCorrelation().equals(ownerStatus.leaseTokenCorrelation())) { + throw conflict("Region binding preimage proof does not match the current grant and tuple"); + } + } + + private static BridgeInputs requireBridgeInputs( + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolvedRegion, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference reference, + CanonicalGameplayRegionRuntimeStatus ownerStatus) { + Objects.requireNonNull(worldRequest, "worldRequest"); + Objects.requireNonNull(resolvedRegion, "resolvedRegion"); + Objects.requireNonNull(reference, "runtimeReference"); + Objects.requireNonNull(ownerStatus, "ownerStatus"); + if (evidence.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || evidence.candidate().lifecycle() + != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL + || evidence.expectedPrior() != null + || evidence.transition().expectedPriorBindingRef() != null + || evidence.transition().expectedPriorBindingGeneration() != null) { + throw conflict("Region bridge applies only to the selected initial PROVISIONAL NEW"); + } + CanonicalGameplayBindingIdentity identity = evidence.candidate().identity(); + var target = worldRequest.getExpectedTarget(); + var assignment = resolvedRegion.lifecycleAssignment(); + if (worldRequest.getSchemaVersion() != 1 + || !worldRequest.getUnknownFields().asMap().isEmpty() + || !reference.target().equals(target) + || !reference.assignmentUuid().toString().equals(worldRequest.getAssignmentUuid()) + || !reference.canonicalAccountUuid().toString().equals(worldRequest.getCanonicalAccountUuid()) + || !reference.characterUuid().toString().equals(worldRequest.getCharacterUuid()) + || !reference.intentDigest().equals(worldRequest.getAssignmentIntentDigest()) + || !identity.accountId().toString().equals(worldRequest.getCanonicalAccountUuid()) + || !identity.characterId().toString().equals(worldRequest.getCharacterUuid()) + || !identity.tenantId().toString().equals(target.getCanonicalTenantUuid()) + || !identity.gameInstanceId().toString().equals(target.getGameInstanceId()) + || !identity.playableStateNamespaceId() + .toString() + .equals(target.getPlayableStateNamespaceUuid()) + || !"SHARED".equals(identity.playableStateScope()) + || !reference.runtimeEntityId().tenantId().equals(identity.tenantId()) + || !reference.runtimeEntityId().gameInstanceId().equals(identity.gameInstanceId().toString()) + || !identity.tenantId().equals(assignment.request().canonicalTenantId()) + || !identity.gameInstanceId().equals(assignment.request().canonicalGameInstanceId()) + || !identity.regionId().equals(assignment.operationalRegionId()) + || !identity.regionId().equals(resolvedRegion.operationalRegionId()) + || !identity.regionEpoch().equals(BigInteger.valueOf(ownerStatus.regionEpoch())) + || !reference.workloadNamespace().equals(assignment.request().targetNamespace()) + || !identity.tenantId().equals(ownerStatus.tenantId()) + || !identity.gameInstanceId().equals(ownerStatus.gameInstanceId()) + || !resolvedRegion.canonicalRegionInstanceId().equals(ownerStatus.canonicalRegionId()) + || !resolvedRegion.operationalRegionId().equals(ownerStatus.regionId()) + || !assignment.captureId().equals(ownerStatus.captureId()) + || !assignment.graphSha256().equals(ownerStatus.graphSha256()) + || !assignment.preparationInputDigest().equals(ownerStatus.preparationInputDigest()) + || !assignment.request().equals(ownerStatus.lifecycleRequest()) + || assignment.lifecycleEpoch() != ownerStatus.lifecycleEpoch() + || assignment.lifecycleRowVersion() != ownerStatus.lifecycleRowVersion() + || ownerStatus.paused() + || !CanonicalGameplayRegionRedisKeys.tenantRegionTag( + ownerStatus.tenantId(), ownerStatus.gameInstanceId(), ownerStatus.regionId()) + .equals(ownerStatus.tenantRegionTag())) { + throw conflict("Entity, World, binding, and region owner scopes do not form one exact join"); + } + return new BridgeInputs( + reference.runtimeEntityId(), + reference.projectionGeneration(), + reference.projectionFence(), + reference.workloadNamespace(), + reference.assignmentUuid(), + reference.intentDigest(), + CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(reference), + CanonicalGameplayRegionBindingBridgeProofs.worldSourceDigest(worldRequest, resolvedRegion), + resolvedRegion.canonicalRegionInstanceId(), + assignment.lifecycleEpoch(), + assignment.lifecycleRowVersion(), + assignment.captureId(), + assignment.graphSha256(), + assignment.preparationInputDigest()); + } + + private static void requireCurrentRegionOwner( + DSLContext transaction, CanonicalGameplayRegionRuntimeStatus expected) { + Record row = + transaction.fetchOne( + "SELECT * FROM game_session_region_runtime_status" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR SHARE", + expected.tenantId(), + expected.gameInstanceId(), + expected.regionId()); + if (row == null + || !Objects.equals(row.get("canonical_region_id", UUID.class), expected.canonicalRegionId()) + || !Objects.equals(row.get("tenant_region_tag", String.class), expected.tenantRegionTag()) + || !Objects.equals(row.get("region_epoch", Long.class), expected.regionEpoch()) + || !Objects.equals(row.get("executor_fence", Long.class), expected.executorFence().longValueExact()) + || !Objects.equals( + row.get("lease_token_correlation", String.class), expected.leaseTokenCorrelation()) + || !Objects.equals(row.get("owner_service", String.class), expected.ownerService()) + || !Objects.equals(row.get("owner_instance_id", String.class), expected.ownerInstanceId()) + || !Objects.equals(row.get("lifecycle_epoch", Long.class), expected.lifecycleEpoch()) + || !Objects.equals(row.get("lifecycle_row_version", Long.class), expected.lifecycleRowVersion()) + || !Objects.equals(row.get("capture_id", UUID.class), expected.captureId()) + || !Arrays.equals( + row.get("lifecycle_request_bytes", byte[].class), + expected.lifecycleRequest().canonicalBytes()) + || !Objects.equals(row.get("graph_sha256", String.class), expected.graphSha256()) + || !Objects.equals(row.get("preparation_input_digest", String.class), expected.preparationInputDigest()) + || !Boolean.FALSE.equals(row.get("paused", Boolean.class)) + || !Objects.equals(row.get("last_committed_tick_id", Long.class), expected.lastCommittedTickId()) + || !Objects.equals(row.get("last_committed_tick_batch_id", String.class), expected.lastCommittedTickBatchId())) { + throw conflict("Durable region owner, timeline, or executor fence changed"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw conflict("Region bridge repository calls require no ambient SQL transaction"); + } + } + + private record BridgeInputs( + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId, + long projectionGeneration, + long projectionFence, + String workloadNamespace, + UUID assignmentId, + String assignmentIntentDigest, + String entityReferenceDigest, + String worldSourceDigest, + UUID canonicalRegionId, + long lifecycleEpoch, + long lifecycleRowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest) {} + + /** Inventory-issued result of the exact durable region ACK and its independent SQL readback. */ + static final class RegionBridgeAcknowledgement { + private final CanonicalGameplayBindingRegionBridgeObligation obligation; + + private RegionBridgeAcknowledgement( + CanonicalGameplayBindingRegionBridgeObligation obligation) { + if (obligation.status() + != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { + throw conflict("Only a persisted region bridge ACK can create its receipt"); + } + this.obligation = obligation; + } + + CanonicalGameplayBindingRegionBridgeObligation obligation() { + return obligation; + } + } + /** * Reads a lease-bound PROVISIONAL decision from its existing transition and current inventory. * The supplied Account lease is only an expected value; all returned decision fields are loaded @@ -1409,8 +1961,13 @@ private static void requireExactProvisionalRows( || !regionObligation.sessionId().equals(candidate.identity().sessionId()) || !regionObligation.regionId().equals(candidate.identity().regionId()) || !regionObligation.regionEpoch().equals(candidate.identity().regionEpoch()) - || regionObligation.status() - != CanonicalGameplayBindingRegionBridgeObligation.Status.REQUIRED + || (regionObligation.status() + != CanonicalGameplayBindingRegionBridgeObligation.Status.REQUIRED + && regionObligation.status() + != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) + || (regionObligation.status() + == CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED + && prior != null) || !regionObligation.inventoryRevision().equals(transition.inventoryRevision())) { throw conflict("Durable issuer or region obligations differ from this exact transition"); } @@ -2585,8 +3142,11 @@ private static void requireExactStoredObligations( transaction.fetchOne( "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE", request.transitionId()); + String regionStatus = + regionObligation == null ? null : regionObligation.get("status", String.class); if (regionObligation == null - || !"REQUIRED".equals(regionObligation.get("status", String.class)) + || (!"REQUIRED".equals(regionStatus) && !"ACKNOWLEDGED".equals(regionStatus)) + || ("ACKNOWLEDGED".equals(regionStatus) && expectedPriorRef != null) || !Arrays.equals( regionObligation.get("binding_ref", byte[].class), request.candidate().bindingRef().bytes()) @@ -3079,7 +3639,27 @@ private static CanonicalGameplayBindingRegionBridgeObligation toRegionObligation readBigInteger(row, "region_epoch"), CanonicalGameplayBindingRegionBridgeObligation.Status.valueOf( row.get("status", String.class)), - readBigInteger(row, "inventory_revision")); + readBigInteger(row, "inventory_revision"), + row.get("bridge_operation_id", UUID.class), + row.get("bridge_preimage_state", String.class), + row.get("runtime_entity_id", Long.class), + row.get("entity_projection_generation", Long.class), + row.get("entity_projection_fence", Long.class), + row.get("entity_workload_namespace", String.class), + row.get("assignment_uuid", UUID.class), + row.get("assignment_intent_digest", String.class), + row.get("entity_reference_digest", String.class), + row.get("world_source_digest", String.class), + row.get("canonical_region_id", UUID.class), + row.get("world_lifecycle_epoch", Long.class), + row.get("world_lifecycle_row_version", Long.class), + row.get("world_capture_id", UUID.class), + row.get("world_graph_sha256", String.class), + row.get("world_preparation_input_digest", String.class), + nullableBigInteger(row, "executor_fence"), + row.get("lease_token_correlation", String.class), + row.get("redis_readback_digest", String.class), + nullableInstant(row, "acknowledged_at")); } private static CanonicalGameplayBindingIdentity toIdentity(Record row) { @@ -3106,6 +3686,11 @@ private static BigInteger nullableBigInteger(Record row, String name) { return value == null ? null : value.toBigIntegerExact(); } + private static Instant nullableInstant(Record row, String name) { + OffsetDateTime value = row.get(name, OffsetDateTime.class); + return value == null ? null : value.toInstant(); + } + private static CanonicalGameplayBindingRef optionalRef(byte[] bytes) { return bytes == null ? null : CanonicalGameplayBindingRef.fromExactBytes(bytes); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java index c6aa5d1e03..84169b204d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwner.java @@ -24,8 +24,7 @@ public CanonicalGameplayIssuerBootstrapCoverageOwner( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource currentStateSource) { this.dsl = Objects.requireNonNull(dsl, "dsl"); - this.partitionRedisOwner = - Objects.requireNonNull(partitionRedisOwner, "partitionRedisOwner"); + this.partitionRedisOwner = Objects.requireNonNull(partitionRedisOwner, "partitionRedisOwner"); this.currentStateSource = Objects.requireNonNull(currentStateSource, "currentStateSource"); } @@ -53,8 +52,7 @@ public CanonicalGameplayIssuerInstalledAnchor completeInitialBootstrap( coverageRepository.readInstalledAnchor( bootstrapOperationId, bootstrapRequestId, initialState); if (installed.isPresent()) { - return readInstalledAnchorPartitions( - plan, installed.get(), coverageRepository, initialState); + return readInstalledAnchorPartitions(plan, installed.get(), coverageRepository, initialState); } CanonicalGameplayIssuerBootstrapMemberOperationRepository memberOperationRepository = @@ -119,7 +117,8 @@ private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchorPartitions( coverageRepository .readInstalledAnchor( installed.bootstrapOperationId(), installed.bootstrapRequestId(), afterReadback) - .orElseThrow(() -> unavailable("Installed issuer anchor disappeared during exact readback")); + .orElseThrow( + () -> unavailable("Installed issuer anchor disappeared during exact readback")); if (!Arrays.equals(installed.exactAnchorBytes(), confirmed.exactAnchorBytes()) || !installed.exactAnchorDigest().equals(confirmed.exactAnchorDigest())) { throw unavailable("Installed issuer anchor changed during physical partition readback"); @@ -145,7 +144,8 @@ private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchorPartitions( CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(expected.incarnation())) || !sameCheckpoint(current.accountCheckpoint(), expected.accountCheckpoint())) { - throw unavailable("Current Account source or stable Redis incarnation changed during bootstrap"); + throw unavailable( + "Current Account source or stable Redis incarnation changed during bootstrap"); } return current; } @@ -220,12 +220,14 @@ private static void requireSamePlan( private static void requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); } private static void requireNoAmbientTransaction() { if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw unavailable("Initial issuer bootstrap completion cannot join an ambient SQL transaction"); + throw unavailable( + "Initial issuer bootstrap completion cannot join an ambient SQL transaction"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java index dee6a30666..0273e77a9c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -22,8 +22,8 @@ import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; import org.jooq.DSLContext; import org.jooq.Record; @@ -32,7 +32,8 @@ /** SQL owner for exact per-partition proof retention and one local initial anchor installation. */ final class CanonicalGameplayIssuerBootstrapCoverageRepository { private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; - private static final String OPERATION = "game_session_canonical_issuer_bootstrap_member_operation"; + private static final String OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; private static final String PROOF = "game_session_canonical_issuer_bootstrap_partition_proof"; private static final String COUNTER = "game_session_canonical_issuer_bootstrap_coverage_counter"; private static final String ANCHOR = "game_session_canonical_issuer_installed_anchor"; @@ -67,7 +68,9 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re requireProofContext(input, currentPlan); Record existing = transaction.fetchOne( - "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", currentPlan.bootstrapIntent().operationId(), input.partitionId()); if (existing != null) { @@ -76,7 +79,9 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re } int inserted = transaction.execute( - "INSERT INTO " + PROOF + " (" + "INSERT INTO " + + PROOF + + " (" + "build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, " + "build_plan_digest, bootstrap_operation_fence, bootstrap_coverage_fence, " + "issuer_inventory_snapshot_revision, layout_version, partition_count, " @@ -120,10 +125,13 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re if (inserted != 1) throw conflict("Exact partition proof did not persist"); Record saved = transaction.fetchOne( - "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ?", input.bootstrapOperationId(), input.partitionId()); - if (saved == null) throw conflict("Exact partition proof is unreadable after persistence"); + if (saved == null) + throw conflict("Exact partition proof is unreadable after persistence"); requireSameProof(saved, input); }); } @@ -176,7 +184,9 @@ void verifyExistingPartitionProof( requireProofContext(input, currentPlan); Record row = transaction.fetchOne( - "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ?", input.bootstrapOperationId(), input.partitionId()); if (row == null) throw conflict("Installed anchor is missing an exact partition proof"); @@ -225,7 +235,9 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( createAnchor(plan, currentState, generation, proof); int inserted = transaction.execute( - "INSERT INTO " + ANCHOR + " (" + "INSERT INTO " + + ANCHOR + + " (" + "issuer_id, bootstrap_operation_id, bootstrap_request_id, build_operation_id, " + "build_plan_digest, control_epoch, issuer_coverage_operation_id, operation_fence, " + "coverage_fence, issuer_inventory_snapshot_revision, layout_version, partition_count, " @@ -236,10 +248,14 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( + "physical_binding_count, aggregate_counted_capacity, partition_proof_root_digest, " + "exact_anchor_bytes, exact_anchor_digest, anchor_state) " + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'INITIAL_INSTALLED' " - + "FROM " + CONTROL + " c WHERE c.issuer_id = ? AND c.state = 'INITIAL_BOOTSTRAP_INTENT' " + + "FROM " + + CONTROL + + " c WHERE c.issuer_id = ? AND c.state = 'INITIAL_BOOTSTRAP_INTENT' " + "AND c.control_epoch = ? AND c.current_operation_id = ? " + "AND c.current_operation_fence = ? AND c.current_coverage_fence = ? " - + "AND NOT EXISTS (SELECT 1 FROM " + ANCHOR + " a WHERE a.issuer_id = c.issuer_id)", + + "AND NOT EXISTS (SELECT 1 FROM " + + ANCHOR + + " a WHERE a.issuer_id = c.issuer_id)", anchor.issuerId(), anchor.bootstrapOperationId(), anchor.bootstrapRequestId(), @@ -278,8 +294,7 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( intent.coverageFence()); if (inserted != 1) throw conflict("Exact initial issuer anchor compare-and-set refused"); Record saved = - transaction.fetchOne( - "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); + transaction.fetchOne("SELECT * FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); if (saved == null) throw conflict("Installed issuer anchor is unreadable after its CAS"); CanonicalGameplayIssuerInstalledAnchor result = loadAnchor(saved); requireSameAnchor(result, anchor); @@ -293,7 +308,8 @@ private CanonicalGameplayIssuerInstalledAnchor createAnchor( BigInteger generation, ProofSummary proof) { CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); - CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout = intent.layoutDescriptor(); + CanonicalGameplayIssuerLayoutBootstrapIntent.LayoutDescriptor layout = + intent.layoutDescriptor(); CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint source = intent.sourceCheckpoint(); byte[] incarnationBytes = @@ -346,10 +362,12 @@ private ProofSummary verifyCompleteProof( intent.operationId()); BigInteger partitionCount = intent.layoutDescriptor().partitionCount(); if (!BigInteger.valueOf(proofRows.size()).equals(partitionCount)) { - throw conflict("Initial issuer anchor requires one positive physical proof per finite partition"); + throw conflict( + "Initial issuer anchor requires one positive physical proof per finite partition"); } - Map worksByOrdinal = new HashMap<>(); + Map worksByOrdinal = + new HashMap<>(); Map exactOperationValues = new HashMap<>(); Map expectedReservationsByPartition = new HashMap<>(); Map expectedCapacityByPartition = new HashMap<>(); @@ -365,10 +383,13 @@ private ProofSummary verifyCompleteProof( } List operations = transaction.fetch( - "SELECT * FROM " + OPERATION + " WHERE bootstrap_operation_id = ? ORDER BY work_ordinal", + "SELECT * FROM " + + OPERATION + + " WHERE bootstrap_operation_id = ? ORDER BY work_ordinal", intent.operationId()); if (operations.size() != plan.memberWorks().size()) { - throw conflict("Finite coverage cannot complete while any SQL member operation is unresolved"); + throw conflict( + "Finite coverage cannot complete while any SQL member operation is unresolved"); } for (Record operation : operations) { long ordinal = requireNonNegativeLong(operation, "work_ordinal"); @@ -389,7 +410,8 @@ private ProofSummary verifyCompleteProof( if (exactOperationValues.putIfAbsent(work.reservationId(), bytes) != null) { throw conflict("Finite SQL work contains a duplicate reservation identity"); } - if (Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) expectedBindingCount++; + if (Boolean.TRUE.equals(operation.get("expected_binding_present", Boolean.class))) + expectedBindingCount++; } BigInteger expectedPartition = BigInteger.ZERO; @@ -397,22 +419,27 @@ private ProofSummary verifyCompleteProof( BigInteger bindingCount = BigInteger.ZERO; BigInteger aggregateCountedCapacity = BigInteger.ZERO; BigInteger expectedAggregateCapacity = BigInteger.valueOf(expectedCapacityCount); - BigInteger aggregateBound = partitionCount.multiply(intent.layoutDescriptor().partitionCapacity()); + BigInteger aggregateBound = + partitionCount.multiply(intent.layoutDescriptor().partitionCapacity()); MessageDigest root = sha256Digest(); for (Record row : proofRows) { BigInteger partitionId = readInteger(row, "partition_id"); if (!partitionId.equals(expectedPartition)) { - throw conflict("Initial issuer physical proof set is not the exact contiguous finite range"); + throw conflict( + "Initial issuer physical proof set is not the exact contiguous finite range"); } requireProofMatchesPlan(row, plan, expectedIncarnationBytes, partitionId); - int expectedPartitionReservations = expectedReservationsByPartition.getOrDefault(partitionId, 0); + int expectedPartitionReservations = + expectedReservationsByPartition.getOrDefault(partitionId, 0); int expectedPartitionCapacity = expectedCapacityByPartition.getOrDefault(partitionId, 0); - Map fields = decodeFieldSet(requireBytes(row, "exact_physical_field_set_bytes")); + Map fields = + decodeFieldSet(requireBytes(row, "exact_physical_field_set_bytes")); byte[] metadata = fields.get(METADATA_FIELD); if (metadata == null || !Arrays.equals(metadata, requireBytes(row, "exact_metadata_bytes"))) { throw conflict("Partition proof does not retain its exact common physical metadata"); } - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata(metadata, metadata); + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.requireExactMetadata( + metadata, metadata); Set reservationIds = new HashSet<>(); int physicalBindings = 0; int physicalCapacity = 0; @@ -457,7 +484,9 @@ private ProofSummary verifyCompleteProof( } else { CanonicalGameplayBindingRef bindingRef; try { - bindingRef = CanonicalGameplayBindingRef.fromExactBytes(fieldName.getBytes(StandardCharsets.UTF_8)); + bindingRef = + CanonicalGameplayBindingRef.fromExactBytes( + fieldName.getBytes(StandardCharsets.UTF_8)); } catch (RuntimeException malformed) { throw conflict("Physical issuer binding field has invalid canonical identity"); } @@ -469,7 +498,9 @@ private ProofSummary verifyCompleteProof( } } expectedFieldNames.addAll( - reservationIds.stream().map(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec::reservationField).toList()); + reservationIds.stream() + .map(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec::reservationField) + .toList()); if (!expectedFieldNames.equals(fields.keySet()) || physicalReservations != expectedPartitionReservations || physicalCapacity != expectedPartitionCapacity @@ -478,18 +509,24 @@ private ProofSummary verifyCompleteProof( || physicalBindings != readInt(row, "physical_binding_count") || physicalCapacity != readInt(row, "physical_counted_capacity_count") || fields.size() != readInt(row, "physical_field_count") - || !expectedAggregateCapacity.equals(readInteger(row, "planned_aggregate_capacity_count"))) { + || !expectedAggregateCapacity.equals( + readInteger(row, "planned_aggregate_capacity_count"))) { throw conflict("Physical partition proof differs from SQL work or capacity expectations"); } - if (BigInteger.valueOf(physicalCapacity).compareTo(intent.layoutDescriptor().partitionCapacity()) > 0) { + if (BigInteger.valueOf(physicalCapacity) + .compareTo(intent.layoutDescriptor().partitionCapacity()) + > 0) { throw conflict("Physical issuer partition exceeds its pinned reservation capacity"); } reservationCount = reservationCount.add(BigInteger.valueOf(physicalReservations)); bindingCount = bindingCount.add(BigInteger.valueOf(physicalBindings)); aggregateCountedCapacity = aggregateCountedCapacity.add(BigInteger.valueOf(physicalCapacity)); updateRoot(root, partitionId.toString().getBytes(StandardCharsets.US_ASCII)); - updateRoot(root, CanonicalGameplayIssuerMemberV2Codec.sha256( - requireBytes(row, "exact_physical_field_set_bytes")).getBytes(StandardCharsets.US_ASCII)); + updateRoot( + root, + CanonicalGameplayIssuerMemberV2Codec.sha256( + requireBytes(row, "exact_physical_field_set_bytes")) + .getBytes(StandardCharsets.US_ASCII)); expectedPartition = expectedPartition.add(BigInteger.ONE); } if (!expectedPartition.equals(partitionCount) @@ -497,7 +534,8 @@ private ProofSummary verifyCompleteProof( || !bindingCount.equals(BigInteger.valueOf(expectedBindingCount)) || !aggregateCountedCapacity.equals(expectedAggregateCapacity) || aggregateCountedCapacity.compareTo(aggregateBound) > 0) { - throw conflict("Initial issuer proof does not cover complete reservation and aggregate capacity"); + throw conflict( + "Initial issuer proof does not cover complete reservation and aggregate capacity"); } return new ProofSummary( proofRows.size(), @@ -555,7 +593,9 @@ private static void requireOperationMatches( || !reservation.transitionId().equals(work.transitionId()) || !reservation.partitionId().equals(work.plannedPartitionId()) || !reservation.issuerCoverageOperationId().equals(work.originalIssuerCoverageOperationId()) - || !reservation.issuerCoverageOperationFence().equals(work.originalIssuerCoverageOperationFence()) + || !reservation + .issuerCoverageOperationFence() + .equals(work.originalIssuerCoverageOperationFence()) || !reservation.coverageFence().equals(work.originalCoverageFence()) || !reservation.inventorySnapshotRevision().equals(work.originalInventorySnapshotRevision()) || !work.reservationLifecycle().equals(reservation.lifecycle().name()) @@ -565,21 +605,32 @@ private static void requireOperationMatches( || !anchor.coverageFence().equals(intent.coverageFence()) || !anchor.issuerInventorySnapshotRevision().equals(intent.inventorySnapshotRevision()) || !value.issuerControlEpoch().equals(intent.controlEpoch()) - || !Arrays.equals(value.layoutDescriptor().exactDescriptorBytes(), intent.layoutDescriptor().exactDescriptorBytes()) + || !Arrays.equals( + value.layoutDescriptor().exactDescriptorBytes(), + intent.layoutDescriptor().exactDescriptorBytes()) || !Arrays.equals(work.bindingRef(), value.owner().bindingRef().bytes()) - || !Boolean.valueOf(work.countsTowardCapacity()).equals(row.get("counts_toward_capacity", Boolean.class)) - || !Boolean.valueOf(isBindingPresent(row)).equals(row.get("expected_binding_present", Boolean.class)) + || !Boolean.valueOf(work.countsTowardCapacity()) + .equals(row.get("counts_toward_capacity", Boolean.class)) + || !Boolean.valueOf(isBindingPresent(row)) + .equals(row.get("expected_binding_present", Boolean.class)) || !work.reservationId().equals(requireUuid(row, "reservation_id")) - || !work.reservationSourceRowDigest().equals(requireText(row, "reservation_source_row_digest")) - || !work.originalIssuerCoverageOperationId().equals(requireUuid(row, "original_issuer_coverage_operation_id")) - || !work.originalIssuerCoverageOperationFence().equals(readInteger(row, "original_issuer_coverage_operation_fence")) + || !work.reservationSourceRowDigest() + .equals(requireText(row, "reservation_source_row_digest")) + || !work.originalIssuerCoverageOperationId() + .equals(requireUuid(row, "original_issuer_coverage_operation_id")) + || !work.originalIssuerCoverageOperationFence() + .equals(readInteger(row, "original_issuer_coverage_operation_fence")) || !work.originalCoverageFence().equals(readInteger(row, "original_coverage_fence")) - || !work.originalInventorySnapshotRevision().equals(readInteger(row, "original_inventory_snapshot_revision")) + || !work.originalInventorySnapshotRevision() + .equals(readInteger(row, "original_inventory_snapshot_revision")) || !intent.operationId().equals(requireUuid(row, "bootstrap_anchor_operation_id")) || !intent.operationFence().equals(readInteger(row, "bootstrap_anchor_operation_fence")) || !intent.coverageFence().equals(readInteger(row, "bootstrap_anchor_coverage_fence")) - || !intent.inventorySnapshotRevision().equals(readInteger(row, "bootstrap_anchor_inventory_snapshot_revision"))) { - throw conflict("SQL member operation does not match its exact reservation, anchor, and plan tuple"); + || !intent + .inventorySnapshotRevision() + .equals(readInteger(row, "bootstrap_anchor_inventory_snapshot_revision"))) { + throw conflict( + "SQL member operation does not match its exact reservation, anchor, and plan tuple"); } } @@ -600,19 +651,25 @@ private static void requireProofMatchesPlan( || !plan.planDigest().equals(requireText(row, "build_plan_digest")) || !intent.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) || !intent.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) - || !intent.inventorySnapshotRevision().equals(readInteger(row, "issuer_inventory_snapshot_revision")) + || !intent + .inventorySnapshotRevision() + .equals(readInteger(row, "issuer_inventory_snapshot_revision")) || !layout.layoutVersion().equals(readInteger(row, "layout_version")) || !layout.partitionCount().equals(readInteger(row, "partition_count")) || !layout.partitionCapacity().equals(readInteger(row, "partition_capacity")) || !layout.mappingIdentity().equals(requireText(row, "mapping_identity")) - || !Arrays.equals(layout.exactDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) + || !Arrays.equals( + layout.exactDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) || !layout.descriptorDigest().equals(requireText(row, "layout_descriptor_digest")) - || !Arrays.equals(source.exactCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) + || !Arrays.equals( + source.exactCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) || !source.checkpointDigest().equals(requireText(row, "source_checkpoint_digest")) || !Arrays.equals(expectedEvent, optionalBytes(row, "source_event_bytes")) - || !Objects.equals(source.latestIssuerEventDigest(), row.get("source_event_digest", String.class)) + || !Objects.equals( + source.latestIssuerEventDigest(), row.get("source_event_digest", String.class)) || !Arrays.equals(expectedIncarnationBytes, exactIncarnation) - || !CanonicalGameplayIssuerMemberV2Codec.sha256(exactIncarnation).equals(requireText(row, "incarnation_digest")) + || !CanonicalGameplayIssuerMemberV2Codec.sha256(exactIncarnation) + .equals(requireText(row, "incarnation_digest")) || !partitionId.equals(readInteger(row, "partition_id")) || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state"))) { throw conflict("Persisted physical proof differs from the exact current plan tuple"); @@ -671,7 +728,8 @@ private static void requireAnchorMatchesPlan( || !Objects.equals(anchor.sourceEventDigest(), source.latestIssuerEventDigest()) || !Arrays.equals(anchor.incarnationBytes(), currentIncarnation) || !sameCheckpoint(current.accountCheckpoint(), source)) { - throw conflict("Installed issuer anchor does not match the exact current source and initial layout"); + throw conflict( + "Installed issuer anchor does not match the exact current source and initial layout"); } } @@ -694,7 +752,7 @@ private static void requireCounterCoversAnchor( anchor.issuerId()); if (counter == null || readInteger(counter, "last_issued_coverage_generation") - .compareTo(anchor.globalCoverageGeneration()) + .compareTo(anchor.globalCoverageGeneration()) < 0) { throw conflict("Installed anchor generation is beyond the current global issuer counter"); } @@ -711,7 +769,8 @@ private static void requireSameAnchor( CanonicalGameplayIssuerInstalledAnchor expected) { if (!Arrays.equals(actual.exactAnchorBytes(), expected.exactAnchorBytes()) || !actual.exactAnchorDigest().equals(expected.exactAnchorDigest())) { - throw conflict("Installed issuer anchor readback differs from its exact owner-issued pointer"); + throw conflict( + "Installed issuer anchor readback differs from its exact owner-issued pointer"); } } @@ -756,7 +815,9 @@ private static CanonicalGameplayIssuerInstalledAnchor loadAnchor(Record row) { private BigInteger allocateGlobalCoverageGeneration(DSLContext transaction) { transaction.execute( - "INSERT INTO " + COUNTER + " (issuer_id, last_issued_coverage_generation, counter_version) " + "INSERT INTO " + + COUNTER + + " (issuer_id, last_issued_coverage_generation, counter_version) " + "VALUES (?, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", ISSUER); Record counter = @@ -766,10 +827,12 @@ private BigInteger allocateGlobalCoverageGeneration(DSLContext transaction) { BigInteger previous = readInteger(counter, "last_issued_coverage_generation"); long version = requireNonNegativeLong(counter, "counter_version"); BigInteger next = previous.add(BigInteger.ONE); - if (next.toString().length() > 256) throw conflict("Global issuer coverage generation is outside its bound"); + if (next.toString().length() > 256) + throw conflict("Global issuer coverage generation is outside its bound"); int updated = transaction.execute( - "UPDATE " + COUNTER + "UPDATE " + + COUNTER + " SET last_issued_coverage_generation = ?, counter_version = ?, updated_at = CURRENT_TIMESTAMP " + "WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = ?", next, @@ -795,8 +858,11 @@ private static ProofInput proofInput( || readback.physicalPartitionReservationCount() != physical.reservationCount() || readback.physicalBindingCount() != physical.bindingCount() || readback.physicalCountedCapacityCount() != physical.countedReservationCount() - || !readback.plannedAggregateCapacityCount().equals(physical.plannedAggregateCapacityCount())) { - throw conflict("Physical Redis readback capability differs from its exact prepared field set"); + || !readback + .plannedAggregateCapacityCount() + .equals(physical.plannedAggregateCapacityCount())) { + throw conflict( + "Physical Redis readback capability differs from its exact prepared field set"); } return new ProofInput( plan.buildOperationId(), @@ -878,28 +944,36 @@ private static void requireSameProof(Record row, ProofInput expected) { || !expected.planDigest().equals(requireText(row, "build_plan_digest")) || !expected.operationFence().equals(readInteger(row, "bootstrap_operation_fence")) || !expected.coverageFence().equals(readInteger(row, "bootstrap_coverage_fence")) - || !expected.snapshotRevision().equals(readInteger(row, "issuer_inventory_snapshot_revision")) + || !expected + .snapshotRevision() + .equals(readInteger(row, "issuer_inventory_snapshot_revision")) || !expected.layoutVersion().equals(readInteger(row, "layout_version")) || !expected.partitionCount().equals(readInteger(row, "partition_count")) || !expected.partitionCapacity().equals(readInteger(row, "partition_capacity")) || !expected.mappingIdentity().equals(requireText(row, "mapping_identity")) - || !Arrays.equals(expected.layoutDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) + || !Arrays.equals( + expected.layoutDescriptorBytes(), requireBytes(row, "layout_descriptor_bytes")) || !expected.layoutDescriptorDigest().equals(requireText(row, "layout_descriptor_digest")) - || !Arrays.equals(expected.sourceCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) + || !Arrays.equals( + expected.sourceCheckpointBytes(), requireBytes(row, "source_checkpoint_bytes")) || !expected.sourceCheckpointDigest().equals(requireText(row, "source_checkpoint_digest")) || !Arrays.equals(expected.sourceEventBytes(), optionalBytes(row, "source_event_bytes")) - || !Objects.equals(expected.sourceEventDigest(), row.get("source_event_digest", String.class)) + || !Objects.equals( + expected.sourceEventDigest(), row.get("source_event_digest", String.class)) || !Arrays.equals(expected.incarnationBytes(), requireBytes(row, "incarnation_bytes")) || !expected.incarnationDigest().equals(requireText(row, "incarnation_digest")) || !expected.partitionId().equals(readInteger(row, "partition_id")) || !Arrays.equals(expected.metadataBytes(), requireBytes(row, "exact_metadata_bytes")) - || !Arrays.equals(expected.fieldSetBytes(), requireBytes(row, "exact_physical_field_set_bytes")) + || !Arrays.equals( + expected.fieldSetBytes(), requireBytes(row, "exact_physical_field_set_bytes")) || !expected.fieldSetDigest().equals(requireText(row, "exact_physical_field_set_digest")) || expected.fieldCount() != readInt(row, "physical_field_count") || expected.reservationCount() != readInt(row, "physical_reservation_count") || expected.bindingCount() != readInt(row, "physical_binding_count") || expected.countedCapacityCount() != readInt(row, "physical_counted_capacity_count") - || !expected.aggregateCountedCapacity().equals(readInteger(row, "planned_aggregate_capacity_count")) + || !expected + .aggregateCountedCapacity() + .equals(readInteger(row, "planned_aggregate_capacity_count")) || !"EXACT_PHYSICAL_READBACK".equals(requireText(row, "proof_state"))) { throw conflict("Exact partition proof retry changed its original physical bytes or tuple"); } @@ -907,9 +981,11 @@ private static void requireSameProof(Record row, ProofInput expected) { private static byte[] encodeFieldSet(Map fields) { List> entries = new ArrayList<>(fields.entrySet()); - entries.sort((left, right) -> compareUnsigned( - left.getKey().getBytes(StandardCharsets.UTF_8), - right.getKey().getBytes(StandardCharsets.UTF_8))); + entries.sort( + (left, right) -> + compareUnsigned( + left.getKey().getBytes(StandardCharsets.UTF_8), + right.getKey().getBytes(StandardCharsets.UTF_8))); try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (DataOutputStream output = new DataOutputStream(bytes)) { @@ -920,10 +996,12 @@ private static byte[] encodeFieldSet(Map fields) { writeBytes(output, entry.getValue()); } } - if (bytes.size() > 17 * 1024 * 1024) throw conflict("Physical field proof exceeds its bounded storage limit"); + if (bytes.size() > 17 * 1024 * 1024) + throw conflict("Physical field proof exceeds its bounded storage limit"); return bytes.toByteArray(); } catch (IOException impossible) { - throw new IllegalStateException("Could not encode exact issuer physical readback", impossible); + throw new IllegalStateException( + "Could not encode exact issuer physical readback", impossible); } } @@ -932,22 +1010,30 @@ private static Map decodeFieldSet(byte[] encoded) { throw conflict("Persisted issuer physical field proof is outside its bound"); } try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(encoded))) { - if (!Arrays.equals(readBytes(input, 256), FIELDSET_MAGIC.getBytes(StandardCharsets.US_ASCII))) { + if (!Arrays.equals( + readBytes(input, 256), FIELDSET_MAGIC.getBytes(StandardCharsets.US_ASCII))) { throw conflict("Persisted issuer physical field proof has an unsupported encoding"); } int count = input.readInt(); - if (count < 1 || count > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS) { + if (count < 1 + || count > CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS) { throw conflict("Persisted issuer physical field count is outside its bound"); } Map fields = new HashMap<>(); byte[] previous = null; for (int index = 0; index < count; index++) { - byte[] rawField = readBytes(input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_BINDING_REF_BYTES); - if (rawField.length == 0 || (previous != null && compareUnsigned(previous, rawField) >= 0)) { + byte[] rawField = + readBytes( + input, + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_BINDING_REF_BYTES); + if (rawField.length == 0 + || (previous != null && compareUnsigned(previous, rawField) >= 0)) { throw conflict("Persisted issuer physical fields are duplicated or noncanonical"); } String field = decodeUtf8(rawField); - byte[] value = readBytes(input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_VALUE_BYTES); + byte[] value = + readBytes( + input, CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_VALUE_BYTES); if (value.length == 0 || fields.putIfAbsent(field, value) != null) { throw conflict("Persisted issuer physical field is empty or duplicated"); } @@ -967,7 +1053,8 @@ private static void writeBytes(DataOutputStream output, byte[] bytes) throws IOE private static byte[] readBytes(DataInputStream input, int maxBytes) throws IOException { int length = input.readInt(); - if (length < 0 || length > maxBytes) throw conflict("Issuer physical proof field exceeds its bound"); + if (length < 0 || length > maxBytes) + throw conflict("Issuer physical proof field exceeds its bound"); byte[] value = input.readNBytes(length); if (value.length != length) throw conflict("Issuer physical proof field is truncated"); return value; @@ -975,7 +1062,8 @@ private static byte[] readBytes(DataInputStream input, int maxBytes) throws IOEx private static String decodeUtf8(byte[] bytes) { try { - return StandardCharsets.UTF_8.newDecoder() + return StandardCharsets.UTF_8 + .newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) .decode(java.nio.ByteBuffer.wrap(bytes)) @@ -1113,12 +1201,35 @@ private record ProofInput( fieldSetBytes = fieldSetBytes.clone(); } - @Override public byte[] layoutDescriptorBytes() { return layoutDescriptorBytes.clone(); } - @Override public byte[] sourceCheckpointBytes() { return sourceCheckpointBytes.clone(); } - @Override public byte[] sourceEventBytes() { return sourceEventBytes == null ? null : sourceEventBytes.clone(); } - @Override public byte[] incarnationBytes() { return incarnationBytes.clone(); } - @Override public byte[] metadataBytes() { return metadataBytes.clone(); } - @Override public byte[] fieldSetBytes() { return fieldSetBytes.clone(); } + @Override + public byte[] layoutDescriptorBytes() { + return layoutDescriptorBytes.clone(); + } + + @Override + public byte[] sourceCheckpointBytes() { + return sourceCheckpointBytes.clone(); + } + + @Override + public byte[] sourceEventBytes() { + return sourceEventBytes == null ? null : sourceEventBytes.clone(); + } + + @Override + public byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + @Override + public byte[] metadataBytes() { + return metadataBytes.clone(); + } + + @Override + public byte[] fieldSetBytes() { + return fieldSetBytes.clone(); + } } private record ProofSummary( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java index 427c587275..e80b4b8124 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java @@ -85,13 +85,15 @@ public final class CanonicalGameplayIssuerInstalledAnchor { this.buildPlanDigest = requireDigest(buildPlanDigest, "buildPlanDigest"); this.issuerId = requireIssuer(issuerId); this.controlEpoch = requirePositive(controlEpoch, "controlEpoch"); - this.issuerCoverageOperationId = requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId"); + this.issuerCoverageOperationId = + requireNonNil(issuerCoverageOperationId, "issuerCoverageOperationId"); this.operationFence = requirePositive(operationFence, "operationFence"); this.coverageFence = requirePositive(coverageFence, "coverageFence"); if (!this.issuerCoverageOperationId.equals(this.bootstrapOperationId) || !this.controlEpoch.equals(this.operationFence) || this.operationFence.equals(this.coverageFence)) { - throw new IllegalArgumentException("Initial anchor must retain its exact distinct operation tuple"); + throw new IllegalArgumentException( + "Initial anchor must retain its exact distinct operation tuple"); } this.issuerInventorySnapshotRevision = requirePositive(issuerInventorySnapshotRevision, "issuerInventorySnapshotRevision"); @@ -104,13 +106,17 @@ public final class CanonicalGameplayIssuerInstalledAnchor { } this.layoutDescriptorBytes = nonEmpty(layoutDescriptorBytes, "layoutDescriptorBytes"); this.layoutDescriptorDigest = requireDigest(layoutDescriptorDigest, "layoutDescriptorDigest"); - requireDigestMatches(this.layoutDescriptorBytes, this.layoutDescriptorDigest, "layout descriptor"); + requireDigestMatches( + this.layoutDescriptorBytes, this.layoutDescriptorDigest, "layout descriptor"); this.issuerAuthGeneration = requirePositive(issuerAuthGeneration, "issuerAuthGeneration"); this.sourceCheckpointBytes = nonEmpty(sourceCheckpointBytes, "sourceCheckpointBytes"); this.sourceCheckpointDigest = requireDigest(sourceCheckpointDigest, "sourceCheckpointDigest"); - requireDigestMatches(this.sourceCheckpointBytes, this.sourceCheckpointDigest, "source checkpoint"); - this.sourceEventBytes = sourceEventBytes == null ? null : nonEmpty(sourceEventBytes, "sourceEventBytes"); - this.sourceEventDigest = sourceEventDigest == null ? null : requireDigest(sourceEventDigest, "sourceEventDigest"); + requireDigestMatches( + this.sourceCheckpointBytes, this.sourceCheckpointDigest, "source checkpoint"); + this.sourceEventBytes = + sourceEventBytes == null ? null : nonEmpty(sourceEventBytes, "sourceEventBytes"); + this.sourceEventDigest = + sourceEventDigest == null ? null : requireDigest(sourceEventDigest, "sourceEventDigest"); if ((this.sourceEventBytes == null) != (this.sourceEventDigest == null)) { throw new IllegalArgumentException("Account source event bytes and digest must be paired"); } @@ -120,31 +126,37 @@ public final class CanonicalGameplayIssuerInstalledAnchor { this.incarnationBytes = nonEmpty(incarnationBytes, "incarnationBytes"); this.incarnationDigest = requireDigest(incarnationDigest, "incarnationDigest"); requireDigestMatches(this.incarnationBytes, this.incarnationDigest, "stable incarnation"); - this.globalCoverageGeneration = requirePositive(globalCoverageGeneration, "globalCoverageGeneration"); + this.globalCoverageGeneration = + requirePositive(globalCoverageGeneration, "globalCoverageGeneration"); if (partitionProofCount < 1 || !BigInteger.valueOf(partitionProofCount).equals(partitionCount) || physicalReservationCount < 0 || physicalBindingCount < 0 || physicalBindingCount > physicalReservationCount) { - throw new IllegalArgumentException("Installed anchor must retain the complete finite proof counts"); + throw new IllegalArgumentException( + "Installed anchor must retain the complete finite proof counts"); } this.partitionProofCount = partitionProofCount; this.physicalReservationCount = physicalReservationCount; this.physicalBindingCount = physicalBindingCount; - this.aggregateCountedCapacity = Objects.requireNonNull(aggregateCountedCapacity, "aggregateCountedCapacity"); + this.aggregateCountedCapacity = + Objects.requireNonNull(aggregateCountedCapacity, "aggregateCountedCapacity"); if (aggregateCountedCapacity.signum() < 0 || aggregateCountedCapacity.compareTo(partitionCount.multiply(partitionCapacity)) > 0 || aggregateCountedCapacity.compareTo(BigInteger.valueOf(physicalReservationCount)) > 0) { - throw new IllegalArgumentException("Installed anchor aggregate capacity is outside its finite bound"); + throw new IllegalArgumentException( + "Installed anchor aggregate capacity is outside its finite bound"); } - this.partitionProofRootDigest = requireDigest(partitionProofRootDigest, "partitionProofRootDigest"); + this.partitionProofRootDigest = + requireDigest(partitionProofRootDigest, "partitionProofRootDigest"); this.exactAnchorBytes = encodeExactAnchor(); this.exactAnchorDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactAnchorBytes); if ((storedExactAnchorBytes == null) != (storedExactAnchorDigest == null) || (storedExactAnchorBytes != null && (!java.util.Arrays.equals(this.exactAnchorBytes, storedExactAnchorBytes) || !this.exactAnchorDigest.equals(storedExactAnchorDigest)))) { - throw new IllegalArgumentException("Stored installed-anchor bytes differ from their exact tuple"); + throw new IllegalArgumentException( + "Stored installed-anchor bytes differ from their exact tuple"); } } @@ -209,37 +221,129 @@ private byte[] encodeExactAnchor() { }); } - public UUID bootstrapOperationId() { return bootstrapOperationId; } - public UUID bootstrapRequestId() { return bootstrapRequestId; } - public UUID buildOperationId() { return buildOperationId; } - public String buildPlanDigest() { return buildPlanDigest; } - public String issuerId() { return issuerId; } - public BigInteger controlEpoch() { return controlEpoch; } - public UUID issuerCoverageOperationId() { return issuerCoverageOperationId; } - public BigInteger operationFence() { return operationFence; } - public BigInteger coverageFence() { return coverageFence; } - public BigInteger issuerInventorySnapshotRevision() { return issuerInventorySnapshotRevision; } - public BigInteger layoutVersion() { return layoutVersion; } - public BigInteger partitionCount() { return partitionCount; } - public BigInteger partitionCapacity() { return partitionCapacity; } - public String mappingIdentity() { return mappingIdentity; } - public byte[] layoutDescriptorBytes() { return layoutDescriptorBytes.clone(); } - public String layoutDescriptorDigest() { return layoutDescriptorDigest; } - public BigInteger issuerAuthGeneration() { return issuerAuthGeneration; } - public byte[] sourceCheckpointBytes() { return sourceCheckpointBytes.clone(); } - public String sourceCheckpointDigest() { return sourceCheckpointDigest; } - public byte[] sourceEventBytes() { return sourceEventBytes == null ? null : sourceEventBytes.clone(); } - public String sourceEventDigest() { return sourceEventDigest; } - public byte[] incarnationBytes() { return incarnationBytes.clone(); } - public String incarnationDigest() { return incarnationDigest; } - public BigInteger globalCoverageGeneration() { return globalCoverageGeneration; } - public long partitionProofCount() { return partitionProofCount; } - public long physicalReservationCount() { return physicalReservationCount; } - public long physicalBindingCount() { return physicalBindingCount; } - public BigInteger aggregateCountedCapacity() { return aggregateCountedCapacity; } - public String partitionProofRootDigest() { return partitionProofRootDigest; } - public byte[] exactAnchorBytes() { return exactAnchorBytes.clone(); } - public String exactAnchorDigest() { return exactAnchorDigest; } + public UUID bootstrapOperationId() { + return bootstrapOperationId; + } + + public UUID bootstrapRequestId() { + return bootstrapRequestId; + } + + public UUID buildOperationId() { + return buildOperationId; + } + + public String buildPlanDigest() { + return buildPlanDigest; + } + + public String issuerId() { + return issuerId; + } + + public BigInteger controlEpoch() { + return controlEpoch; + } + + public UUID issuerCoverageOperationId() { + return issuerCoverageOperationId; + } + + public BigInteger operationFence() { + return operationFence; + } + + public BigInteger coverageFence() { + return coverageFence; + } + + public BigInteger issuerInventorySnapshotRevision() { + return issuerInventorySnapshotRevision; + } + + public BigInteger layoutVersion() { + return layoutVersion; + } + + public BigInteger partitionCount() { + return partitionCount; + } + + public BigInteger partitionCapacity() { + return partitionCapacity; + } + + public String mappingIdentity() { + return mappingIdentity; + } + + public byte[] layoutDescriptorBytes() { + return layoutDescriptorBytes.clone(); + } + + public String layoutDescriptorDigest() { + return layoutDescriptorDigest; + } + + public BigInteger issuerAuthGeneration() { + return issuerAuthGeneration; + } + + public byte[] sourceCheckpointBytes() { + return sourceCheckpointBytes.clone(); + } + + public String sourceCheckpointDigest() { + return sourceCheckpointDigest; + } + + public byte[] sourceEventBytes() { + return sourceEventBytes == null ? null : sourceEventBytes.clone(); + } + + public String sourceEventDigest() { + return sourceEventDigest; + } + + public byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + public String incarnationDigest() { + return incarnationDigest; + } + + public BigInteger globalCoverageGeneration() { + return globalCoverageGeneration; + } + + public long partitionProofCount() { + return partitionProofCount; + } + + public long physicalReservationCount() { + return physicalReservationCount; + } + + public long physicalBindingCount() { + return physicalBindingCount; + } + + public BigInteger aggregateCountedCapacity() { + return aggregateCountedCapacity; + } + + public String partitionProofRootDigest() { + return partitionProofRootDigest; + } + + public byte[] exactAnchorBytes() { + return exactAnchorBytes.clone(); + } + + public String exactAnchorDigest() { + return exactAnchorDigest; + } private static byte[] encode(IoWriter writer) { try { @@ -254,10 +358,14 @@ private static byte[] encode(IoWriter writer) { } private static void writeText(DataOutputStream output, String value) throws IOException { - writeBytes(output, Objects.requireNonNull(value, "exact text").getBytes(java.nio.charset.StandardCharsets.UTF_8)); + writeBytes( + output, + Objects.requireNonNull(value, "exact text") + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); } - private static void writeBigInteger(DataOutputStream output, BigInteger value) throws IOException { + private static void writeBigInteger(DataOutputStream output, BigInteger value) + throws IOException { writeText(output, Objects.requireNonNull(value, "exact counter").toString()); } @@ -278,12 +386,14 @@ private static void writeNullableText(DataOutputStream output, String value) thr private static UUID requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); - if (value.equals(new UUID(0L, 0L))) throw new IllegalArgumentException(name + " must not be nil"); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); return value; } private static String requireIssuer(String value) { - if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER.equals(value)) { + if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER.equals( + value)) { throw new IllegalArgumentException("Installed anchor issuer scope is not canonical"); } return value; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java new file mode 100644 index 0000000000..fe2f1c877d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; + +/** Manual owner for the initial-NEW region binding mutation and its durable local ACK. */ +final class CanonicalGameplayRegionBindingBridgeOwner { + private final CanonicalGameplayRegionLeaseOwner regionLeaseOwner; + private final CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient; + + CanonicalGameplayRegionBindingBridgeOwner( + CanonicalGameplayRegionLeaseOwner regionLeaseOwner, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) { + this.regionLeaseOwner = Objects.requireNonNull(regionLeaseOwner, "regionLeaseOwner"); + this.entityReferenceClient = Objects.requireNonNull(entityReferenceClient, "entityReferenceClient"); + } + + /** Acquires the real region grant/fence, then performs the selected first-NEW bridge. */ + CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement installAndBridge( + UUID transitionId, + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { + return bridge(regionLeaseOwner.installForTransition(transitionId, request)); + } + + /** Returns the closed same-grant capability so a lost bridge reply can retry without reacquire. */ + CanonicalGameplayRegionLeaseOwner.Installation installForTransition( + UUID transitionId, + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { + return regionLeaseOwner.installForTransition(transitionId, request); + } + + /** Executes only an exact first-NEW bridge from a privately created region installation. */ + CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( + CanonicalGameplayRegionLeaseOwner.Installation installation) { + Objects.requireNonNull(installation, "installation"); + CanonicalGameplayRegionLeaseOwner.BridgeContext initial = + regionLeaseOwner.currentBridgeContext(installation); + if (initial.evidence().expectedPrior() != null + || initial.evidence().transition().status() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.PROVISIONAL) { + throw unavailable(); + } + + ReadPreseededActorRuntimeReferenceRequest entityRequest = + entityRequest(installation.worldRequest); + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference reference = + entityReferenceClient.read(entityRequest); + CanonicalGameplayRegionLeaseOwner.RegionBridgePreimage initialPreimage = + regionLeaseOwner.probeRegionSessionBinding(installation, reference); + regionLeaseOwner.prepareBridge(installation, initialPreimage, reference); + + // The stable operation and current SQL fence are durable before this first physical write. + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference beforeWriteReference = + entityReferenceClient.read(entityRequest); + if (!sameReference(reference, beforeWriteReference)) throw unavailable(); + CanonicalGameplayRegionLeaseOwner.RegionBridgePreimage beforeWritePreimage = + regionLeaseOwner.probeRegionSessionBinding(installation, beforeWriteReference); + CanonicalGameplayBindingRegionBridgeObligation prepared = + regionLeaseOwner.prepareBridge( + installation, beforeWritePreimage, beforeWriteReference); + regionLeaseOwner.applyRegionSessionBinding(installation, beforeWriteReference); + + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference currentReference = + entityReferenceClient.read(entityRequest); + if (!sameReference(reference, currentReference)) throw unavailable(); + CanonicalGameplayRegionLeaseOwner.RegionBridgePreimage beforeReadbackPreimage = + regionLeaseOwner.probeRegionSessionBinding(installation, currentReference); + prepared = + regionLeaseOwner.prepareBridge( + installation, beforeReadbackPreimage, currentReference); + + CanonicalGameplayRegionLeaseRedisOwner.BindingReadback readback = + regionLeaseOwner.readBackRegionSessionBinding( + installation, beforeReadbackPreimage.context().status(), currentReference); + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference afterReadbackReference = + entityReferenceClient.read(entityRequest); + if (!sameReference(reference, afterReadbackReference)) throw unavailable(); + CanonicalGameplayRegionLeaseOwner.RegionBridgePreimage beforeAckPreimage = + regionLeaseOwner.probeRegionSessionBinding(installation, afterReadbackReference); + if (!beforeReadbackPreimage.context().status().equals(beforeAckPreimage.context().status())) { + throw unavailable(); + } + prepared = + regionLeaseOwner.prepareBridge( + installation, beforeAckPreimage, afterReadbackReference); + + return regionLeaseOwner.acknowledgeBridge( + installation, + prepared, + beforeAckPreimage.context(), + afterReadbackReference, + readback); + } + + private static ReadPreseededActorRuntimeReferenceRequest entityRequest( + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { + return ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(request.getAssignmentUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setExpectedTarget(request.getExpectedTarget()) + .setCharacterUuid(request.getCharacterUuid()) + .setIntentDigest(request.getAssignmentIntentDigest()) + .build(); + } + + private static boolean sameReference( + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference expected, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference actual) { + return CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(expected) + .equals(CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(actual)); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Canonical first-NEW region bridge requires the exact current fenced source and readback"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java new file mode 100644 index 0000000000..3537746e81 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java @@ -0,0 +1,40 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.time.Clock; +import java.time.Duration; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import org.jooq.DSLContext; + +/** Explicit manual composition; this first-NEW bridge has no Spring or default registration. */ +final class CanonicalGameplayRegionBindingBridgeOwnerFactory { + private CanonicalGameplayRegionBindingBridgeOwnerFactory() {} + + static CanonicalGameplayRegionBindingBridgeOwner compose( + DSLContext dsl, + RedisClient coordinationRedis, + RedisScriptCatalog scriptCatalog, + CanonicalGameplayRegionIncarnationSource incarnationSource, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock) { + Objects.requireNonNull(entityReferenceClient, "entityReferenceClient"); + return new CanonicalGameplayRegionBindingBridgeOwner( + CanonicalGameplayRegionLeaseOwnerFactory.compose( + dsl, + coordinationRedis, + scriptCatalog, + incarnationSource, + worldRegionResolver, + runtimeIdentity, + leaseTtl, + clock), + entityReferenceClient); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java new file mode 100644 index 0000000000..da0fbcabc7 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.google.protobuf.MessageLite; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.UUID; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; + +/** Closed digest projections for exact bridge sources and independently observed readback. */ +final class CanonicalGameplayRegionBindingBridgeProofs { + private CanonicalGameplayRegionBindingBridgeProofs() {} + + static String entityReferenceDigest( + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference reference) { + var response = + ReadPreseededActorRuntimeReferenceResponse.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(reference.assignmentUuid().toString()) + .setCanonicalAccountUuid(reference.canonicalAccountUuid().toString()) + .setCharacterUuid(reference.characterUuid().toString()) + .setIntentDigest(reference.intentDigest()) + .setExpectedTarget(reference.target()) + .setPublishedOwnerProofDigest(reference.publishedOwnerProofDigest()) + .setRuntimeEntityId(reference.runtimeEntityId().value()) + .setProjectionGeneration(reference.projectionGeneration()) + .setProjectionFence(reference.projectionFence()) + .setCorePayload(reference.corePayload()) + .build(); + return sha256( + reference.workloadNamespace().getBytes(StandardCharsets.UTF_8), response.toByteArray()); + } + + static String worldSourceDigest( + CanonicalInitialPlayerLocationRequest request, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolved) { + var assignment = resolved.lifecycleAssignment(); + return sha256( + request.toByteArray(), + resolved.observation().toByteArray(), + assignment.request().canonicalBytes(), + assignment.lifecycleStatus().getBytes(StandardCharsets.US_ASCII), + Long.toString(assignment.lifecycleEpoch()).getBytes(StandardCharsets.US_ASCII), + Long.toString(assignment.lifecycleRowVersion()).getBytes(StandardCharsets.US_ASCII), + assignment.canonicalRegionId().toString().getBytes(StandardCharsets.US_ASCII), + assignment.operationalRegionId().toString().getBytes(StandardCharsets.US_ASCII), + assignment.captureId().toString().getBytes(StandardCharsets.US_ASCII), + assignment.graphSha256().getBytes(StandardCharsets.US_ASCII), + assignment.preparationInputDigest().getBytes(StandardCharsets.US_ASCII)); + } + + static String timelinePreparationDigest( + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalInitialPlayerLocationRequest request, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolved, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + String worldDigest, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation, + String absenceProofDigest) { + var identity = evidence.candidate().identity(); + return sha256( + uuid(evidence.transition().transitionId()), + evidence.candidate().bindingRef().bytes(), + identity.accountId().toString().getBytes(StandardCharsets.US_ASCII), + identity.tenantId().toString().getBytes(StandardCharsets.US_ASCII), + identity.playableStateNamespaceId().toString().getBytes(StandardCharsets.US_ASCII), + identity.characterId().toString().getBytes(StandardCharsets.US_ASCII), + identity.playableStateScope().getBytes(StandardCharsets.US_ASCII), + identity.gameInstanceId().toString().getBytes(StandardCharsets.US_ASCII), + Long.toString(identity.runtimeGameInstanceId()).getBytes(StandardCharsets.US_ASCII), + identity.sessionId().getBytes(StandardCharsets.US_ASCII), + evidence.candidate().bindingGeneration().toString().getBytes(StandardCharsets.US_ASCII), + identity.regionId().toString().getBytes(StandardCharsets.US_ASCII), + identity.regionEpoch().toString().getBytes(StandardCharsets.US_ASCII), + source.canonicalRegionId().toString().getBytes(StandardCharsets.US_ASCII), + source.regionId().toString().getBytes(StandardCharsets.US_ASCII), + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId()) + .getBytes(StandardCharsets.US_ASCII), + source.lifecycleRequest().canonicalBytes(), + Long.toString(source.lifecycleEpoch()).getBytes(StandardCharsets.US_ASCII), + Long.toString(source.lifecycleRowVersion()).getBytes(StandardCharsets.US_ASCII), + source.captureId().toString().getBytes(StandardCharsets.US_ASCII), + source.graphSha256().getBytes(StandardCharsets.US_ASCII), + source.preparationInputDigest().getBytes(StandardCharsets.US_ASCII), + worldDigest.getBytes(StandardCharsets.US_ASCII), + incarnation.scopeBytes(), + incarnation.canonicalBytes(), + absenceProofDigest.getBytes(StandardCharsets.US_ASCII), + request.toByteArray(), + resolved.observation().toByteArray()); + } + + static String initialMetaDigest(String tag, UUID operationId, String sourceDigest) { + String baseline = + "region_epoch=1\n" + + "current_tick_id=-1\n" + + "current_tick_state=APPLIED\n" + + "first_timeline_operation_id=" + + operationId + + "\nfirst_timeline_source_digest=" + + sourceDigest; + return sha256(tag.getBytes(StandardCharsets.US_ASCII), baseline.getBytes(StandardCharsets.US_ASCII)); + } + + private static byte[] uuid(UUID value) { + return value.toString().getBytes(StandardCharsets.US_ASCII); + } + + static String redisReadbackDigest( + CanonicalGameplayRegionRuntimeStatus status, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId, + String sessionId, + String bindingGeneration) { + String exact = + status.tenantRegionTag() + + "\n" + + CanonicalGameplayRegionRedisKeys.sessionBinding( + status.tenantId(), + status.gameInstanceId(), + status.regionId(), + runtimeEntityId.value()) + + "\n" + + runtimeEntityId.tenantId() + + "\n" + + runtimeEntityId.gameInstanceId() + + "\n" + + runtimeEntityId.value() + + "\n" + + sessionId + + "\n" + + bindingGeneration + + "\n" + + status.regionEpoch() + + "\n" + + status.executorFence() + + "\n" + + status.leaseTokenCorrelation(); + return sha256(exact.getBytes(StandardCharsets.US_ASCII)); + } + + private static String sha256(MessageLite... values) { + byte[][] parts = new byte[values.length][]; + for (int index = 0; index < values.length; index++) parts[index] = values[index].toByteArray(); + return sha256(parts); + } + + private static String sha256(byte[]... parts) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (byte[] part : parts) { + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(part.length).array()); + digest.update(part); + } + return HexFormat.of().formatHex(digest.digest()); + } catch (Exception impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionIncarnationSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionIncarnationSource.java new file mode 100644 index 0000000000..12d39d9568 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionIncarnationSource.java @@ -0,0 +1,349 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.IOException; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Narrow current-source port for the stable Redis deployment incarnation used by region prep. */ +@FunctionalInterface +interface CanonicalGameplayRegionIncarnationSource { + JsonMapper JSON = JsonMapper.builder().build(); + + /** Reads current typed deployment evidence for exactly this canonical region key scope. */ + StableEvidence readCurrent(RegionScope scope); + + static CanonicalGameplayRegionIncarnationSource unavailable() { + return scope -> { + throw new IllegalStateException("Stable region incarnation source is unavailable"); + }; + } + + record RegionScope(UUID tenantId, UUID gameInstanceId, UUID regionId, String tenantRegionTag) { + public RegionScope { + requireNonNil(tenantId); + requireNonNil(gameInstanceId); + requireNonNil(regionId); + String derived = + CanonicalGameplayRegionRedisKeys.tenantRegionTag(tenantId, gameInstanceId, regionId); + if (!derived.equals(tenantRegionTag)) throw unavailableException(); + } + + static RegionScope from(CanonicalGameplayRegionRuntimeStatusRepository.Source source) { + Objects.requireNonNull(source, "source"); + return new RegionScope( + source.tenantId(), + source.gameInstanceId(), + source.regionId(), + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId())); + } + + byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", "firemud.gs.region-incarnation-scope/v1"); + value.put("tenantId", tenantId.toString()); + value.put("gameInstanceId", gameInstanceId.toString()); + value.put("regionId", regionId.toString()); + value.put("tenantRegionTag", tenantRegionTag); + byte[] bytes = CanonicalGameplayRegionIncarnationSource.canonicalBytes(value); + if (bytes.length > 4096) throw unavailableException(); + return bytes; + } + } + + /** + * Complete stable incarnation value. This carries the established deployment evidence shape; + * it does not verify a source, create a production provider, or reuse Account intent context. + */ + record StableEvidence( + RegionScope scope, + String attestorBinding, + String acceptedAttestationDigest, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + targetDeploymentEvidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest, + boolean qualifiedNonResetProfile, + TimelineInitializationQualification timelineInitializationQualification) { + public StableEvidence { + Objects.requireNonNull(scope, "scope"); + requireText(attestorBinding); + requireDigest(acceptedAttestationDigest); + Objects.requireNonNull(targetDeploymentEvidence, "targetDeploymentEvidence"); + requireDigest(coordOpsRoAclDigest); + requireDigest(coordRedisConfigObservedDigest); + if (!qualifiedNonResetProfile) throw unavailableException(); + Objects.requireNonNull(timelineInitializationQualification, "timelineInitializationQualification"); + if (targetDeploymentEvidence.canonicalNodeSet().size() > 2048 + || scope.canonicalBytes().length > 4096 + || stableValueBytes( + scope, + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest) + .length + > 65536 + || timelineInitializationQualification.canonicalBytes().length > 8192 + || !timelineInitializationQualification.matches( + scope, + stableDigest( + scope, + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest))) { + throw unavailableException(); + } + if (timelineInitializationQualification.qualifiedNonResetProfile() + != qualifiedNonResetProfile) { + throw unavailableException(); + } + } + + static StableEvidence fromCurrentSource( + RegionScope scope, + String attestorBinding, + String acceptedAttestationDigest, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + targetDeploymentEvidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest, + boolean qualifiedNonResetProfile, + String qualifiedNonResetProfileId, + String qualifiedNonResetProfileEvidenceDigest, + boolean recoveryInactive, + String recoveryInactiveEvidenceDigest, + boolean noUnfinishedPriorWork, + String noUnfinishedPriorWorkEvidenceDigest) { + String stableDigest = + CanonicalGameplayRegionIncarnationSource.stableDigest( + scope, + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest); + return new StableEvidence( + scope, + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest, + qualifiedNonResetProfile, + new TimelineInitializationQualification( + scope, + stableDigest, + qualifiedNonResetProfile, + qualifiedNonResetProfileId, + qualifiedNonResetProfileEvidenceDigest, + recoveryInactive, + recoveryInactiveEvidenceDigest, + noUnfinishedPriorWork, + noUnfinishedPriorWorkEvidenceDigest)); + } + + byte[] scopeBytes() { + return scope.canonicalBytes(); + } + + byte[] stableCanonicalBytes() { + return CanonicalGameplayRegionIncarnationSource.canonicalBytes(stableValue( + scope, + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest)); + } + + byte[] canonicalBytes() { + Map value = + stableValue( + scope, + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest); + value.put("qualifiedNonResetProfile", qualifiedNonResetProfile); + value.put("timelineInitializationQualification", timelineInitializationQualification.toMap()); + byte[] bytes = CanonicalGameplayRegionIncarnationSource.canonicalBytes(value); + if (bytes.length > 65536) throw unavailableException(); + return bytes; + } + + String digest() { + return digestBytes(stableCanonicalBytes()); + } + } + + /** Positive exact-scope evidence for all canonical first-metadata initialization prerequisites. */ + record TimelineInitializationQualification( + RegionScope scope, + String stableIncarnationDigest, + boolean qualifiedNonResetProfile, + String qualifiedNonResetProfileId, + String qualifiedNonResetProfileEvidenceDigest, + boolean recoveryInactive, + String recoveryInactiveEvidenceDigest, + boolean noUnfinishedPriorWork, + String noUnfinishedPriorWorkEvidenceDigest) { + public TimelineInitializationQualification { + Objects.requireNonNull(scope, "scope"); + requireDigest(stableIncarnationDigest); + if (!qualifiedNonResetProfile || !recoveryInactive || !noUnfinishedPriorWork) { + throw unavailableException(); + } + requireText(qualifiedNonResetProfileId); + requireDigest(qualifiedNonResetProfileEvidenceDigest); + requireDigest(recoveryInactiveEvidenceDigest); + requireDigest(noUnfinishedPriorWorkEvidenceDigest); + } + + boolean matches(RegionScope expectedScope, String expectedStableIncarnationDigest) { + return scope.equals(expectedScope) + && stableIncarnationDigest.equals(expectedStableIncarnationDigest) + && qualifiedNonResetProfile + && recoveryInactive + && noUnfinishedPriorWork; + } + + byte[] canonicalBytes() { + return CanonicalGameplayRegionIncarnationSource.canonicalBytes(toMap()); + } + + private Map toMap() { + Map value = new LinkedHashMap<>(); + value.put("scope", scopeMap(scope)); + value.put("stableIncarnationDigest", stableIncarnationDigest); + value.put("qualifiedNonResetProfile", qualifiedNonResetProfile); + value.put("qualifiedNonResetProfileId", qualifiedNonResetProfileId); + value.put("qualifiedNonResetProfileEvidenceDigest", qualifiedNonResetProfileEvidenceDigest); + value.put("recoveryInactive", recoveryInactive); + value.put("recoveryInactiveEvidenceDigest", recoveryInactiveEvidenceDigest); + value.put("noUnfinishedPriorWork", noUnfinishedPriorWork); + value.put("noUnfinishedPriorWorkEvidenceDigest", noUnfinishedPriorWorkEvidenceDigest); + return value; + } + } + + private static String stableDigest( + RegionScope scope, + String attestorBinding, + String acceptedAttestationDigest, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence evidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest) { + return digestBytes( + stableValueBytes( + scope, + attestorBinding, + acceptedAttestationDigest, + evidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest)); + } + + private static byte[] stableValueBytes( + RegionScope scope, + String attestorBinding, + String acceptedAttestationDigest, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence evidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest) { + return canonicalBytes( + stableValue( + scope, + attestorBinding, + acceptedAttestationDigest, + evidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest)); + } + + private static Map stableValue( + RegionScope scope, + String attestorBinding, + String acceptedAttestationDigest, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence evidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest) { + Map value = new LinkedHashMap<>(); + value.put("schema", "firemud.gs.region-stable-incarnation/v1"); + value.put("scope", scopeMap(scope)); + value.put("attestorBinding", attestorBinding); + value.put("acceptedAttestationDigest", acceptedAttestationDigest); + value.put("targetDeploymentEvidence", targetDeploymentEvidenceMap(evidence)); + value.put("coordOpsRoAclDigest", coordOpsRoAclDigest); + value.put("coordRedisConfigObservedDigest", coordRedisConfigObservedDigest); + return value; + } + + private static Map scopeMap(RegionScope scope) { + return Map.of( + "tenantId", scope.tenantId().toString(), + "gameInstanceId", scope.gameInstanceId().toString(), + "regionId", scope.regionId().toString(), + "tenantRegionTag", scope.tenantRegionTag()); + } + + private static Map targetDeploymentEvidenceMap( + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence evidence) { + Map value = new LinkedHashMap<>(); + value.put("deploymentIdentity", evidence.deploymentIdentity()); + value.put("deploymentGeneration", evidence.deploymentGeneration()); + value.put("canonicalNodeSet", evidence.canonicalNodeSet()); + value.put("redisBuildIdentity", evidence.redisBuildIdentity()); + value.put("luaScriptRegistryVersion", evidence.luaScriptRegistryVersion()); + value.put("luaScriptRegistryDigest", evidence.luaScriptRegistryDigest()); + value.put("startupState", evidence.startupState()); + value.put("bootGeneration", evidence.bootGeneration()); + value.put("startupGeneration", evidence.startupGeneration()); + value.put("storageGeneration", evidence.storageGeneration()); + value.put("aofGeneration", evidence.aofGeneration()); + return value; + } + + private static byte[] canonicalBytes(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw unavailableException(); + } + } + + static String digestBytes(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (Exception impossible) { + throw unavailableException(); + } + } + + private static void requireText(String value) { + if (value == null || value.isBlank() || !value.equals(value.trim())) throw unavailableException(); + } + + private static void requireDigest(String value) { + if (value == null || !value.matches("[0-9a-f]{64}")) throw unavailableException(); + } + + private static void requireNonNil(UUID value) { + Objects.requireNonNull(value, "scope UUID"); + if (value.equals(new UUID(0L, 0L))) throw unavailableException(); + } + + private static IllegalStateException unavailableException() { + return new IllegalStateException("Stable region incarnation source is unavailable"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 4cd92958a6..b4199404a0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -5,25 +5,29 @@ import java.time.Duration; import java.time.Instant; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Manually composed owner for an authenticated initial-placement region assignment. It installs and - * revalidates region ownership only; the region session-binding bridge remains unavailable until - * its typed runtime-entity identity source is supplied. + * Manually composed owner for an authenticated initial-placement region assignment. It installs + * region ownership and supplies only same-installation, same-grant capabilities to the selected + * first-NEW session-binding bridge. */ final class CanonicalGameplayRegionLeaseOwner { private final CanonicalGameplayBindingInventoryRepository bindingInventory; private final CanonicalGameplayRegionRuntimeStatusRepository statusRepository; private final CanonicalGameplayRegionLeaseRedisOwner redisOwner; + private final CanonicalGameplayRegionIncarnationSource incarnationSource; private final CanonicalInitialPlayerLocationRegionResolver worldRegionResolver; private final RuntimeIdentity runtimeIdentity; private final Duration leaseTtl; @@ -33,6 +37,7 @@ final class CanonicalGameplayRegionLeaseOwner { CanonicalGameplayBindingInventoryRepository bindingInventory, CanonicalGameplayRegionRuntimeStatusRepository statusRepository, CanonicalGameplayRegionLeaseRedisOwner redisOwner, + CanonicalGameplayRegionIncarnationSource incarnationSource, CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, RuntimeIdentity runtimeIdentity, Duration leaseTtl, @@ -40,6 +45,7 @@ final class CanonicalGameplayRegionLeaseOwner { this.bindingInventory = Objects.requireNonNull(bindingInventory, "bindingInventory"); this.statusRepository = Objects.requireNonNull(statusRepository, "statusRepository"); this.redisOwner = Objects.requireNonNull(redisOwner, "redisOwner"); + this.incarnationSource = Objects.requireNonNull(incarnationSource, "incarnationSource"); this.worldRegionResolver = Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"); this.runtimeIdentity = Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"); this.leaseTtl = Objects.requireNonNull(leaseTtl, "leaseTtl"); @@ -60,22 +66,92 @@ Installation installForTransition( Objects.requireNonNull(worldRequest, "worldRequest"); CanonicalGameplayBindingProvisionalCasEvidence evidence = readCurrentProvisionalEvidence(transitionId); - CanonicalGameplayRegionRuntimeStatusRepository.Source source = - resolveExactSource(worldRequest, evidence); + ResolvedBridgeSource initialResolved = resolveExactBridgeSource(worldRequest, evidence); + CanonicalGameplayRegionRuntimeStatusRepository.Source source = initialResolved.source; + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation = + readCurrentIncarnation(source); long expectedRegionEpoch = exactExpectedRegionEpoch(evidence.candidate().identity().regionEpoch()); CanonicalGameplayRegionRuntimeStatus prior = statusRepository.find(source).orElse(null); if (prior == null && expectedRegionEpoch != 1L) throw unavailable(); if (prior != null && prior.regionEpoch() != expectedRegionEpoch) throw unavailable(); - CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant = - redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; + CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; + if (prior == null) { + preparation = statusRepository.findTimelinePreparation(source).orElse(null); + if (preparation == null) { + CanonicalGameplayRegionLeaseRedisOwner.TimelineAbsenceProof absenceProof = + redisOwner.requireTimelineAbsent(source, incarnation); + preparation = + statusRepository.prepareInitialTimeline( + evidence, + worldRequest, + initialResolved.resolvedRegion, + source, + incarnation, + absenceProof, + clock.instant()); + } + if (!statusRepository.matchesTimelinePreparation( + preparation, + evidence, + worldRequest, + initialResolved.resolvedRegion, + source, + incarnation) + || preparation.phase() + == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INSTALLED) { + throw unavailable(); + } + Optional permit = + statusRepository.beginInitialTimeline(preparation, clock.instant()); + grant = + redisOwner.initializeOrResumeTimeline( + preparation, permit.orElse(null), leaseTtl, runtimeIdentity); + redisOwner.verifyInitializedTimeline(grant, preparation); + requireSameIncarnation(incarnation, readCurrentIncarnation(source)); + ResolvedBridgeSource afterInitWorld = resolveExactBridgeSource(worldRequest, evidence); + requireSameSource(source, afterInitWorld.source); + bindingInventory.requireSameProvisionalSource( + evidence, readCurrentProvisionalEvidence(transitionId)); + preparation = + statusRepository.markRedisInitialized( + preparation, + grant.tokenCorrelation(), + CanonicalGameplayRegionBindingBridgeProofs.initialMetaDigest( + preparation.tenantRegionTag(), + preparation.operationId(), + preparation.sourceDigest()), + clock.instant()); + } else { + preparation = + statusRepository + .findTimelinePreparation(source) + .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); + if (!statusRepository.matchesTimelinePreparation( + preparation, + evidence, + worldRequest, + initialResolved.resolvedRegion, + source, + incarnation) + || preparation.phase() + != CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INSTALLED + && preparation.phase() + != CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.REDIS_INITIALIZED) { + throw unavailable(); + } + grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); + } redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); CanonicalGameplayRegionRuntimeStatusRepository.Source afterAcquire = resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); requireSameSource(source, afterAcquire); redisOwner.renew(grant, leaseTtl); redisOwner.requireCurrent(grant); + requireSameIncarnation(incarnation, readCurrentIncarnation(source)); + redisOwner.verifyInitializedTimeline(grant, preparation); Instant installedAt = clock.instant(); CanonicalGameplayRegionRuntimeStatus installed = @@ -89,6 +165,7 @@ Installation installForTransition( installedAt); redisOwner.requireCurrent(grant); + redisOwner.verifyInitializedTimeline(grant, preparation); CanonicalGameplayRegionRuntimeStatus observed = statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!installed.equals(observed) || observed.paused()) throw unavailable(); @@ -96,29 +173,144 @@ Installation installForTransition( resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); requireSameSource(source, afterInstall); redisOwner.requireCurrent(grant); - return new Installation(transitionId, worldRequest, evidence, source, grant, installed); + requireSameIncarnation(incarnation, readCurrentIncarnation(source)); + redisOwner.verifyInitializedTimeline(grant, preparation); + statusRepository.markTimelineInstalled(preparation, installed, clock.instant()); + redisOwner.requireCurrent(grant); + redisOwner.verifyInitializedTimeline(grant, preparation); + requireSameIncarnation(incarnation, readCurrentIncarnation(source)); + requireSameSource( + source, resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId))); + CanonicalGameplayRegionRuntimeStatus finalStatus = + statusRepository.find(source).orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); + if (!installed.equals(finalStatus) || finalStatus.paused()) throw unavailable(); + return new Installation( + transitionId, worldRequest, evidence, source, incarnation, preparation, grant, installed); } /** * Revalidates the same SQL source, World assignment and acquired lease before any later bridge. */ void revalidateBeforeBridge(Installation installation) { + currentBridgeContext(installation); + } + + BridgeContext currentBridgeContext(Installation installation) { requireNoAmbientTransaction(); Objects.requireNonNull(installation, "installation"); if (!installation.owner.equals(this)) throw unavailable(); CanonicalGameplayBindingProvisionalCasEvidence evidence = readCurrentProvisionalEvidence(installation.transitionId); - if (!installation.evidence.equals(evidence)) throw unavailable(); + bindingInventory.requireSameProvisionalSource(installation.evidence, evidence); + ResolvedBridgeSource resolved = + resolveExactBridgeSource(installation.worldRequest, evidence); CanonicalGameplayRegionRuntimeStatusRepository.Source currentSource = - resolveExactSource(installation.worldRequest, evidence); + resolved.source; requireSameSource(installation.source, currentSource); - redisOwner.renew(installation.grant, leaseTtl); + requireSameIncarnation(installation.incarnation, readCurrentIncarnation(currentSource)); CanonicalGameplayRegionRuntimeStatus current = statusRepository .find(currentSource) .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); if (!installation.status.equals(current) || current.paused()) throw unavailable(); + redisOwner.renew(installation.grant, leaseTtl); redisOwner.requireCurrent(installation.grant); + redisOwner.verifyInitializedTimeline(installation.grant, installation.preparation); + requireSameIncarnation(installation.incarnation, readCurrentIncarnation(currentSource)); + return new BridgeContext(evidence, currentSource, current, resolved.resolvedRegion); + } + + CanonicalGameplayBindingRegionBridgeObligation prepareBridge( + Installation installation, + RegionBridgePreimage preimage, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference reference) { + Objects.requireNonNull(preimage, "preimage"); + BridgeContext context = preimage.context(); + requireOwnedContext(installation, context); + return bindingInventory.prepareRegionBridge( + context.evidence, + installation.worldRequest, + context.resolvedRegion, + reference, + context.status, + preimage.redisPreimage()); + } + + RegionBridgePreimage probeRegionSessionBinding( + Installation installation, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference reference) { + BridgeContext context = currentBridgeContext(installation); + CanonicalGameplayRegionLeaseRedisOwner.BindingPreimage redisPreimage = + redisOwner.probeSessionBinding( + installation.grant, + context.status, + reference.runtimeEntityId(), + installation.evidence.candidate().identity().sessionId(), + installation.evidence.candidate().bindingGeneration()); + return new RegionBridgePreimage(context, redisPreimage); + } + + void applyRegionSessionBinding( + Installation installation, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference reference) { + BridgeContext context = currentBridgeContext(installation); + redisOwner.applySessionBinding( + installation.grant, + context.status, + reference.runtimeEntityId(), + installation.evidence.candidate().identity().sessionId(), + installation.evidence.candidate().bindingGeneration()); + } + + CanonicalGameplayRegionLeaseRedisOwner.BindingReadback readBackRegionSessionBinding( + Installation installation, + CanonicalGameplayRegionRuntimeStatus currentStatus, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference reference) { + BridgeContext context = currentBridgeContext(installation); + if (!context.status.equals(currentStatus)) throw unavailable(); + return redisOwner.readBackSessionBinding( + installation.grant, + context.status, + reference.runtimeEntityId(), + installation.evidence.candidate().identity().sessionId(), + installation.evidence.candidate().bindingGeneration()); + } + + CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement acknowledgeBridge( + Installation installation, + CanonicalGameplayBindingRegionBridgeObligation prepared, + BridgeContext context, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference reference, + CanonicalGameplayRegionLeaseRedisOwner.BindingReadback readback) { + requireOwnedContext(installation, context); + BridgeContext finalContext = currentBridgeContext(installation); + requireOwnedContext(installation, finalContext); + if (!context.status.equals(finalContext.status) + || !context.source.equals(finalContext.source) + || !context.resolvedRegion.equals(finalContext.resolvedRegion)) { + throw unavailable(); + } + return bindingInventory.acknowledgeRegionBridge( + prepared, + installation.worldRequest, + finalContext.resolvedRegion, + reference, + finalContext.status, + readback, + clock.instant()); + } + + private void requireOwnedContext(Installation installation, BridgeContext context) { + Objects.requireNonNull(installation, "installation"); + Objects.requireNonNull(context, "bridgeContext"); + if (!installation.owner.equals(this) + || !installation.source.equals(context.source) + || !installation.status.equals(context.status) + || !installation.transitionId.equals(context.evidence.transition().transitionId()) + || context.resolvedRegion == null) { + throw unavailable(); + } + bindingInventory.requireSameProvisionalSource(installation.evidence, context.evidence); } private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvidence( @@ -130,6 +322,9 @@ private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvi != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL || evidence.candidate().lifecycle() != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL + || evidence.expectedPrior() != null + || evidence.transition().expectedPriorBindingRef() != null + || evidence.transition().expectedPriorBindingGeneration() != null || !evidence.transition().transitionId().equals(transitionId) || !evidence.candidate().transitionId().equals(transitionId)) { throw unavailable(); @@ -140,6 +335,12 @@ private CanonicalGameplayBindingProvisionalCasEvidence readCurrentProvisionalEvi private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveExactSource( CanonicalInitialPlayerLocationRequest request, CanonicalGameplayBindingProvisionalCasEvidence evidence) { + return resolveExactBridgeSource(request, evidence).source; + } + + private ResolvedBridgeSource resolveExactBridgeSource( + CanonicalInitialPlayerLocationRequest request, + CanonicalGameplayBindingProvisionalCasEvidence evidence) { requireNoAmbientTransaction(); var identity = evidence.candidate().identity(); var target = request.getExpectedTarget(); @@ -163,17 +364,48 @@ private CanonicalGameplayRegionRuntimeStatusRepository.Source resolveExactSource || !identity.regionId().equals(assignment.operationalRegionId())) { throw unavailable(); } - return new CanonicalGameplayRegionRuntimeStatusRepository.Source( - identity.tenantId(), - identity.gameInstanceId(), - assignment.canonicalRegionId(), - assignment.operationalRegionId(), - assignment.lifecycleEpoch(), - assignment.lifecycleRowVersion(), - assignment.request(), - assignment.captureId(), - assignment.graphSha256(), - assignment.preparationInputDigest()); + return new ResolvedBridgeSource( + new CanonicalGameplayRegionRuntimeStatusRepository.Source( + identity.tenantId(), + identity.gameInstanceId(), + assignment.canonicalRegionId(), + assignment.operationalRegionId(), + assignment.lifecycleEpoch(), + assignment.lifecycleRowVersion(), + assignment.request(), + assignment.captureId(), + assignment.graphSha256(), + assignment.preparationInputDigest()), + resolved); + } + + private CanonicalGameplayRegionIncarnationSource.StableEvidence readCurrentIncarnation( + CanonicalGameplayRegionRuntimeStatusRepository.Source source) { + requireNoAmbientTransaction(); + CanonicalGameplayRegionIncarnationSource.RegionScope scope = + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source); + CanonicalGameplayRegionIncarnationSource.StableEvidence current = + incarnationSource.readCurrent(scope); + if (current == null + || !scope.equals(current.scope()) + || !current + .timelineInitializationQualification() + .matches(scope, current.digest())) { + throw unavailable(); + } + return current; + } + + private static void requireSameIncarnation( + CanonicalGameplayRegionIncarnationSource.StableEvidence expected, + CanonicalGameplayRegionIncarnationSource.StableEvidence actual) { + if (expected == null + || actual == null + || !expected.scope().equals(actual.scope()) + || !java.util.Arrays.equals(expected.scopeBytes(), actual.scopeBytes()) + || !java.util.Arrays.equals(expected.canonicalBytes(), actual.canonicalBytes())) { + throw unavailable(); + } } private static long exactExpectedRegionEpoch(BigInteger value) { @@ -208,18 +440,22 @@ private static IllegalStateException unavailable() { /** Private construction prevents caller-created installation/readback objects. */ final class Installation { private final CanonicalGameplayRegionLeaseOwner owner; - private final UUID transitionId; - private final CanonicalInitialPlayerLocationRequest worldRequest; - private final CanonicalGameplayBindingProvisionalCasEvidence evidence; - private final CanonicalGameplayRegionRuntimeStatusRepository.Source source; - private final CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; - private final CanonicalGameplayRegionRuntimeStatus status; + final UUID transitionId; + final CanonicalInitialPlayerLocationRequest worldRequest; + final CanonicalGameplayBindingProvisionalCasEvidence evidence; + final CanonicalGameplayRegionRuntimeStatusRepository.Source source; + final CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation; + final CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; + final CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; + final CanonicalGameplayRegionRuntimeStatus status; private Installation( UUID transitionId, CanonicalInitialPlayerLocationRequest worldRequest, CanonicalGameplayBindingProvisionalCasEvidence evidence, CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant, CanonicalGameplayRegionRuntimeStatus status) { this.owner = CanonicalGameplayRegionLeaseOwner.this; @@ -227,8 +463,24 @@ private Installation( this.worldRequest = worldRequest; this.evidence = evidence; this.source = source; + this.incarnation = incarnation; + this.preparation = preparation; this.grant = grant; this.status = status; } } + + record BridgeContext( + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatus status, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolvedRegion) {} + + record RegionBridgePreimage( + BridgeContext context, + CanonicalGameplayRegionLeaseRedisOwner.BindingPreimage redisPreimage) {} + + private record ResolvedBridgeSource( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolvedRegion) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java index 957244c0f4..c2fbb8305f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java @@ -17,6 +17,7 @@ static CanonicalGameplayRegionLeaseOwner compose( DSLContext dsl, RedisClient coordinationRedis, RedisScriptCatalog scriptCatalog, + CanonicalGameplayRegionIncarnationSource incarnationSource, CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, RuntimeIdentity runtimeIdentity, Duration leaseTtl, @@ -24,10 +25,12 @@ static CanonicalGameplayRegionLeaseOwner compose( Objects.requireNonNull(dsl, "dsl"); Objects.requireNonNull(coordinationRedis, "coordinationRedis"); Objects.requireNonNull(scriptCatalog, "scriptCatalog"); + Objects.requireNonNull(incarnationSource, "incarnationSource"); return new CanonicalGameplayRegionLeaseOwner( new CanonicalGameplayBindingInventoryRepository(dsl), new CanonicalGameplayRegionRuntimeStatusRepository(dsl), new CanonicalGameplayRegionLeaseRedisOwner(coordinationRedis, scriptCatalog), + incarnationSource, Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"), Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"), Objects.requireNonNull(leaseTtl, "leaseTtl"), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index c193baaef9..5a2b62af70 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -8,6 +8,7 @@ import io.lettuce.core.codec.ByteArrayCodec; import java.io.IOException; import java.io.InputStream; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.Duration; @@ -22,6 +23,9 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Manually composed region lease using the exact full-scope key, registered Lua, and readback. */ @@ -30,14 +34,41 @@ final class CanonicalGameplayRegionLeaseRedisOwner { private static final String SCHEMA = "gs_region_lease/v1"; private static final int MAX_SCRIPT_BYTES = 16 * 1024; private static final long COMMAND_TIMEOUT_MILLIS = 5_000L; - private static final List LEASE_ARGUMENTS = List.of("schema", "token", "leaseTtlMs"); - private static final List READ_ARGUMENTS = List.of("schema", "token"); + private static final List LEASE_ARGUMENTS = + List.of("schema", "token", "expectedRegionEpoch", "leaseTtlMs"); + private static final List READ_ARGUMENTS = List.of("schema", "token", "expectedRegionEpoch"); private static final List EXPECTED_KEYS = List.of( new RedisScriptDescriptor.KeySpec( "regionLease", "tick-executor-lease:", - RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + RedisScriptDescriptor.HashTagDeclaration.REQUIRED), + new RedisScriptDescriptor.KeySpec( + "regionMeta", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + private static final String TIMELINE_SCHEMA = "gs_region_timeline_init/v1"; + private static final List TIMELINE_ARGUMENTS = + List.of( + "schema", + "action", + "token", + "expectedRegionEpoch", + "initializationOperationId", + "preparationDigest", + "leaseTtlMs", + "mayCreateFromAbsence"); + private static final String BRIDGE_SCHEMA = "gs_region_binding_bridge/v1"; + private static final List BRIDGE_ARGUMENTS = + List.of("schema", "action", "leaseToken", "expectedRegionEpoch", "sessionId", "bindingGeneration"); + private static final List BRIDGE_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "regionLease", + "tick-executor-lease:", + RedisScriptDescriptor.HashTagDeclaration.REQUIRED), + new RedisScriptDescriptor.KeySpec( + "regionMeta", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED), + new RedisScriptDescriptor.KeySpec( + "regionSessionBinding", "tick:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); private final RedisClient redisClient; private final RedisScriptCatalog catalog; @@ -74,6 +105,83 @@ LeaseGrant acquire( return grant; } + TimelineAbsenceProof requireTimelineAbsent( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation) { + requireNoAmbientTransaction(); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(incarnation, "incarnation"); + if (!CanonicalGameplayRegionIncarnationSource.RegionScope.from(source) + .equals(incarnation.scope())) { + throw unavailable(); + } + long outcome = + executeTimeline( + source, + 1L, + UUID.randomUUID().toString(), + "PROBE", + UUID.randomUUID(), + incarnation.digest(), + 1L, + false); + if (outcome != 1L) throw unavailable(); + return new TimelineAbsenceProof( + source, + incarnation.scopeBytes(), + incarnation.canonicalBytes(), + absenceProofDigest(source, incarnation)); + } + + LeaseGrant initializeOrResumeTimeline( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + CanonicalGameplayRegionRuntimeStatusRepository.InitialInitializationPermit permit, + Duration leaseTtl, + RuntimeIdentity identity) { + requireNoAmbientTransaction(); + Objects.requireNonNull(preparation, "preparation"); + long ttlMillis = ttlMillis(leaseTtl); + String ownerService = requireOwnerService(identity); + String ownerInstance = requireOwnerInstance(identity); + boolean mayCreate = permit != null; + if (mayCreate + && (!permit.operationId().equals(preparation.operationId()) + || !permit.sourceDigest().equals(preparation.sourceDigest()))) { + throw unavailable(); + } + LeaseGrant grant = + new LeaseGrant(preparation.source(), preparation.regionEpoch(), UUID.randomUUID().toString(), + ownerService, ownerInstance); + long outcome = + executeTimeline( + grant, + "INITIALIZE", + preparation.operationId(), + preparation.sourceDigest(), + ttlMillis, + mayCreate); + if (outcome != 1L && outcome != 2L) throw unavailable(); + return grant; + } + + void verifyInitializedTimeline( + LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation) { + requireNoAmbientTransaction(); + if (!grant.source.equals(preparation.source()) || grant.regionEpoch != preparation.regionEpoch()) { + throw unavailable(); + } + long outcome = + executeTimeline( + grant, + "VERIFY", + preparation.operationId(), + preparation.sourceDigest(), + 1L, + false); + if (outcome != 3L) throw unavailable(); + } + void requireGrantScope( LeaseGrant grant, CanonicalGameplayRegionRuntimeStatusRepository.Source source, @@ -116,6 +224,219 @@ void requireCurrent(LeaseGrant grant) { if (outcome != 1L) throw unavailable(); } + private long executeTimeline( + LeaseGrant grant, + String action, + UUID operationId, + String sourceDigest, + long ttlMillis, + boolean mayCreate) { + return executeTimeline( + grant.source, + grant.regionEpoch, + grant.token, + action, + operationId, + sourceDigest, + ttlMillis, + mayCreate); + } + + private long executeTimeline( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + long regionEpoch, + String token, + String action, + UUID operationId, + String sourceDigest, + long ttlMillis, + boolean mayCreate) { + requireNoAmbientTransaction(); + RedisScriptDescriptor descriptor = + requireDescriptor( + CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_ID, + CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_PATH, + TIMELINE_ARGUMENTS); + byte[] script = scriptSource(descriptor); + byte[][] keys = + new byte[][] { + ascii(CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId())), + ascii(CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())) + }; + byte[][] arguments = + new byte[][] { + ascii(TIMELINE_SCHEMA), + ascii(action), + ascii(token), + ascii(Long.toString(regionEpoch)), + ascii(operationId.toString()), + ascii(sourceDigest), + ascii(Long.toString(ttlMillis)), + ascii(mayCreate ? "1" : "0") + }; + return executeInteger(script, keys, arguments); + } + + private static String absenceProofDigest( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation) { + return digest( + "SHA-256", + concat( + ascii("firemud.gs.region-timeline-absent/v1"), + incarnation.scopeBytes(), + incarnation.canonicalBytes(), + ascii(CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId())))); + } + + private static byte[] concat(byte[]... values) { + int length = 0; + for (byte[] value : values) length = Math.addExact(length, value.length); + byte[] result = new byte[length]; + int offset = 0; + for (byte[] value : values) { + System.arraycopy(value, 0, result, offset, value.length); + offset += value.length; + } + return result; + } + + /** Applies one exact first-NEW tuple under the same acquired grant and durable owner fence. */ + void applySessionBinding( + LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatus durableOwner, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId, + String sessionId, + BigInteger bindingGeneration) { + long outcome = + executeBinding( + grant, durableOwner, runtimeEntityId, sessionId, bindingGeneration, "APPLY"); + if (outcome != 1L && outcome != 2L) throw unavailable(); + } + + /** Reads and privately binds the exact physical preimage under the live lease and epoch. */ + BindingPreimage probeSessionBinding( + LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatus durableOwner, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId, + String sessionId, + BigInteger bindingGeneration) { + long outcome = + executeBinding( + grant, durableOwner, runtimeEntityId, sessionId, bindingGeneration, "PROBE"); + if (outcome != 4L && outcome != 5L) throw unavailable(); + return new BindingPreimage( + runtimeEntityId, + sessionId, + bindingGeneration, + durableOwner.regionEpoch(), + durableOwner.executorFence(), + durableOwner.leaseTokenCorrelation(), + outcome == 4L ? PreimageState.ABSENT : PreimageState.EXACT); + } + + /** Independently reads exact region-local state under the same live grant and durable fence. */ + BindingReadback readBackSessionBinding( + LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatus durableOwner, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId, + String sessionId, + BigInteger bindingGeneration) { + long outcome = + executeBinding( + grant, durableOwner, runtimeEntityId, sessionId, bindingGeneration, "READBACK"); + if (outcome != 3L) throw unavailable(); + return new BindingReadback( + runtimeEntityId, + sessionId, + bindingGeneration, + durableOwner.regionEpoch(), + durableOwner.executorFence(), + durableOwner.leaseTokenCorrelation(), + CanonicalGameplayRegionBindingBridgeProofs.redisReadbackDigest( + durableOwner, runtimeEntityId, sessionId, bindingGeneration.toString())); + } + + private long executeBinding( + LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatus durableOwner, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId, + String sessionId, + BigInteger bindingGeneration, + String action) { + requireNoAmbientTransaction(); + Objects.requireNonNull(grant, "grant"); + Objects.requireNonNull(durableOwner, "durableOwner"); + Objects.requireNonNull(runtimeEntityId, "runtimeEntityId"); + Objects.requireNonNull(bindingGeneration, "bindingGeneration"); + if (bindingGeneration.signum() <= 0 + || bindingGeneration.toString().length() > 128 + || sessionId == null + || !sessionId.matches( + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + || !"APPLY".equals(action) && !"READBACK".equals(action) && !"PROBE".equals(action)) { + throw unavailable(); + } + requireGrantBackedStatus(grant, durableOwner, runtimeEntityId); + RedisScriptDescriptor descriptor = requireBridgeDescriptor(); + byte[] script = scriptSource(descriptor); + byte[][] keys = + new byte[][] { + ascii(grant.key()), + ascii(CanonicalGameplayRegionRedisKeys.meta( + grant.source.tenantId(), grant.source.gameInstanceId(), grant.source.regionId())), + ascii(CanonicalGameplayRegionRedisKeys.sessionBinding( + grant.source.tenantId(), + grant.source.gameInstanceId(), + grant.source.regionId(), + runtimeEntityId.value())) + }; + byte[][] arguments = + new byte[][] { + ascii(BRIDGE_SCHEMA), + ascii(action), + ascii(grant.token), + ascii(Long.toString(grant.regionEpoch)), + ascii(sessionId), + ascii(bindingGeneration.toString()) + }; + return executeInteger(script, keys, arguments); + } + + private static void requireGrantBackedStatus( + LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatus status, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId) { + if (!status.tenantId().equals(grant.source.tenantId()) + || !status.gameInstanceId().equals(grant.source.gameInstanceId()) + || !status.canonicalRegionId().equals(grant.source.canonicalRegionId()) + || !status.regionId().equals(grant.source.regionId()) + || status.lifecycleEpoch() != grant.source.lifecycleEpoch() + || status.lifecycleRowVersion() != grant.source.lifecycleRowVersion() + || !status.lifecycleRequest().equals(grant.source.lifecycleRequest()) + || !status.captureId().equals(grant.source.captureId()) + || !status.graphSha256().equals(grant.source.graphSha256()) + || !status.preparationInputDigest().equals(grant.source.preparationInputDigest()) + || !status.tenantRegionTag() + .equals( + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + grant.source.tenantId(), + grant.source.gameInstanceId(), + grant.source.regionId())) + || status.regionEpoch() != grant.regionEpoch + || !status.leaseTokenCorrelation().equals(grant.tokenCorrelation()) + || !status.ownerService().equals(grant.ownerService) + || !status.ownerInstanceId().equals(grant.ownerInstanceId) + || status.paused() + || !runtimeEntityId.tenantId().equals(grant.source.tenantId()) + || !runtimeEntityId.gameInstanceId().equals(grant.source.gameInstanceId().toString())) { + throw unavailable(); + } + } + private long execute( String scriptId, String resourcePath, @@ -125,13 +446,18 @@ private long execute( boolean includeTtl) { RedisScriptDescriptor descriptor = requireDescriptor(scriptId, resourcePath, expectedArguments); byte[] source = scriptSource(descriptor); - byte[] key = ascii(grant.key()); + byte[][] keys = + new byte[][] { + ascii(grant.key()), + ascii(CanonicalGameplayRegionRedisKeys.meta( + grant.source.tenantId(), grant.source.gameInstanceId(), grant.source.regionId())) + }; byte[][] arguments = grant.arguments(includeTtl ? ttlMillis : null); if (arguments.length != expectedArguments.size()) throw unavailable(); - return executeInteger(source, key, arguments); + return executeInteger(source, keys, arguments); } - private long executeInteger(byte[] script, byte[] key, byte[][] arguments) { + private long executeInteger(byte[] script, byte[][] keys, byte[][] arguments) { requireNoAmbientTransaction(); try (StatefulRedisConnection connection = redisClient.connect(ByteArrayCodec.INSTANCE)) { @@ -141,7 +467,7 @@ private long executeInteger(byte[] script, byte[] key, byte[][] arguments) { if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); Long result = await( - commands.evalsha(loadedSha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + commands.evalsha(loadedSha, ScriptOutputType.INTEGER, keys, arguments)); if (result == null) throw unavailable(); return result; } catch (RuntimeException failure) { @@ -149,6 +475,31 @@ private long executeInteger(byte[] script, byte[] key, byte[][] arguments) { } } + private RedisScriptDescriptor requireBridgeDescriptor() { + try { + RedisScriptDescriptor descriptor = + catalog.require(CanonicalGameplayRegionBindingBridgeRedisScriptContribution.SCRIPT_ID); + if (!CanonicalGameplayRegionBindingBridgeRedisScriptContribution.SCRIPT_ID + .equals(descriptor.scriptId()) + || !CanonicalGameplayRegionBindingBridgeRedisScriptContribution.SCRIPT_PATH + .equals(descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.TICK_LOCK + || !BRIDGE_KEYS.equals(descriptor.keys()) + || !BRIDGE_ARGUMENTS.equals( + descriptor.arguments().stream() + .map(RedisScriptDescriptor.ArgumentSpec::name) + .toList())) { + throw unavailable(); + } + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + private RedisScriptDescriptor requireDescriptor( String id, String resourcePath, List arguments) { try { @@ -302,12 +653,165 @@ String ownerInstanceId() { } private byte[][] arguments(Long ttlMillis) { - if (ttlMillis == null) return new byte[][] {ascii(SCHEMA), ascii(token)}; - return new byte[][] {ascii(SCHEMA), ascii(token), ascii(ttlMillis.toString())}; + if (ttlMillis == null) { + return new byte[][] {ascii(SCHEMA), ascii(token), ascii(Long.toString(regionEpoch))}; + } + return new byte[][] { + ascii(SCHEMA), ascii(token), ascii(Long.toString(regionEpoch)), ascii(ttlMillis.toString()) + }; } String key() { return key; } } + + /** Private result of the same-slot probe that observed no region meta or executor lease. */ + static final class TimelineAbsenceProof { + private final CanonicalGameplayRegionRuntimeStatusRepository.Source source; + private final byte[] incarnationScopeBytes; + private final byte[] incarnationSourceBytes; + private final String proofDigest; + + private TimelineAbsenceProof( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + byte[] incarnationScopeBytes, + byte[] incarnationSourceBytes, + String proofDigest) { + this.source = Objects.requireNonNull(source, "source"); + this.incarnationScopeBytes = incarnationScopeBytes.clone(); + this.incarnationSourceBytes = incarnationSourceBytes.clone(); + this.proofDigest = Objects.requireNonNull(proofDigest, "proofDigest"); + } + + boolean matches( + CanonicalGameplayRegionRuntimeStatusRepository.Source expectedSource, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation) { + return source.equals(expectedSource) + && java.util.Arrays.equals(incarnationScopeBytes, incarnation.scopeBytes()) + && java.util.Arrays.equals(incarnationSourceBytes, incarnation.canonicalBytes()) + && proofDigest.equals(absenceProofDigest(expectedSource, incarnation)); + } + + String digest() { + return proofDigest; + } + } + + /** Private-construction proof that a second region Lua call read the exact live tuple. */ + static final class BindingReadback { + private final CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId; + private final String sessionId; + private final BigInteger bindingGeneration; + private final long regionEpoch; + private final BigInteger executorFence; + private final String leaseTokenCorrelation; + private final String digest; + + private BindingReadback( + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId, + String sessionId, + BigInteger bindingGeneration, + long regionEpoch, + BigInteger executorFence, + String leaseTokenCorrelation, + String digest) { + this.runtimeEntityId = runtimeEntityId; + this.sessionId = sessionId; + this.bindingGeneration = bindingGeneration; + this.regionEpoch = regionEpoch; + this.executorFence = executorFence; + this.leaseTokenCorrelation = leaseTokenCorrelation; + this.digest = digest; + } + + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId() { + return runtimeEntityId; + } + + String sessionId() { + return sessionId; + } + + BigInteger bindingGeneration() { + return bindingGeneration; + } + + long regionEpoch() { + return regionEpoch; + } + + BigInteger executorFence() { + return executorFence; + } + + String leaseTokenCorrelation() { + return leaseTokenCorrelation; + } + + String digest() { + return digest; + } + } + + /** Private-construction result of a lease/epoch-checked read of the exact key preimage. */ + static final class BindingPreimage { + private final CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId; + private final String sessionId; + private final BigInteger bindingGeneration; + private final long regionEpoch; + private final BigInteger executorFence; + private final String leaseTokenCorrelation; + private final PreimageState state; + + private BindingPreimage( + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId, + String sessionId, + BigInteger bindingGeneration, + long regionEpoch, + BigInteger executorFence, + String leaseTokenCorrelation, + PreimageState state) { + this.runtimeEntityId = runtimeEntityId; + this.sessionId = sessionId; + this.bindingGeneration = bindingGeneration; + this.regionEpoch = regionEpoch; + this.executorFence = executorFence; + this.leaseTokenCorrelation = leaseTokenCorrelation; + this.state = state; + } + + CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId runtimeEntityId() { + return runtimeEntityId; + } + + String sessionId() { + return sessionId; + } + + BigInteger bindingGeneration() { + return bindingGeneration; + } + + long regionEpoch() { + return regionEpoch; + } + + BigInteger executorFence() { + return executorFence; + } + + String leaseTokenCorrelation() { + return leaseTokenCorrelation; + } + + PreimageState state() { + return state; + } + } + + enum PreimageState { + ABSENT, + EXACT + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java index a58e6ae01e..13ccd21fb9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java @@ -23,6 +23,19 @@ static String lease(UUID tenantId, UUID gameInstanceId, UUID regionId) { return "tick-executor-lease:{" + tenantRegionTag(tenantId, gameInstanceId, regionId) + "}"; } + static String meta(UUID tenantId, UUID gameInstanceId, UUID regionId) { + return "tick:{" + tenantRegionTag(tenantId, gameInstanceId, regionId) + "}:meta"; + } + + static String sessionBinding( + UUID tenantId, UUID gameInstanceId, UUID regionId, long runtimeEntityId) { + if (runtimeEntityId <= 0L) throw new IllegalArgumentException("runtimeEntityId must be positive"); + return "tick:{" + + tenantRegionTag(tenantId, gameInstanceId, regionId) + + "}:session-binding:" + + runtimeEntityId; + } + private static void requireCanonicalId(UUID id, String name) { Objects.requireNonNull(id, name); if (id.equals(new UUID(0L, 0L)) || !UUID.fromString(id.toString()).equals(id)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index e8bcd5504d..76f78322ea 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -3,12 +3,19 @@ import java.math.BigInteger; import java.time.Instant; import java.time.LocalDateTime; +import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.Arrays; import java.util.Objects; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.impl.DSL; @@ -17,6 +24,7 @@ /** Durable region timeline and owner-fence persistence, separate from the instance status row. */ final class CanonicalGameplayRegionRuntimeStatusRepository { private static final String TABLE = "game_session_region_runtime_status"; + private static final String PREPARATION_TABLE = "game_session_region_timeline_preparation"; private static final String FENCE_SEQUENCE = "game_session_region_executor_fence_seq"; private final DSLContext dsl; @@ -46,6 +54,572 @@ Optional find(Source source) { return Optional.of(status); } + /** Persists the original nonadmitting first-timeline operation before any Redis mutation. */ + TimelinePreparation prepareInitialTimeline( + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolvedRegion, + Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation, + CanonicalGameplayRegionLeaseRedisOwner.TimelineAbsenceProof absenceProof, + Instant now) { + requireNoAmbientTransaction(); + Objects.requireNonNull(now, "now"); + if (absenceProof == null || !absenceProof.matches(source, incarnation)) throw unavailable(); + InitialTimelineInputs inputs = + requireInitialTimelineInputs( + evidence, + worldRequest, + resolvedRegion, + source, + incarnation, + absenceProof.digest()); + try { + TimelinePreparation prepared = + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + lockRegionScope(transaction, inputs.tenantRegionTag()); + Record existingStatus = + transaction.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " FOR UPDATE", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + if (existingStatus != null) throw unavailable(); + Record existingTransition = + transaction.fetchOne( + "SELECT * FROM " + PREPARATION_TABLE + " WHERE transition_id = ? FOR UPDATE", + evidence.transition().transitionId()); + if (existingTransition != null) { + TimelinePreparation current = toTimelinePreparation(existingTransition); + if (!matchesPreparation(current, evidence, inputs, source) + || current.phase == TimelinePreparationPhase.INSTALLED) { + throw unavailable(); + } + return current; + } + Record existingScope = + transaction.fetchOne( + "SELECT initialization_operation_id FROM " + + PREPARATION_TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " FOR UPDATE", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + if (existingScope != null) throw unavailable(); + UUID operationId = UUID.randomUUID(); + transaction.execute( + "INSERT INTO " + + PREPARATION_TABLE + + " (initialization_operation_id, transition_id, account_id, tenant_id," + + " playable_state_namespace_id, character_id, playable_state_scope," + + " game_instance_id, runtime_game_instance_id, binding_ref, session_id," + + " binding_generation, canonical_region_id, region_id, tenant_region_tag," + + " lifecycle_epoch, lifecycle_row_version, capture_id," + + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," + + " assignment_uuid, assignment_intent_digest, world_source_digest," + + " preparation_digest, stable_incarnation_scope_bytes," + + " stable_incarnation_source_bytes, stable_incarnation_qualification_bytes," + + " stable_incarnation_digest," + + " timeline_preimage_state, timeline_absence_proof_digest, region_epoch," + + " last_committed_tick_id, phase, created_at, updated_at)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ABSENT', ?, 1, -1, 'PREPARED', ?, ?)", + operationId, + evidence.transition().transitionId(), + evidence.candidate().identity().accountId(), + evidence.candidate().identity().tenantId(), + evidence.candidate().identity().playableStateNamespaceId(), + evidence.candidate().identity().characterId(), + evidence.candidate().identity().playableStateScope(), + evidence.candidate().identity().gameInstanceId(), + evidence.candidate().identity().runtimeGameInstanceId(), + evidence.candidate().bindingRef().bytes(), + evidence.candidate().identity().sessionId(), + evidence.candidate().bindingGeneration().toString(), + source.canonicalRegionId(), + source.regionId(), + inputs.tenantRegionTag(), + source.lifecycleEpoch(), + source.lifecycleRowVersion(), + source.captureId(), + source.lifecycleRequest().canonicalBytes(), + source.graphSha256(), + source.preparationInputDigest(), + UUID.fromString(worldRequest.getAssignmentUuid()), + worldRequest.getAssignmentIntentDigest(), + inputs.worldSourceDigest(), + inputs.preparationDigest(), + inputs.incarnationScopeBytes(), + inputs.incarnationSourceBytes(), + inputs.incarnationQualificationBytes(), + inputs.incarnationDigest(), + inputs.absenceProofDigest(), + OffsetDateTime.ofInstant(now, ZoneOffset.UTC), + OffsetDateTime.ofInstant(now, ZoneOffset.UTC)); + Record inserted = + transaction.fetchOne( + "SELECT * FROM " + PREPARATION_TABLE + " WHERE transition_id = ?", + evidence.transition().transitionId()); + TimelinePreparation result = + inserted == null ? null : toTimelinePreparation(inserted); + if (result == null || !matchesPreparation(result, evidence, inputs, source)) { + throw unavailable(); + } + return result; + }); + if (find(source).isPresent()) throw unavailable(); + return prepared; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + Optional findTimelinePreparation(Source source) { + requireNoAmbientTransaction(); + Objects.requireNonNull(source, "source"); + String tag = CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId()); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PREPARATION_TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + if (row == null) return Optional.empty(); + TimelinePreparation preparation = toTimelinePreparation(row); + if (!preparation.source.equals(source) || !preparation.tenantRegionTag.equals(tag)) { + throw unavailable(); + } + return Optional.of(preparation); + } + + boolean matchesTimelinePreparation( + TimelinePreparation preparation, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolvedRegion, + Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation) { + Objects.requireNonNull(preparation, "preparation"); + InitialTimelineInputs inputs = + requireInitialTimelineInputs( + evidence, + worldRequest, + resolvedRegion, + source, + incarnation, + preparation.absenceProofDigest); + return matchesPreparation(preparation, evidence, inputs, source); + } + + /** The durable PREPARED-to-INITIALIZING transition grants the sole permission to create meta. */ + Optional beginInitialTimeline( + TimelinePreparation preparation, Instant now) { + requireNoAmbientTransaction(); + Objects.requireNonNull(preparation, "preparation"); + Objects.requireNonNull(now, "now"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + lockRegionScope(transaction, preparation.tenantRegionTag); + if (transaction.fetchOne( + "SELECT 1 FROM " + + TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", + preparation.source.tenantId(), + preparation.source.gameInstanceId(), + preparation.source.regionId()) + != null) { + throw unavailable(); + } + Record row = + transaction.fetchOne( + "SELECT * FROM " + + PREPARATION_TABLE + + " WHERE initialization_operation_id = ? FOR UPDATE", + preparation.operationId); + if (row == null) throw unavailable(); + TimelinePreparation current = toTimelinePreparation(row); + if (!samePreparation(preparation, current)) throw unavailable(); + if (current.phase == TimelinePreparationPhase.INSTALLED) { + return Optional.empty(); + } + if (current.phase != TimelinePreparationPhase.PREPARED) return Optional.empty(); + int updated = + transaction.execute( + "UPDATE " + + PREPARATION_TABLE + + " SET phase = 'INITIALIZING', updated_at = ?" + + " WHERE initialization_operation_id = ? AND phase = 'PREPARED'", + OffsetDateTime.ofInstant(now, ZoneOffset.UTC), + current.operationId); + if (updated != 1) throw unavailable(); + return Optional.of(new InitialInitializationPermit(current.operationId, current.sourceDigest)); + }); + } + + TimelinePreparation markRedisInitialized( + TimelinePreparation preparation, + String leaseTokenCorrelation, + String redisMetaDigest, + Instant now) { + requireNoAmbientTransaction(); + Objects.requireNonNull(preparation, "preparation"); + requireDigest(leaseTokenCorrelation); + requireDigest(redisMetaDigest); + Objects.requireNonNull(now, "now"); + String expectedMetaDigest = + CanonicalGameplayRegionBindingBridgeProofs.initialMetaDigest( + preparation.tenantRegionTag, preparation.operationId, preparation.sourceDigest()); + if (!expectedMetaDigest.equals(redisMetaDigest)) throw unavailable(); + return updatePreparationAfterRedis( + preparation, leaseTokenCorrelation, redisMetaDigest, null, null, now); + } + + TimelinePreparation markTimelineInstalled( + TimelinePreparation preparation, + CanonicalGameplayRegionRuntimeStatus installed, + Instant now) { + requireNoAmbientTransaction(); + Objects.requireNonNull(preparation, "preparation"); + Objects.requireNonNull(installed, "installed"); + Objects.requireNonNull(now, "now"); + if (!matchesSource(installed, preparation.source) + || !installed.tenantRegionTag().equals(preparation.tenantRegionTag) + || installed.regionEpoch() != 1L) { + throw unavailable(); + } + return updatePreparationAfterRedis( + preparation, + installed.leaseTokenCorrelation(), + preparation.redisMetaDigest, + installed.executorFence().longValueExact(), + installed, + now); + } + + private TimelinePreparation updatePreparationAfterRedis( + TimelinePreparation preparation, + String leaseTokenCorrelation, + String redisMetaDigest, + Long executorFence, + CanonicalGameplayRegionRuntimeStatus expectedInstalled, + Instant now) { + try { + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + lockRegionScope(transaction, preparation.tenantRegionTag); + Record currentStatus = + transaction.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", + preparation.source.tenantId(), + preparation.source.gameInstanceId(), + preparation.source.regionId()); + Record row = + transaction.fetchOne( + "SELECT * FROM " + + PREPARATION_TABLE + + " WHERE initialization_operation_id = ? FOR UPDATE", + preparation.operationId); + if (row == null) throw unavailable(); + TimelinePreparation current = toTimelinePreparation(row); + if (!samePreparation(preparation, current)) throw unavailable(); + String expectedMetaDigest = + CanonicalGameplayRegionBindingBridgeProofs.initialMetaDigest( + current.tenantRegionTag, current.operationId, current.sourceDigest()); + if (!expectedMetaDigest.equals(redisMetaDigest) + || current.redisMetaDigest != null + && !current.redisMetaDigest.equals(redisMetaDigest)) { + throw unavailable(); + } + String nextPhase; + if (executorFence == null) { + if (currentStatus != null + || (current.phase != TimelinePreparationPhase.INITIALIZING + && current.phase != TimelinePreparationPhase.REDIS_INITIALIZED)) { + throw unavailable(); + } + nextPhase = "REDIS_INITIALIZED"; + } else { + if (currentStatus == null + || (current.phase != TimelinePreparationPhase.REDIS_INITIALIZED + && current.phase != TimelinePreparationPhase.INSTALLED)) { + throw unavailable(); + } + CanonicalGameplayRegionRuntimeStatus status = toStatus(currentStatus); + if (!status.equals(expectedInstalled) + || !matchesSource(status, preparation.source) + || status.executorFence().longValueExact() != executorFence + || !status.leaseTokenCorrelation().equals(leaseTokenCorrelation)) { + throw unavailable(); + } + nextPhase = "INSTALLED"; + } + int updated = + transaction.execute( + "UPDATE " + + PREPARATION_TABLE + + " SET phase = ?, lease_token_correlation = ?, executor_fence = ?," + + " redis_meta_digest = ?, updated_at = ?" + + " WHERE initialization_operation_id = ?", + nextPhase, + leaseTokenCorrelation, + executorFence, + redisMetaDigest, + OffsetDateTime.ofInstant(now, ZoneOffset.UTC), + current.operationId); + if (updated != 1) throw unavailable(); + return toTimelinePreparation( + Objects.requireNonNull( + transaction.fetchOne( + "SELECT * FROM " + + PREPARATION_TABLE + + " WHERE initialization_operation_id = ?", + current.operationId), + "region timeline preparation must survive phase readback")); + }); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static InitialTimelineInputs requireInitialTimelineInputs( + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolvedRegion, + Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation, + String absenceProofDigest) { + Objects.requireNonNull(evidence, "evidence"); + Objects.requireNonNull(worldRequest, "worldRequest"); + Objects.requireNonNull(resolvedRegion, "resolvedRegion"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(incarnation, "incarnation"); + if (!CanonicalGameplayRegionIncarnationSource.RegionScope.from(source) + .equals(incarnation.scope()) + || absenceProofDigest == null + || !absenceProofDigest.matches("[0-9a-f]{64}")) { + throw unavailable(); + } + var identity = evidence.candidate().identity(); + var assignment = resolvedRegion.lifecycleAssignment(); + var target = worldRequest.getExpectedTarget(); + UUID assignmentId = canonicalNonNilUuid(worldRequest.getAssignmentUuid()); + if (evidence.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || evidence.candidate().lifecycle() + != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL + || evidence.expectedPrior() != null + || evidence.transition().expectedPriorBindingRef() != null + || evidence.transition().expectedPriorBindingGeneration() != null + || !evidence.transition().transitionId().equals(evidence.candidate().transitionId()) + || worldRequest.getSchemaVersion() != 1 + || !worldRequest.hasExpectedTarget() + || !worldRequest.getUnknownFields().asMap().isEmpty() + || !target.getUnknownFields().asMap().isEmpty() + || !identity.accountId().toString().equals(worldRequest.getCanonicalAccountUuid()) + || !identity.characterId().toString().equals(worldRequest.getCharacterUuid()) + || !identity.tenantId().toString().equals(target.getCanonicalTenantUuid()) + || !identity.gameInstanceId().toString().equals(target.getGameInstanceId()) + || !identity.playableStateNamespaceId() + .toString() + .equals(target.getPlayableStateNamespaceUuid()) + || !"SHARED".equals(identity.playableStateScope()) + || !identity.tenantId().equals(source.tenantId()) + || !identity.gameInstanceId().equals(source.gameInstanceId()) + || !identity.regionId().equals(source.regionId()) + || !identity.regionEpoch().equals(BigInteger.ONE) + || !worldRequest.getAssignmentIntentDigest().matches("[0-9a-f]{64}") + || !source.canonicalRegionId().equals(resolvedRegion.canonicalRegionInstanceId()) + || !source.regionId().equals(resolvedRegion.operationalRegionId()) + || !source.regionId().equals(assignment.operationalRegionId()) + || !source.lifecycleRequest().equals(assignment.request()) + || source.lifecycleEpoch() != assignment.lifecycleEpoch() + || source.lifecycleRowVersion() != assignment.lifecycleRowVersion() + || !source.captureId().equals(assignment.captureId()) + || !source.graphSha256().equals(assignment.graphSha256()) + || !source.preparationInputDigest().equals(assignment.preparationInputDigest()) + || !identity.tenantId().equals(assignment.request().canonicalTenantId()) + || !identity.gameInstanceId().equals(assignment.request().canonicalGameInstanceId()) + || !identity.regionId().equals(assignment.operationalRegionId())) { + throw unavailable(); + } + String tag = + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId()); + String worldDigest = + CanonicalGameplayRegionBindingBridgeProofs.worldSourceDigest(worldRequest, resolvedRegion); + String preparationDigest = + CanonicalGameplayRegionBindingBridgeProofs.timelinePreparationDigest( + evidence, + worldRequest, + resolvedRegion, + source, + worldDigest, + incarnation, + absenceProofDigest); + return new InitialTimelineInputs( + tag, + assignmentId, + worldRequest.getAssignmentIntentDigest(), + worldDigest, + preparationDigest, + incarnation.scopeBytes(), + incarnation.stableCanonicalBytes(), + incarnation.timelineInitializationQualification().canonicalBytes(), + incarnation.digest(), + absenceProofDigest); + } + + private static boolean matchesPreparation( + TimelinePreparation preparation, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + InitialTimelineInputs inputs, + Source source) { + var identity = evidence.candidate().identity(); + return preparation.transitionId.equals(evidence.transition().transitionId()) + && preparation.source.equals(source) + && preparation.tenantRegionTag.equals(inputs.tenantRegionTag()) + && preparation.accountId.equals(identity.accountId()) + && preparation.tenantId.equals(identity.tenantId()) + && preparation.playableStateNamespaceId.equals(identity.playableStateNamespaceId()) + && preparation.characterId.equals(identity.characterId()) + && preparation.playableStateScope.equals(identity.playableStateScope()) + && preparation.gameInstanceId.equals(identity.gameInstanceId()) + && preparation.runtimeGameInstanceId == identity.runtimeGameInstanceId() + && Arrays.equals(preparation.bindingRef, evidence.candidate().bindingRef().bytes()) + && preparation.sessionId.equals(identity.sessionId()) + && preparation.bindingGeneration.equals(evidence.candidate().bindingGeneration()) + && preparation.assignmentId.equals(inputs.assignmentId()) + && preparation.assignmentIntentDigest.equals(inputs.assignmentIntentDigest()) + && preparation.worldSourceDigest.equals(inputs.worldSourceDigest()) + && preparation.preparationDigest.equals(inputs.preparationDigest()) + && Arrays.equals(preparation.incarnationScopeBytes, inputs.incarnationScopeBytes()) + && Arrays.equals(preparation.incarnationSourceBytes, inputs.incarnationSourceBytes()) + && Arrays.equals( + preparation.incarnationQualificationBytes, + inputs.incarnationQualificationBytes()) + && preparation.incarnationDigest.equals(inputs.incarnationDigest()) + && preparation.timelinePreimageState.equals("ABSENT") + && preparation.absenceProofDigest.equals(inputs.absenceProofDigest()); + } + + private static boolean samePreparation( + TimelinePreparation expected, TimelinePreparation actual) { + return expected.operationId.equals(actual.operationId) + && expected.transitionId.equals(actual.transitionId) + && expected.source.equals(actual.source) + && expected.preparationDigest.equals(actual.preparationDigest) + && expected.worldSourceDigest.equals(actual.worldSourceDigest) + && expected.tenantRegionTag.equals(actual.tenantRegionTag) + && Arrays.equals(expected.incarnationScopeBytes, actual.incarnationScopeBytes) + && Arrays.equals(expected.incarnationSourceBytes, actual.incarnationSourceBytes) + && Arrays.equals( + expected.incarnationQualificationBytes, actual.incarnationQualificationBytes) + && expected.incarnationDigest.equals(actual.incarnationDigest) + && expected.timelinePreimageState.equals(actual.timelinePreimageState) + && expected.absenceProofDigest.equals(actual.absenceProofDigest); + } + + private static void lockRegionScope(DSLContext transaction, String tenantRegionTag) { + String key = "game-session-region-owner-install:v1:" + tenantRegionTag; + transaction.fetch("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", key); + } + + private static TimelinePreparation toTimelinePreparation(Record row) { + Source source = + new Source( + row.get("tenant_id", UUID.class), + row.get("game_instance_id", UUID.class), + row.get("canonical_region_id", UUID.class), + row.get("region_id", UUID.class), + row.get("lifecycle_epoch", Long.class), + row.get("lifecycle_row_version", Long.class), + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored( + row.get("lifecycle_request_bytes", byte[].class)), + row.get("capture_id", UUID.class), + row.get("graph_sha256", String.class), + row.get("preparation_input_digest", String.class)); + Long fence = row.get("executor_fence", Long.class); + return new TimelinePreparation( + row.get("initialization_operation_id", UUID.class), + row.get("transition_id", UUID.class), + row.get("account_id", UUID.class), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("character_id", UUID.class), + row.get("playable_state_scope", String.class), + row.get("game_instance_id", UUID.class), + row.get("runtime_game_instance_id", Long.class), + row.get("binding_ref", byte[].class), + row.get("session_id", String.class), + new BigInteger(row.get("binding_generation", java.math.BigDecimal.class).toPlainString()), + row.get("assignment_uuid", UUID.class), + row.get("assignment_intent_digest", String.class), + row.get("canonical_region_id", UUID.class), + row.get("region_id", UUID.class), + row.get("tenant_region_tag", String.class), + source, + row.get("world_source_digest", String.class), + row.get("preparation_digest", String.class), + row.get("stable_incarnation_scope_bytes", byte[].class), + row.get("stable_incarnation_source_bytes", byte[].class), + row.get("stable_incarnation_qualification_bytes", byte[].class), + row.get("stable_incarnation_digest", String.class), + row.get("timeline_preimage_state", String.class), + row.get("timeline_absence_proof_digest", String.class), + row.get("region_epoch", Long.class), + row.get("last_committed_tick_id", Long.class), + TimelinePreparationPhase.valueOf(row.get("phase", String.class)), + row.get("lease_token_correlation", String.class), + fence == null ? null : BigInteger.valueOf(fence), + row.get("redis_meta_digest", String.class), + row.get("updated_at", OffsetDateTime.class).toInstant()); + } + + private record InitialTimelineInputs( + String tenantRegionTag, + UUID assignmentId, + String assignmentIntentDigest, + String worldSourceDigest, + String preparationDigest, + byte[] incarnationScopeBytes, + byte[] incarnationSourceBytes, + byte[] incarnationQualificationBytes, + String incarnationDigest, + String absenceProofDigest) { + private InitialTimelineInputs { + incarnationScopeBytes = incarnationScopeBytes.clone(); + incarnationSourceBytes = incarnationSourceBytes.clone(); + incarnationQualificationBytes = incarnationQualificationBytes.clone(); + } + + @Override + public byte[] incarnationScopeBytes() { + return incarnationScopeBytes.clone(); + } + + @Override + public byte[] incarnationSourceBytes() { + return incarnationSourceBytes.clone(); + } + + @Override + public byte[] incarnationQualificationBytes() { + return incarnationQualificationBytes.clone(); + } + } + /** Installs a new durable fence for an already acquired and source-bound Redis grant. */ CanonicalGameplayRegionRuntimeStatus installOwner( Source source, @@ -321,4 +895,220 @@ record Source( private static void requireNonNil(UUID value) { if (value.equals(new UUID(0L, 0L))) throw unavailable(); } + + private static UUID canonicalNonNilUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw unavailable(); + } + return parsed; + } catch (RuntimeException malformed) { + throw unavailable(malformed); + } + } + + static final class TimelinePreparation { + private final UUID operationId; + private final UUID transitionId; + private final UUID accountId; + private final UUID tenantId; + private final UUID playableStateNamespaceId; + private final UUID characterId; + private final String playableStateScope; + private final UUID gameInstanceId; + private final long runtimeGameInstanceId; + private final byte[] bindingRef; + private final String sessionId; + private final BigInteger bindingGeneration; + private final UUID assignmentId; + private final String assignmentIntentDigest; + private final UUID canonicalRegionId; + private final UUID regionId; + private final String tenantRegionTag; + private final Source source; + private final String worldSourceDigest; + private final String preparationDigest; + private final byte[] incarnationScopeBytes; + private final byte[] incarnationSourceBytes; + private final byte[] incarnationQualificationBytes; + private final String incarnationDigest; + private final String timelinePreimageState; + private final String absenceProofDigest; + private final long regionEpoch; + private final long lastCommittedTickId; + private final TimelinePreparationPhase phase; + private final String leaseTokenCorrelation; + private final BigInteger executorFence; + private final String redisMetaDigest; + private final Instant updatedAt; + + private TimelinePreparation( + UUID operationId, + UUID transitionId, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + UUID characterId, + String playableStateScope, + UUID gameInstanceId, + long runtimeGameInstanceId, + byte[] bindingRef, + String sessionId, + BigInteger bindingGeneration, + UUID assignmentId, + String assignmentIntentDigest, + UUID canonicalRegionId, + UUID regionId, + String tenantRegionTag, + Source source, + String worldSourceDigest, + String preparationDigest, + byte[] incarnationScopeBytes, + byte[] incarnationSourceBytes, + byte[] incarnationQualificationBytes, + String incarnationDigest, + String timelinePreimageState, + String absenceProofDigest, + long regionEpoch, + long lastCommittedTickId, + TimelinePreparationPhase phase, + String leaseTokenCorrelation, + BigInteger executorFence, + String redisMetaDigest, + Instant updatedAt) { + this.operationId = Objects.requireNonNull(operationId, "operationId"); + this.transitionId = Objects.requireNonNull(transitionId, "transitionId"); + this.accountId = Objects.requireNonNull(accountId, "accountId"); + this.tenantId = Objects.requireNonNull(tenantId, "tenantId"); + this.playableStateNamespaceId = + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + this.characterId = Objects.requireNonNull(characterId, "characterId"); + this.playableStateScope = Objects.requireNonNull(playableStateScope, "playableStateScope"); + this.gameInstanceId = Objects.requireNonNull(gameInstanceId, "gameInstanceId"); + this.runtimeGameInstanceId = runtimeGameInstanceId; + this.bindingRef = Objects.requireNonNull(bindingRef, "bindingRef").clone(); + this.sessionId = Objects.requireNonNull(sessionId, "sessionId"); + this.bindingGeneration = Objects.requireNonNull(bindingGeneration, "bindingGeneration"); + this.assignmentId = Objects.requireNonNull(assignmentId, "assignmentId"); + this.assignmentIntentDigest = Objects.requireNonNull(assignmentIntentDigest, "assignmentIntentDigest"); + this.canonicalRegionId = Objects.requireNonNull(canonicalRegionId, "canonicalRegionId"); + this.regionId = Objects.requireNonNull(regionId, "regionId"); + this.tenantRegionTag = Objects.requireNonNull(tenantRegionTag, "tenantRegionTag"); + this.source = Objects.requireNonNull(source, "source"); + this.worldSourceDigest = Objects.requireNonNull(worldSourceDigest, "worldSourceDigest"); + this.preparationDigest = Objects.requireNonNull(preparationDigest, "preparationDigest"); + this.incarnationScopeBytes = + Objects.requireNonNull(incarnationScopeBytes, "incarnationScopeBytes").clone(); + this.incarnationSourceBytes = + Objects.requireNonNull(incarnationSourceBytes, "incarnationSourceBytes").clone(); + this.incarnationQualificationBytes = + Objects.requireNonNull(incarnationQualificationBytes, "incarnationQualificationBytes") + .clone(); + this.incarnationDigest = Objects.requireNonNull(incarnationDigest, "incarnationDigest"); + this.timelinePreimageState = Objects.requireNonNull(timelinePreimageState, "timelinePreimageState"); + this.absenceProofDigest = Objects.requireNonNull(absenceProofDigest, "absenceProofDigest"); + if (!incarnationDigest.equals( + CanonicalGameplayRegionIncarnationSource.digestBytes(this.incarnationSourceBytes)) + || this.incarnationQualificationBytes.length == 0 + || this.incarnationQualificationBytes.length > 8192 + || !timelinePreimageState.equals("ABSENT") + || !absenceProofDigest.matches("[0-9a-f]{64}")) { + throw unavailable(); + } + this.regionEpoch = regionEpoch; + this.lastCommittedTickId = lastCommittedTickId; + this.phase = Objects.requireNonNull(phase, "phase"); + this.leaseTokenCorrelation = leaseTokenCorrelation; + this.executorFence = executorFence; + this.redisMetaDigest = redisMetaDigest; + this.updatedAt = Objects.requireNonNull(updatedAt, "updatedAt"); + } + + UUID operationId() { + return operationId; + } + + UUID transitionId() { + return transitionId; + } + + Source source() { + return source; + } + + String tenantRegionTag() { + return tenantRegionTag; + } + + String sourceDigest() { + return preparationDigest; + } + + long regionEpoch() { + return regionEpoch; + } + + String redisMetaDigest() { + return redisMetaDigest; + } + + long lastCommittedTickId() { + return lastCommittedTickId; + } + + TimelinePreparationPhase phase() { + return phase; + } + + String leaseTokenCorrelation() { + return leaseTokenCorrelation; + } + + BigInteger executorFence() { + return executorFence; + } + + boolean matchesIncarnation( + CanonicalGameplayRegionIncarnationSource.StableEvidence current) { + return current != null + && timelinePreimageState.equals("ABSENT") + && Arrays.equals(incarnationScopeBytes, current.scopeBytes()) + && Arrays.equals(incarnationSourceBytes, current.stableCanonicalBytes()) + && Arrays.equals( + incarnationQualificationBytes, + current.timelineInitializationQualification().canonicalBytes()) + && incarnationDigest.equals(current.digest()); + } + + String absenceProofDigest() { + return absenceProofDigest; + } + + } + + static final class InitialInitializationPermit { + private final UUID operationId; + private final String sourceDigest; + + private InitialInitializationPermit(UUID operationId, String sourceDigest) { + this.operationId = Objects.requireNonNull(operationId, "operationId"); + this.sourceDigest = Objects.requireNonNull(sourceDigest, "sourceDigest"); + } + + UUID operationId() { + return operationId; + } + + String sourceDigest() { + return sourceDigest; + } + } + + enum TimelinePreparationPhase { + PREPARED, + INITIALIZING, + REDIS_INITIALIZED, + INSTALLED + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java new file mode 100644 index 0000000000..bbb5794abe --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive descriptor contribution for the manually composed region binding bridge. */ +public final class CanonicalGameplayRegionBindingBridgeRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.region-session-binding-bridge.v1"; + public static final String SCRIPT_PATH = "redis/lua/game-session-region-session-binding-bridge.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-region-session-binding-bridge.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + return List.of(readDescriptor()); + } + + private RedisScriptDescriptor readDescriptor() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { + throw unavailable(); + } + return descriptor; + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Canonical region binding bridge descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java index fd2e684b36..87beeada48 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java @@ -16,9 +16,12 @@ public final class CanonicalGameplayRegionLeaseRedisScriptContribution public static final String ACQUIRE_ID = "game-session.region-lease-acquire.v1"; public static final String RENEW_ID = "game-session.region-lease-renew.v1"; public static final String READ_ID = "game-session.region-lease-read.v1"; + public static final String TIMELINE_INITIALIZE_ID = "game-session.region-timeline-initialize.v1"; public static final String ACQUIRE_PATH = "redis/lua/game-session-region-lease-acquire.lua"; public static final String RENEW_PATH = "redis/lua/game-session-region-lease-renew.lua"; public static final String READ_PATH = "redis/lua/game-session-region-lease-read.lua"; + public static final String TIMELINE_INITIALIZE_PATH = + "redis/lua/game-session-region-timeline-initialize.lua"; private static final JsonMapper JSON = JsonMapper.builder() .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) @@ -36,7 +39,8 @@ public Collection descriptors() { return List.of( read("/redis/scripts/game-session-region-lease-acquire.json", ACQUIRE_ID), read("/redis/scripts/game-session-region-lease-renew.json", RENEW_ID), - read("/redis/scripts/game-session-region-lease-read.json", READ_ID)); + read("/redis/scripts/game-session-region-lease-read.json", READ_ID), + read("/redis/scripts/game-session-region-timeline-initialize.json", TIMELINE_INITIALIZE_ID)); } private RedisScriptDescriptor read(String path, String id) { diff --git a/services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql b/services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql new file mode 100644 index 0000000000..8f90318085 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql @@ -0,0 +1,230 @@ +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + ADD COLUMN bridge_operation_id uuid, + ADD COLUMN bridge_preimage_state character varying(8), + ADD COLUMN runtime_entity_id bigint, + ADD COLUMN entity_projection_generation bigint, + ADD COLUMN entity_projection_fence bigint, + ADD COLUMN entity_workload_namespace text, + ADD COLUMN assignment_uuid uuid, + ADD COLUMN assignment_intent_digest character varying(64), + ADD COLUMN entity_reference_digest character varying(64), + ADD COLUMN world_source_digest character varying(64), + ADD COLUMN canonical_region_id uuid, + ADD COLUMN world_lifecycle_epoch bigint, + ADD COLUMN world_lifecycle_row_version bigint, + ADD COLUMN world_capture_id uuid, + ADD COLUMN world_graph_sha256 character varying(64), + ADD COLUMN world_preparation_input_digest character varying(71), + ADD COLUMN executor_fence numeric, + ADD COLUMN lease_token_correlation character varying(64), + ADD COLUMN redis_readback_digest character varying(64), + ADD COLUMN acknowledged_at timestamp with time zone; + +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + DROP CONSTRAINT chk_gs_canonical_binding_region_bridge_obligation; + +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + ADD CONSTRAINT chk_gs_canonical_binding_region_bridge_obligation CHECK ( + binding_generation > 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_game_instance_id > 0 + -- [jooq ignore start] + AND session_id <> '' + -- [jooq ignore stop] + AND session_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND session_id <> '00000000-0000-0000-0000-000000000000' + AND session_id !~ '^[[:space:]]*$' + AND session_id !~ '[[:cntrl:]]' + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND region_epoch > 0 + AND status IN ('REQUIRED', 'ACKNOWLEDGED') + AND inventory_revision > 0 + AND ( + (bridge_operation_id IS NULL + AND bridge_preimage_state IS NULL + AND runtime_entity_id IS NULL + AND entity_projection_generation IS NULL + AND entity_projection_fence IS NULL + AND entity_workload_namespace IS NULL + AND assignment_uuid IS NULL + AND assignment_intent_digest IS NULL + AND entity_reference_digest IS NULL + AND world_source_digest IS NULL + AND canonical_region_id IS NULL + AND world_lifecycle_epoch IS NULL + AND world_lifecycle_row_version IS NULL + AND world_capture_id IS NULL + AND world_graph_sha256 IS NULL + AND world_preparation_input_digest IS NULL) + OR + (bridge_operation_id IS NOT NULL + AND bridge_preimage_state IS NOT NULL + AND bridge_preimage_state = 'ABSENT' + AND runtime_entity_id IS NOT NULL + AND runtime_entity_id > 0 + AND entity_projection_generation IS NOT NULL + AND entity_projection_generation > 0 + AND entity_projection_fence IS NOT NULL + AND entity_projection_fence > 0 + AND entity_workload_namespace IS NOT NULL + AND entity_workload_namespace <> '' + AND assignment_uuid IS NOT NULL + AND assignment_uuid <> '00000000-0000-0000-0000-000000000000'::uuid + AND assignment_intent_digest IS NOT NULL + AND assignment_intent_digest ~ '^[0-9a-f]{64}$' + AND entity_reference_digest IS NOT NULL + AND entity_reference_digest ~ '^[0-9a-f]{64}$' + AND world_source_digest IS NOT NULL + AND world_source_digest ~ '^[0-9a-f]{64}$' + AND canonical_region_id IS NOT NULL + AND canonical_region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND world_lifecycle_epoch IS NOT NULL + AND world_lifecycle_epoch > 0 + AND world_lifecycle_row_version IS NOT NULL + AND world_lifecycle_row_version >= 0 + AND world_capture_id IS NOT NULL + AND world_capture_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND world_graph_sha256 IS NOT NULL + AND world_graph_sha256 ~ '^[0-9a-f]{64}$' + AND world_preparation_input_digest IS NOT NULL + AND world_preparation_input_digest ~ '^sha256:[0-9a-f]{64}$') + ) + AND ( + (status = 'REQUIRED' + AND redis_readback_digest IS NULL + AND acknowledged_at IS NULL) + OR + (status = 'ACKNOWLEDGED' + AND bridge_operation_id IS NOT NULL + AND executor_fence IS NOT NULL + AND executor_fence > 0 + AND lease_token_correlation IS NOT NULL + AND lease_token_correlation ~ '^[0-9a-f]{64}$' + AND redis_readback_digest IS NOT NULL + AND redis_readback_digest ~ '^[0-9a-f]{64}$' + AND acknowledged_at IS NOT NULL) + ) + AND ( + (bridge_operation_id IS NULL + AND executor_fence IS NULL + AND lease_token_correlation IS NULL) + OR + (bridge_operation_id IS NOT NULL + AND executor_fence IS NOT NULL + AND executor_fence > 0 + AND lease_token_correlation IS NOT NULL + AND lease_token_correlation ~ '^[0-9a-f]{64}$') + ) + ); + +CREATE UNIQUE INDEX ux_gs_canonical_region_bridge_operation + ON game_session_canonical_binding_region_bridge_obligation (bridge_operation_id) + WHERE bridge_operation_id IS NOT NULL; + +CREATE TABLE game_session_region_timeline_preparation ( + initialization_operation_id uuid NOT NULL, + transition_id uuid NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + character_id uuid NOT NULL, + playable_state_scope character varying(16) NOT NULL, + game_instance_id uuid NOT NULL, + runtime_game_instance_id bigint NOT NULL, + binding_ref bytea NOT NULL, + session_id character varying(36) NOT NULL, + binding_generation numeric NOT NULL, + canonical_region_id uuid NOT NULL, + region_id uuid NOT NULL, + tenant_region_tag character varying(101) NOT NULL, + lifecycle_epoch bigint NOT NULL, + lifecycle_row_version bigint NOT NULL, + capture_id uuid NOT NULL, + lifecycle_request_bytes bytea NOT NULL, + graph_sha256 character varying(64) NOT NULL, + preparation_input_digest character varying(71) NOT NULL, + assignment_uuid uuid NOT NULL, + assignment_intent_digest character varying(64) NOT NULL, + world_source_digest character varying(64) NOT NULL, + preparation_digest character varying(64) NOT NULL, + stable_incarnation_scope_bytes bytea NOT NULL, + stable_incarnation_source_bytes bytea NOT NULL, + stable_incarnation_qualification_bytes bytea NOT NULL, + stable_incarnation_digest character varying(64) NOT NULL, + timeline_preimage_state character varying(8) NOT NULL, + timeline_absence_proof_digest character varying(64) NOT NULL, + region_epoch bigint NOT NULL, + last_committed_tick_id bigint NOT NULL, + phase character varying(24) NOT NULL, + lease_token_correlation character varying(64), + executor_fence bigint, + redis_meta_digest character varying(64), + created_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone NOT NULL, + CONSTRAINT pk_game_session_region_timeline_preparation + PRIMARY KEY (initialization_operation_id), + CONSTRAINT ux_game_session_region_timeline_preparation_transition + UNIQUE (transition_id), + CONSTRAINT ux_game_session_region_timeline_preparation_scope + UNIQUE (tenant_id, game_instance_id, region_id), + CONSTRAINT ck_game_session_region_timeline_preparation_ids CHECK ( + initialization_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND character_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND capture_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND assignment_uuid <> '00000000-0000-0000-0000-000000000000'::uuid), + CONSTRAINT ck_game_session_region_timeline_preparation_binding CHECK ( + playable_state_scope = 'SHARED' + AND runtime_game_instance_id > 0 + AND octet_length(binding_ref) BETWEEN 1 AND 128 + AND session_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND session_id <> '00000000-0000-0000-0000-000000000000' + AND binding_generation > 0), + CONSTRAINT ck_game_session_region_timeline_preparation_source CHECK ( + tenant_region_tag ~ '^r1-[0-9a-f]{32}-[0-9a-f]{32}-[0-9a-f]{32}$' + AND lifecycle_epoch > 0 + AND lifecycle_row_version >= 0 + AND octet_length(lifecycle_request_bytes) BETWEEN 1 AND 4096 + AND graph_sha256 ~ '^[0-9a-f]{64}$' + AND preparation_input_digest ~ '^sha256:[0-9a-f]{64}$' + AND assignment_intent_digest ~ '^[0-9a-f]{64}$' + AND world_source_digest ~ '^[0-9a-f]{64}$' + AND preparation_digest ~ '^[0-9a-f]{64}$' + AND octet_length(stable_incarnation_scope_bytes) BETWEEN 1 AND 4096 + AND octet_length(stable_incarnation_source_bytes) BETWEEN 1 AND 65536 + AND octet_length(stable_incarnation_qualification_bytes) BETWEEN 1 AND 8192 + AND stable_incarnation_digest ~ '^[0-9a-f]{64}$' + AND timeline_preimage_state = 'ABSENT' + AND timeline_absence_proof_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT ck_game_session_region_timeline_preparation_baseline CHECK ( + region_epoch = 1 + AND last_committed_tick_id = -1), + CONSTRAINT ck_game_session_region_timeline_preparation_phase CHECK ( + (phase IN ('PREPARED', 'INITIALIZING') + AND lease_token_correlation IS NULL + AND executor_fence IS NULL + AND redis_meta_digest IS NULL) + OR + (phase = 'REDIS_INITIALIZED' + AND lease_token_correlation IS NOT NULL + AND lease_token_correlation ~ '^[0-9a-f]{64}$' + AND executor_fence IS NULL + AND redis_meta_digest IS NOT NULL + AND redis_meta_digest ~ '^[0-9a-f]{64}$') + OR + (phase = 'INSTALLED' + AND lease_token_correlation IS NOT NULL + AND lease_token_correlation ~ '^[0-9a-f]{64}$' + AND executor_fence IS NOT NULL + AND executor_fence > 0 + AND redis_meta_digest IS NOT NULL + AND redis_meta_digest ~ '^[0-9a-f]{64}$')) +); diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua index ee0ef12cf4..3c6851ac9b 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua @@ -1,23 +1,71 @@ --- The region lease contains only its opaque liveness token and Redis TTL. -local key = KEYS[1] -if #KEYS ~= 1 or #ARGV ~= 3 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end +-- Claims only a lease whose separate canonical timeline metadata already matches the expected epoch. +local leaseKey = KEYS[1] +local metaKey = KEYS[2] +if #KEYS ~= 2 or #ARGV ~= 4 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end local token = ARGV[2] -local ttl = ARGV[3] -if not string.match(ttl, '^[1-9][0-9]*$') or string.len(ttl) > 19 +local expectedEpoch = ARGV[3] +local ttl = ARGV[4] + +local function validUuid(value) + return string.len(value) == 36 + and string.sub(value, 9, 9) == '-' + and string.sub(value, 14, 14) == '-' + and string.sub(value, 19, 19) == '-' + and string.sub(value, 24, 24) == '-' + and string.match(string.gsub(value, '%-', ''), '^[0-9a-f]+$') + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positiveInt64(value) + return string.match(value, '^[1-9][0-9]*$') + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function nonnegativeInt64(value) + return (value == '0' or string.match(value, '^[1-9][0-9]*$')) + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function validMeta() + if redis.call('TYPE', metaKey).ok ~= 'hash' + or redis.call('PTTL', metaKey) ~= -1 + or redis.call('HGET', metaKey, 'region_epoch') ~= expectedEpoch then return false end + local tickId = redis.call('HGET', metaKey, 'current_tick_id') + local state = redis.call('HGET', metaKey, 'current_tick_state') + local terminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') + if tickId == '-1' then + return state == 'APPLIED' and not terminalAt + end + if not nonnegativeInt64(tickId) then return false end + if state == 'STAGED' or state == 'RESOLVING' then return not terminalAt end + if state == 'APPLIED' or state == 'ABANDONED' then return positiveInt64(terminalAt or '') end + return false +end + +local tag1 = string.match(leaseKey, '^tick%-executor%-lease:{([^{}:]+)}$') +local tag2 = string.match(metaKey, '^tick:{([^{}:]+)}:meta$') +local tagTenant, tagGame, tagRegion = + string.match(tag1 or '', '^r1%-([0-9a-f]+)%-([0-9a-f]+)%-([0-9a-f]+)$') +if not tag1 or tag1 ~= tag2 + or string.len(tag1) ~= 101 + or not tagTenant or string.len(tagTenant) ~= 32 + or string.len(tagGame) ~= 32 or string.len(tagRegion) ~= 32 + or not validUuid(token) + or not positiveInt64(expectedEpoch) + or not string.match(ttl, '^[1-9][0-9]*$') + or string.len(ttl) > 19 or (string.len(ttl) == 19 and ttl > '9223372036854775807') then return -1 end -if string.len(token) ~= 36 - or string.sub(token, 9, 9) ~= '-' - or string.sub(token, 14, 14) ~= '-' - or string.sub(token, 19, 19) ~= '-' - or string.sub(token, 24, 24) ~= '-' - or not string.match(string.gsub(token, '%-', ''), '^[0-9a-f]+$') then return -1 end -local keyType = redis.call('TYPE', key).ok +if not validMeta() then return 0 end + +local keyType = redis.call('TYPE', leaseKey).ok if keyType ~= 'none' and keyType ~= 'string' then return -2 end if keyType == 'string' then - if redis.call('PTTL', key) <= 0 then return 0 end - if redis.call('GET', key) == token then return 2 end + if redis.call('PTTL', leaseKey) <= 0 then return 0 end + if redis.call('GET', leaseKey) == token then return 2 end return 0 end -local result = redis.call('SET', key, token, 'PX', ttl, 'NX') +local result = redis.call('SET', leaseKey, token, 'PX', ttl, 'NX') if result and result.ok == 'OK' then return 1 end return 0 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua index 0059a7d190..d78fdc7db9 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua @@ -1,14 +1,58 @@ --- Exact atomic readback for one live opaque liveness token. -local key = KEYS[1] -if #KEYS ~= 1 or #ARGV ~= 2 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end +-- Exact atomic readback for one live grant and its complete separate canonical timeline epoch. +local leaseKey = KEYS[1] +local metaKey = KEYS[2] +if #KEYS ~= 2 or #ARGV ~= 3 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end local token = ARGV[2] -if string.len(token) ~= 36 - or string.sub(token, 9, 9) ~= '-' - or string.sub(token, 14, 14) ~= '-' - or string.sub(token, 19, 19) ~= '-' - or string.sub(token, 24, 24) ~= '-' - or not string.match(string.gsub(token, '%-', ''), '^[0-9a-f]+$') then return -1 end -local keyType = redis.call('TYPE', key).ok -if keyType ~= 'string' or redis.call('PTTL', key) <= 0 - or redis.call('GET', key) ~= token then return 0 end +local expectedEpoch = ARGV[3] + +local function validUuid(value) + return string.len(value) == 36 + and string.sub(value, 9, 9) == '-' + and string.sub(value, 14, 14) == '-' + and string.sub(value, 19, 19) == '-' + and string.sub(value, 24, 24) == '-' + and string.match(string.gsub(value, '%-', ''), '^[0-9a-f]+$') + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positiveInt64(value) + return string.match(value, '^[1-9][0-9]*$') + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function nonnegativeInt64(value) + return (value == '0' or string.match(value, '^[1-9][0-9]*$')) + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function validMeta() + if redis.call('TYPE', metaKey).ok ~= 'hash' + or redis.call('PTTL', metaKey) ~= -1 + or redis.call('HGET', metaKey, 'region_epoch') ~= expectedEpoch then return false end + local tickId = redis.call('HGET', metaKey, 'current_tick_id') + local state = redis.call('HGET', metaKey, 'current_tick_state') + local terminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') + if tickId == '-1' then return state == 'APPLIED' and not terminalAt end + if not nonnegativeInt64(tickId) then return false end + if state == 'STAGED' or state == 'RESOLVING' then return not terminalAt end + if state == 'APPLIED' or state == 'ABANDONED' then return positiveInt64(terminalAt or '') end + return false +end + +local tag1 = string.match(leaseKey, '^tick%-executor%-lease:{([^{}:]+)}$') +local tag2 = string.match(metaKey, '^tick:{([^{}:]+)}:meta$') +local tagTenant, tagGame, tagRegion = + string.match(tag1 or '', '^r1%-([0-9a-f]+)%-([0-9a-f]+)%-([0-9a-f]+)$') +if not tag1 or tag1 ~= tag2 + or string.len(tag1) ~= 101 + or not tagTenant or string.len(tagTenant) ~= 32 + or string.len(tagGame) ~= 32 or string.len(tagRegion) ~= 32 + or not validUuid(token) + or not positiveInt64(expectedEpoch) then return -1 end +if not validMeta() + or redis.call('TYPE', leaseKey).ok ~= 'string' + or redis.call('PTTL', leaseKey) <= 0 + or redis.call('GET', leaseKey) ~= token then return 0 end return 1 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua index b9a8939717..6b3daa8c1a 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua @@ -1,18 +1,63 @@ --- Extends only the exact opaque liveness token and never advances the durable executor fence. -local key = KEYS[1] -if #KEYS ~= 1 or #ARGV ~= 3 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end +-- Renews only the exact live lease and a structurally complete separate metadata epoch. +local leaseKey = KEYS[1] +local metaKey = KEYS[2] +if #KEYS ~= 2 or #ARGV ~= 4 or ARGV[1] ~= 'gs_region_lease/v1' then return -1 end local token = ARGV[2] -local ttl = ARGV[3] -if string.len(token) ~= 36 - or string.sub(token, 9, 9) ~= '-' - or string.sub(token, 14, 14) ~= '-' - or string.sub(token, 19, 19) ~= '-' - or string.sub(token, 24, 24) ~= '-' - or not string.match(string.gsub(token, '%-', ''), '^[0-9a-f]+$') then return -1 end -if not string.match(ttl, '^[1-9][0-9]*$') or string.len(ttl) > 19 +local expectedEpoch = ARGV[3] +local ttl = ARGV[4] + +local function validUuid(value) + return string.len(value) == 36 + and string.sub(value, 9, 9) == '-' + and string.sub(value, 14, 14) == '-' + and string.sub(value, 19, 19) == '-' + and string.sub(value, 24, 24) == '-' + and string.match(string.gsub(value, '%-', ''), '^[0-9a-f]+$') + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positiveInt64(value) + return string.match(value, '^[1-9][0-9]*$') + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function nonnegativeInt64(value) + return (value == '0' or string.match(value, '^[1-9][0-9]*$')) + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function validMeta() + if redis.call('TYPE', metaKey).ok ~= 'hash' + or redis.call('PTTL', metaKey) ~= -1 + or redis.call('HGET', metaKey, 'region_epoch') ~= expectedEpoch then return false end + local tickId = redis.call('HGET', metaKey, 'current_tick_id') + local state = redis.call('HGET', metaKey, 'current_tick_state') + local terminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') + if tickId == '-1' then return state == 'APPLIED' and not terminalAt end + if not nonnegativeInt64(tickId) then return false end + if state == 'STAGED' or state == 'RESOLVING' then return not terminalAt end + if state == 'APPLIED' or state == 'ABANDONED' then return positiveInt64(terminalAt or '') end + return false +end + +local tag1 = string.match(leaseKey, '^tick%-executor%-lease:{([^{}:]+)}$') +local tag2 = string.match(metaKey, '^tick:{([^{}:]+)}:meta$') +local tagTenant, tagGame, tagRegion = + string.match(tag1 or '', '^r1%-([0-9a-f]+)%-([0-9a-f]+)%-([0-9a-f]+)$') +if not tag1 or tag1 ~= tag2 + or string.len(tag1) ~= 101 + or not tagTenant or string.len(tagTenant) ~= 32 + or string.len(tagGame) ~= 32 or string.len(tagRegion) ~= 32 + or not validUuid(token) + or not positiveInt64(expectedEpoch) + or not string.match(ttl, '^[1-9][0-9]*$') + or string.len(ttl) > 19 or (string.len(ttl) == 19 and ttl > '9223372036854775807') then return -1 end -local keyType = redis.call('TYPE', key).ok -if keyType ~= 'string' or redis.call('PTTL', key) <= 0 - or redis.call('GET', key) ~= token then return 0 end -redis.call('PEXPIRE', key, ttl) +if not validMeta() then return 0 end +if redis.call('TYPE', leaseKey).ok ~= 'string' + or redis.call('PTTL', leaseKey) <= 0 + or redis.call('GET', leaseKey) ~= token then return 0 end +redis.call('PEXPIRE', leaseKey, ttl) return 1 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-session-binding-bridge.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-session-binding-bridge.lua new file mode 100644 index 0000000000..c232134c8f --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-session-binding-bridge.lua @@ -0,0 +1,105 @@ +-- One exact first-NEW binding write/readback under the current region lease and timeline. +local leaseKey = KEYS[1] +local metaKey = KEYS[2] +local bindingKey = KEYS[3] +if #KEYS ~= 3 or #ARGV ~= 6 or ARGV[1] ~= 'gs_region_binding_bridge/v1' then + return -1 +end + +local action = ARGV[2] +local token = ARGV[3] +local expectedEpoch = ARGV[4] +local sessionId = ARGV[5] +local generation = ARGV[6] +if action ~= 'APPLY' and action ~= 'READBACK' and action ~= 'PROBE' then return -1 end + +local function validUuid(value) + return string.len(value) == 36 + and string.sub(value, 9, 9) == '-' + and string.sub(value, 14, 14) == '-' + and string.sub(value, 19, 19) == '-' + and string.sub(value, 24, 24) == '-' + and string.match(string.gsub(value, '%-', ''), '^[0-9a-f]+$') + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positiveInt64(value) + return string.match(value, '^[1-9][0-9]*$') + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function nonnegativeInt64(value) + return (value == '0' or string.match(value, '^[1-9][0-9]*$')) + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function positiveGeneration(value) + return string.match(value, '^[1-9][0-9]*$') and string.len(value) <= 128 +end + +local tag1 = string.match(leaseKey, '^tick%-executor%-lease:{([^{}:]+)}$') +local tag2 = string.match(metaKey, '^tick:{([^{}:]+)}:meta$') +local tag3, entityId = string.match(bindingKey, '^tick:{([^{}:]+)}:session%-binding:([1-9][0-9]*)$') +local tagTenant, tagGame, tagRegion = + string.match(tag1 or '', '^r1%-([0-9a-f]+)%-([0-9a-f]+)%-([0-9a-f]+)$') +if not tag1 or tag1 ~= tag2 or tag1 ~= tag3 + or string.len(tag1) ~= 101 + or not tagTenant or string.len(tagTenant) ~= 32 + or string.len(tagGame) ~= 32 or string.len(tagRegion) ~= 32 + or not positiveInt64(entityId) + or not validUuid(token) + or not positiveInt64(expectedEpoch) + or not validUuid(sessionId) + or not positiveGeneration(generation) then return -1 end + +local leaseType = redis.call('TYPE', leaseKey).ok +if leaseType ~= 'string' or redis.call('PTTL', leaseKey) <= 0 + or redis.call('GET', leaseKey) ~= token then return 0 end + +local metaType = redis.call('TYPE', metaKey).ok +if metaType ~= 'hash' + or redis.call('PTTL', metaKey) ~= -1 + or redis.call('HGET', metaKey, 'region_epoch') ~= expectedEpoch then return 0 end +local currentTickId = redis.call('HGET', metaKey, 'current_tick_id') +local currentTickState = redis.call('HGET', metaKey, 'current_tick_state') +local currentTickTerminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') +if currentTickId == '-1' then + if currentTickState ~= 'APPLIED' or currentTickTerminalAt then return 0 end +elseif not nonnegativeInt64(currentTickId) then + return 0 +elseif currentTickState == 'STAGED' or currentTickState == 'RESOLVING' then + if currentTickTerminalAt then return 0 end +elseif currentTickState == 'APPLIED' or currentTickState == 'ABANDONED' then + if not positiveInt64(currentTickTerminalAt or '') then return 0 end +else + return 0 +end + +local bindingType = redis.call('TYPE', bindingKey).ok +if bindingType == 'hash' and redis.call('PTTL', bindingKey) ~= -1 then return 0 end +if action == 'PROBE' then + if bindingType == 'none' then return 4 end + if bindingType ~= 'hash' or redis.call('HLEN', bindingKey) ~= 2 then return 0 end + if redis.call('HGET', bindingKey, 'session_id') == sessionId + and redis.call('HGET', bindingKey, 'binding_generation') == generation then return 5 end + return 0 +end +if action == 'READBACK' then + if bindingType ~= 'hash' or redis.call('HLEN', bindingKey) ~= 2 + or redis.call('HGET', bindingKey, 'session_id') ~= sessionId + or redis.call('HGET', bindingKey, 'binding_generation') ~= generation then return 0 end + return 3 +end + +if bindingType == 'none' then + redis.call('HSET', bindingKey, + 'session_id', sessionId, + 'binding_generation', generation) + return 1 +end +if bindingType ~= 'hash' or redis.call('HLEN', bindingKey) ~= 2 then return 0 end +if redis.call('HGET', bindingKey, 'session_id') == sessionId + and redis.call('HGET', bindingKey, 'binding_generation') == generation then return 2 end +return 0 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua new file mode 100644 index 0000000000..2b09a01ef0 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua @@ -0,0 +1,106 @@ +-- Proves a truly absent timeline, then initializes its complete baseline with the first lease. +local leaseKey = KEYS[1] +local metaKey = KEYS[2] +if #KEYS ~= 2 or #ARGV ~= 8 or ARGV[1] ~= 'gs_region_timeline_init/v1' then return -1 end +local action = ARGV[2] +local token = ARGV[3] +local expectedEpoch = ARGV[4] +local operationId = ARGV[5] +local sourceDigest = ARGV[6] +local ttl = ARGV[7] +local mayCreate = ARGV[8] + +local function validUuid(value) + return string.len(value) == 36 + and string.sub(value, 9, 9) == '-' + and string.sub(value, 14, 14) == '-' + and string.sub(value, 19, 19) == '-' + and string.sub(value, 24, 24) == '-' + and string.match(string.gsub(value, '%-', ''), '^[0-9a-f]+$') + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positiveInt64(value) + return string.match(value, '^[1-9][0-9]*$') + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function nonnegativeInt64(value) + return (value == '0' or string.match(value, '^[1-9][0-9]*$')) + and string.len(value) <= 19 + and not (string.len(value) == 19 and value > '9223372036854775807') +end + +local function validTimelineMeta() + if redis.call('TYPE', metaKey).ok ~= 'hash' + or redis.call('PTTL', metaKey) ~= -1 + or redis.call('HGET', metaKey, 'region_epoch') ~= expectedEpoch + or redis.call('HGET', metaKey, 'first_timeline_operation_id') ~= operationId + or redis.call('HGET', metaKey, 'first_timeline_source_digest') ~= sourceDigest then return false end + local tickId = redis.call('HGET', metaKey, 'current_tick_id') + local state = redis.call('HGET', metaKey, 'current_tick_state') + local terminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') + if tickId == '-1' then return state == 'APPLIED' and not terminalAt end + if not nonnegativeInt64(tickId) then return false end + if state == 'STAGED' or state == 'RESOLVING' then return not terminalAt end + if state == 'APPLIED' or state == 'ABANDONED' then return positiveInt64(terminalAt or '') end + return false +end + +local tag1 = string.match(leaseKey, '^tick%-executor%-lease:{([^{}:]+)}$') +local tag2 = string.match(metaKey, '^tick:{([^{}:]+)}:meta$') +local tagTenant, tagGame, tagRegion = + string.match(tag1 or '', '^r1%-([0-9a-f]+)%-([0-9a-f]+)%-([0-9a-f]+)$') +if not tag1 or tag1 ~= tag2 + or string.len(tag1) ~= 101 + or not tagTenant or string.len(tagTenant) ~= 32 + or string.len(tagGame) ~= 32 or string.len(tagRegion) ~= 32 + or (action ~= 'PROBE' and action ~= 'INITIALIZE' and action ~= 'VERIFY') + or not validUuid(token) + or expectedEpoch ~= '1' + or not validUuid(operationId) + or not string.match(sourceDigest, '^[0-9a-f]+$') or string.len(sourceDigest) ~= 64 + or not positiveInt64(ttl) + or (mayCreate ~= '0' and mayCreate ~= '1') then return -1 end + +local leaseType = redis.call('TYPE', leaseKey).ok +local metaType = redis.call('TYPE', metaKey).ok +if (leaseType ~= 'none' and leaseType ~= 'string') + or (metaType ~= 'none' and metaType ~= 'hash') then return -2 end + +if action == 'PROBE' then + if leaseType == 'none' and metaType == 'none' then return 1 end + return 0 +end + +if action == 'VERIFY' then + if not validTimelineMeta() + or leaseType ~= 'string' + or redis.call('PTTL', leaseKey) <= 0 + or redis.call('GET', leaseKey) ~= token then return 0 end + return 3 +end + +if metaType == 'none' then + if leaseType ~= 'none' or mayCreate ~= '1' then return 0 end + redis.call('HSET', metaKey, + 'region_epoch', expectedEpoch, + 'current_tick_id', '-1', + 'current_tick_state', 'APPLIED', + 'first_timeline_operation_id', operationId, + 'first_timeline_source_digest', sourceDigest) +elseif not validTimelineMeta() then + return 0 +end + +if leaseType == 'string' then + local pttl = redis.call('PTTL', leaseKey) + if pttl <= 0 then return 0 end + if redis.call('GET', leaseKey) == token then return 2 end + return 0 +end + +local result = redis.call('SET', leaseKey, token, 'PX', ttl, 'NX') +if result and result.ok == 'OK' then return 1 end +return 0 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json index 5dc87d52af..34def97cdd 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json @@ -1,12 +1,15 @@ { "scriptId": "game-session.region-lease-acquire.v1", "resourcePath": "redis/lua/game-session-region-lease-acquire.lua", - "sha256": "69aa93ce55c5ade188e60bfe71f21c7f54c569016d845abf79e0887999bc8b9d", + "sha256": "f13d30294753b98b715b9652749d6e25285a847f98d57677c3b193d1cc7aee93", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", - "keys": [{"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}], - "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "leaseTtlMs"}], + "keys": [ + {"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}, + {"name": "regionMeta", "ownedPrefix": "tick:", "hashTagDeclaration": "REQUIRED"} + ], + "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "expectedRegionEpoch"}, {"name": "leaseTtlMs"}], "category": "TICK_LOCK", "outcomes": [ {"code": "LEASE_ACQUIRED", "category": "SUCCESS", "effect": "MUTATING"}, diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json index 1a46ba2ca0..30a6e0f0b5 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json @@ -1,12 +1,15 @@ { "scriptId": "game-session.region-lease-read.v1", "resourcePath": "redis/lua/game-session-region-lease-read.lua", - "sha256": "564267ce5acd15cab89ade66466e5d1b959aaadee432cc20ec097915e138acf0", + "sha256": "694631a5d389e6cf75cf108e2f81ee537e1b50e43fa40db8efe4249080c86ef0", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", - "keys": [{"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}], - "arguments": [{"name": "schema"}, {"name": "token"}], + "keys": [ + {"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}, + {"name": "regionMeta", "ownedPrefix": "tick:", "hashTagDeclaration": "REQUIRED"} + ], + "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "expectedRegionEpoch"}], "category": "TICK_LOCK", "outcomes": [ {"code": "LEASE_CURRENT", "category": "SUCCESS", "effect": "NON_MUTATING"}, diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json index 015ecf7a66..a1a306ce63 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json @@ -1,12 +1,15 @@ { "scriptId": "game-session.region-lease-renew.v1", "resourcePath": "redis/lua/game-session-region-lease-renew.lua", - "sha256": "322963204c4d5290fa31354dd71c2d20d3dd9f2185deb4644185427345eee4f4", + "sha256": "b3bbab855f90f4431d2f358b92780907f0b7f67cb3bd673b49973f8b16276c19", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", - "keys": [{"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}], - "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "leaseTtlMs"}], + "keys": [ + {"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}, + {"name": "regionMeta", "ownedPrefix": "tick:", "hashTagDeclaration": "REQUIRED"} + ], + "arguments": [{"name": "schema"}, {"name": "token"}, {"name": "expectedRegionEpoch"}, {"name": "leaseTtlMs"}], "category": "TICK_LOCK", "outcomes": [ {"code": "LEASE_RENEWED", "category": "SUCCESS", "effect": "MUTATING"}, diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-session-binding-bridge.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-session-binding-bridge.json new file mode 100644 index 0000000000..5bcb861167 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-session-binding-bridge.json @@ -0,0 +1,37 @@ +{ + "scriptId": "game-session.region-session-binding-bridge.v1", + "resourcePath": "redis/lua/game-session-region-session-binding-bridge.lua", + "sha256": "29c1832217644dd22f79f84dc749d3b93ce2da440e60b95efe9a988dd2337009", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + {"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}, + {"name": "regionMeta", "ownedPrefix": "tick:", "hashTagDeclaration": "REQUIRED"}, + {"name": "regionSessionBinding", "ownedPrefix": "tick:", "hashTagDeclaration": "REQUIRED"} + ], + "arguments": [ + {"name": "schema"}, + {"name": "action"}, + {"name": "leaseToken"}, + {"name": "expectedRegionEpoch"}, + {"name": "sessionId"}, + {"name": "bindingGeneration"} + ], + "category": "TICK_LOCK", + "outcomes": [ + {"code": "BINDING_APPLIED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "BINDING_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "BINDING_READBACK_MATCH", "category": "SUCCESS", "effect": "NON_MUTATING"}, + {"code": "BINDING_PREIMAGE_ABSENT", "category": "SUCCESS", "effect": "NON_MUTATING"}, + {"code": "BINDING_PREIMAGE_EXACT", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "STALE_OR_CONFLICT", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "REGION", + "lossClass": "STAGED_EFFECT_OR_RETRY", + "tailLossBehavior": "The script requires the same live opaque region lease and an already-established separate tick metadata epoch. It never initializes or resets metadata. A new SQL operation requires a lease- and epoch-checked absent binding preimage; a retained operation may retry only absence or its exact session and binding generation. A different or malformed region binding is preserved and refused.", + "compatibilityLevel": "COMPATIBLE", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "none"}], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json new file mode 100644 index 0000000000..9d2ba49029 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json @@ -0,0 +1,32 @@ +{ + "scriptId": "game-session.region-timeline-initialize.v1", + "resourcePath": "redis/lua/game-session-region-timeline-initialize.lua", + "sha256": "93204b35a25e88883633d6a2e33ddc622d21ac69c82c6c7843251ced56138c3b", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + {"name": "regionLease", "ownedPrefix": "tick-executor-lease:", "hashTagDeclaration": "REQUIRED"}, + {"name": "regionMeta", "ownedPrefix": "tick:", "hashTagDeclaration": "REQUIRED"} + ], + "arguments": [ + {"name": "schema"}, {"name": "action"}, {"name": "token"}, {"name": "expectedRegionEpoch"}, + {"name": "initializationOperationId"}, {"name": "preparationDigest"}, {"name": "leaseTtlMs"}, + {"name": "mayCreateFromAbsence"} + ], + "category": "TICK_LOCK", + "outcomes": [ + {"code": "TIMELINE_INITIALIZED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "INITIALIZATION_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "TIMELINE_ABSENT", "category": "SUCCESS", "effect": "NON_MUTATING"}, + {"code": "EXISTING_OR_CONFLICTING_STATE", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "TYPE_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "REGION", + "lossClass": "STAGED_EFFECT_OR_RETRY", + "tailLossBehavior": "Only the original durable preparation may establish the complete epoch-1 and tick-minus-one APPLIED baseline. An exact retained marker permits same-operation lease recovery; absent, changed, or partial state never triggers a new initialization.", + "compatibilityLevel": "COMPATIBLE", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "none"}], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index 248424f121..b4a323197f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -39,6 +39,7 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; @@ -131,12 +132,11 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep assertThat(first.physicalBindingCount()).isEqualTo(1L); CanonicalGameplayIssuerBootstrapPartitionWork originalWork = partitionWork( - fixture, - fixture.activePartition(), - trustedIncarnation(current.incarnation())); + fixture, fixture.activePartition(), trustedIncarnation(current.incarnation())); var physicalValue = originalWork.memberOperations().getFirst().expectedMemberValue(); var originalReservationRow = - fixture.dsl().fetchOne( + fetchRequired( + fixture.dsl(), "SELECT issuer_coverage_operation_id, issuer_coverage_operation_fence, coverage_fence," + " inventory_snapshot_revision, inventory_revision" + " FROM game_session_canonical_issuer_partition_reservation WHERE reservation_id = ?", @@ -145,41 +145,59 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep .isEqualTo(originalReservationRow.get("issuer_coverage_operation_id", UUID.class)) .isNotEqualTo(physicalValue.anchor().issuerCoverageOperationId()); assertThat(physicalValue.reservation().issuerCoverageOperationFence()) - .isEqualTo(originalReservationRow.get("issuer_coverage_operation_fence", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow + .get("issuer_coverage_operation_fence", BigDecimal.class) + .toBigIntegerExact()); assertThat(physicalValue.reservation().coverageFence()) - .isEqualTo(originalReservationRow.get("coverage_fence", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow.get("coverage_fence", BigDecimal.class).toBigIntegerExact()); assertThat(physicalValue.reservation().inventorySnapshotRevision()) - .isEqualTo(originalReservationRow.get("inventory_snapshot_revision", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow + .get("inventory_snapshot_revision", BigDecimal.class) + .toBigIntegerExact()); assertThat(physicalValue.reservation().inventoryRevision()) - .isEqualTo(originalReservationRow.get("inventory_revision", BigDecimal.class).toBigIntegerExact()); + .isEqualTo( + originalReservationRow.get("inventory_revision", BigDecimal.class).toBigIntegerExact()); assertThat(physicalValue.anchor().issuerCoverageOperationId()) .isEqualTo(first.issuerCoverageOperationId()); assertThat(physicalValue.anchor().operationFence()).isEqualTo(first.operationFence()); assertThat(physicalValue.anchor().coverageFence()).isEqualTo(first.coverageFence()); assertThat(physicalValue.anchor().issuerInventorySnapshotRevision()) .isEqualTo(first.issuerInventorySnapshotRevision()); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") - .get("proof_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("proof_count", Long.class)) .isEqualTo(PARTITION_COUNT.longValueExact()); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") - .get("anchor_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") + .get("anchor_count", Long.class)) .isEqualTo(1L); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS pending_count FROM game_session_canonical_issuer_bootstrap_member_operation" - + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") - .get("pending_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS pending_count FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_status = 'PENDING_PHYSICAL_PROOF'") + .get("pending_count", Long.class)) .isEqualTo((long) fixture.plan().memberWorks().size()); - assertThat(fixture.dsl().fetchOne( - "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("last_issued_coverage_generation", BigDecimal.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("last_issued_coverage_generation", BigDecimal.class)) .isEqualTo(new BigDecimal(first.globalCoverageGeneration())); - assertThat(fixture.dsl().fetchOne( - "SELECT state FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", - ISSUER) - .get("state", String.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT state FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", + ISSUER) + .get("state", String.class)) .isEqualTo("INITIAL_BOOTSTRAP_INTENT"); for (BigInteger partitionId = BigInteger.ZERO; @@ -199,14 +217,17 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep byte[] exactAnchorBeforeCounterAdvance = first.exactAnchorBytes(); String anchorStorageBeforeCounterAdvance = anchorStorageImage(fixture.dsl()); String proofStorageBeforeCounterAdvance = proofStorageImage(fixture.dsl()); - BigInteger laterCoverageGeneration = first.globalCoverageGeneration().add(BigInteger.valueOf(4)); - fixture.dsl().execute( - "UPDATE game_session_canonical_issuer_bootstrap_coverage_counter" - + " SET last_issued_coverage_generation = ?, counter_version = 2" - + " WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = 1", - laterCoverageGeneration, - ISSUER, - first.globalCoverageGeneration()); + BigInteger laterCoverageGeneration = + first.globalCoverageGeneration().add(BigInteger.valueOf(4)); + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_bootstrap_coverage_counter" + + " SET last_issued_coverage_generation = ?, counter_version = 2" + + " WHERE issuer_id = ? AND last_issued_coverage_generation = ? AND counter_version = 1", + laterCoverageGeneration, + ISSUER, + first.globalCoverageGeneration()); assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); assertThat(anchorStorageImage(fixture.dsl())).isEqualTo(anchorStorageBeforeCounterAdvance); assertThat(proofStorageImage(fixture.dsl())).isEqualTo(proofStorageBeforeCounterAdvance); @@ -218,15 +239,19 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep assertThat(replay.exactAnchorBytes()).containsExactly(first.exactAnchorBytes()); assertThat(replay.exactAnchorBytes()).containsExactly(exactAnchorBeforeCounterAdvance); assertThat(replay.globalCoverageGeneration()).isEqualTo(first.globalCoverageGeneration()); - assertThat(fixture.dsl().fetchOne( - "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("counter_version", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("counter_version", Long.class)) .isEqualTo(2L); - assertThat(fixture.dsl().fetchOne( - "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("last_issued_coverage_generation", BigDecimal.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT last_issued_coverage_generation FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("last_issued_coverage_generation", BigDecimal.class)) .isEqualTo(new BigDecimal(laterCoverageGeneration)); assertThat(originalReservationImage(fixture.dsl())).isEqualTo(originalReservationImage); } @@ -239,7 +264,9 @@ void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherG owner(fixture, () -> current) .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); byte[] missingKey = key(fixture, fixture.activePartition()); - administratorCommands.del(missingKey); + byte[][] missingKeyArguments = new byte[1][]; + missingKeyArguments[0] = missingKey; + administratorCommands.del(missingKeyArguments); assertThatThrownBy( () -> @@ -247,15 +274,19 @@ void installedReplayRefusesMissingPartitionWithoutRebuildingOrAllocatingAnotherG .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.type(missingKey)).isEqualTo("none"); - assertThat(fixture.dsl().fetchOne( - "SELECT global_coverage_generation FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", - ISSUER) - .get("global_coverage_generation", BigDecimal.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT global_coverage_generation FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + ISSUER) + .get("global_coverage_generation", BigDecimal.class)) .isEqualTo(new BigDecimal(installed.globalCoverageGeneration())); - assertThat(fixture.dsl().fetchOne( - "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", - ISSUER) - .get("counter_version", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT counter_version FROM game_session_canonical_issuer_bootstrap_coverage_counter WHERE issuer_id = ?", + ISSUER) + .get("counter_version", Long.class)) .isEqualTo(1L); } @@ -265,13 +296,14 @@ void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPoint var sourceIncarnation = stableIncarnation("source-movement"); var changedCheckpoint = checkpointShape(BigInteger.valueOf(8)); AtomicInteger sourceCalls = new AtomicInteger(); - var changedAfterReadback = - () -> - new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - sourceCalls.incrementAndGet() == 5 - ? changedCheckpoint - : sourceFixture.intent().sourceCheckpoint(), - sourceIncarnation); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + changedAfterReadback = + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + sourceCalls.incrementAndGet() == 5 + ? changedCheckpoint + : sourceFixture.intent().sourceCheckpoint(), + sourceIncarnation); assertThatThrownBy( () -> owner(sourceFixture, changedAfterReadback) @@ -285,11 +317,14 @@ void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPoint var initialIncarnation = stableIncarnation("incarnation-movement"); var changedIncarnation = changedIncarnation(initialIncarnation); AtomicInteger incarnationCalls = new AtomicInteger(); - var changedIncarnationAfterReadback = - () -> - new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( - incarnationFixture.intent().sourceCheckpoint(), - incarnationCalls.incrementAndGet() == 5 ? changedIncarnation : initialIncarnation); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + changedIncarnationAfterReadback = + () -> + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + incarnationFixture.intent().sourceCheckpoint(), + incarnationCalls.incrementAndGet() == 5 + ? changedIncarnation + : initialIncarnation); assertThatThrownBy( () -> owner(incarnationFixture, changedIncarnationAfterReadback) @@ -337,15 +372,18 @@ void finitePlanCapacityConflictDoesNotCreateAnyPartitionOrCoverageGeneration() { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("blockers"); assertNoInstalledCoverage(fixture); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") - .get("proof_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") + .get("proof_count", Long.class)) .isZero(); assertThat(administratorCommands.type(key(fixture, BigInteger.ZERO))).isEqualTo("none"); } private void assertPhysicalTupleConflict(boolean wrongNewAnchor) { Fixture fixture = fixture(BigInteger.ONE, PARTITION_CAPACITY, 1); + administratorCommands.del(new byte[][] {key(fixture, BigInteger.ZERO)}); var incarnation = stableIncarnation(wrongNewAnchor ? "wrong-anchor" : "wrong-original"); CanonicalGameplayIssuerBootstrapPartitionWork work = partitionWork(fixture, BigInteger.ZERO, trustedIncarnation(incarnation)); @@ -381,14 +419,12 @@ private void assertPhysicalTupleConflict(boolean wrongNewAnchor) { expected.incarnation()); byte[] changedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(changed); byte[] key = key(fixture, BigInteger.ZERO); + administratorCommands.hset(key, expected.owner().bindingRef().bytes(), changedBytes); administratorCommands.hset( key, - expected.owner().bindingRef().bytes(), - changedBytes); - administratorCommands.hset( - key, - ascii(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( - expected.reservation().reservationId())), + ascii( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + expected.reservation().reservationId())), changedBytes); assertThatThrownBy( @@ -444,7 +480,8 @@ private CanonicalGameplayIssuerBootstrapPartitionRedisOwner partitionRedisOwner( private CanonicalGameplayIssuerBootstrapPartitionWork partitionWork( Fixture fixture, BigInteger partitionId, - CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation incarnation) { + CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation + incarnation) { return new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.dsl()) .preparePartitionWork( fixture.intent().operationId(), @@ -515,15 +552,10 @@ private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState c CanonicalGameplayIssuerMemberV2Codec.sha256(event)); } - private static CanonicalGameplayIssuerMemberV2Value.Incarnation - stableIncarnation(String seed) { + private static CanonicalGameplayIssuerMemberV2Value.Incarnation stableIncarnation(String seed) { String digest = digest(seed.getBytes(StandardCharsets.UTF_8)); return new CanonicalGameplayIssuerMemberV2Value.Incarnation( - "controlled-attestor-" + seed, - digest, - deploymentEvidence(seed, digest), - digest, - digest); + "controlled-attestor-" + seed, digest, deploymentEvidence(seed, digest), digest, digest); } private static CanonicalGameplayIssuerBootstrapMemberOperationRepository.TrustedStableIncarnation @@ -606,13 +638,14 @@ private static CanonicalGameplayBindingIdentity identityInPartition( identity(partitions, capacity, "coverage-active-" + seed + "-" + candidate); if (identity.bindingRef().partitionId(partitions).equals(partitionId)) return identity; } - throw new IllegalStateException("Could not create a second reservation in the target partition"); + throw new IllegalStateException( + "Could not create a second reservation in the target partition"); } - private static void seedActiveSource( - DSLContext dsl, CanonicalGameplayBindingIdentity identity) { + private static void seedActiveSource(DSLContext dsl, CanonicalGameplayBindingIdentity identity) { byte[] bindingRef = identity.bindingRef().bytes(); - BigInteger partitionId = identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); + BigInteger partitionId = + identity.bindingRef().partitionId(identity.issuerIndexPartitionCount()); UUID accountIndexFence = UUID.randomUUID(); UUID reservationId = UUID.randomUUID(); UUID transitionId = UUID.randomUUID(); @@ -709,14 +742,16 @@ private static void seedActiveSource( } private static String originalReservationImage(DSLContext dsl) { - return dsl.fetchOne( + return fetchRequired( + dsl, "SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY reservation_id), '[]'::jsonb)::text AS image " + "FROM game_session_canonical_issuer_partition_reservation r") .get("image", String.class); } private static String anchorStorageImage(DSLContext dsl) { - return dsl.fetchOne( + return fetchRequired( + dsl, "SELECT encode(exact_anchor_bytes, 'base64') || ':' || exact_anchor_digest || ':'" + " || global_coverage_generation::text AS image" + " FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", @@ -725,7 +760,8 @@ private static String anchorStorageImage(DSLContext dsl) { } private static String proofStorageImage(DSLContext dsl) { - return dsl.fetchOne( + return fetchRequired( + dsl, "SELECT coalesce(string_agg(partition_id::text || ':'" + " || encode(exact_metadata_bytes, 'base64') || ':'" + " || encode(exact_physical_field_set_bytes, 'base64') || ':'" @@ -735,23 +771,33 @@ private static String proofStorageImage(DSLContext dsl) { } private static long fixtureProofCount(Fixture fixture) { - return fixture.dsl() - .fetchOne( + return fetchRequired( + fixture.dsl(), "SELECT count(*) AS proof_count FROM game_session_canonical_issuer_bootstrap_partition_proof") .get("proof_count", Long.class); } private static void assertNoInstalledCoverage(Fixture fixture) { - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") - .get("anchor_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS anchor_count FROM game_session_canonical_issuer_installed_anchor") + .get("anchor_count", Long.class)) .isZero(); - assertThat(fixture.dsl().fetchOne( - "SELECT count(*) AS counter_count FROM game_session_canonical_issuer_bootstrap_coverage_counter") - .get("counter_count", Long.class)) + assertThat( + fetchRequired( + fixture.dsl(), + "SELECT count(*) AS counter_count FROM game_session_canonical_issuer_bootstrap_coverage_counter") + .get("counter_count", Long.class)) .isZero(); } + private static Record fetchRequired(DSLContext dsl, String sql, Object... bindings) { + Record record = dsl.fetchOne(sql, bindings); + if (record == null) throw new IllegalStateException("Required focused query returned no row"); + return record; + } + private static byte[] key(Fixture fixture, BigInteger partitionId) { return CanonicalGameplayIssuerRedisKeys.forPartition( fixture.intent().layoutDescriptor(), partitionId) @@ -777,13 +823,23 @@ private void establishActualLegacyDisposition(DSLContext dsl) { "controlled-redis-volume-uid"); var fencedCohort = new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { - @Override public UUID cohortId() { return cohortId; } - @Override public UUID legacyWriterFence() { return writerFence; } - @Override public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { return storageIdentity; } - @Override public void requireStillFenced( - CanonicalGameplayLegacyMigrationStorageIdentity expected) { + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { if (!storageIdentity.equals(expected)) { throw new IllegalStateException("Controlled test storage identity changed"); } @@ -804,17 +860,22 @@ private void establishActualLegacyDisposition(DSLContext dsl) { Family.DURABLE_EFFECT), List.of()), new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { - @Override public void rebuildExact( + @Override + public void rebuildExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, CanonicalGameplayLegacyMigrationSourceSnapshot source, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); assertThat(canonical.reservations()).isEmpty(); } - @Override public CanonicalGameplayLegacyMigrationReadback readBackExact( + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, - net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot canonical) { assertThat(canonical.bindings()).isEmpty(); return new CanonicalGameplayLegacyMigrationReadback( @@ -865,7 +926,8 @@ private void dropSchema(String schema) { DSL.using(connection, SQLDialect.POSTGRES) .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); } catch (SQLException failure) { - throw new IllegalStateException("Could not drop the owned issuer coverage test schema", failure); + throw new IllegalStateException( + "Could not drop the owned issuer coverage test schema", failure); } } @@ -904,7 +966,9 @@ private record Fixture( CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint currentAccountCheckpoint, CanonicalGameplayIssuerPartitionBuildPlan plan) { - DSLContext dsl() { return schema.dsl(); } + DSLContext dsl() { + return schema.dsl(); + } } private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java new file mode 100644 index 0000000000..8edd15cc9d --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java @@ -0,0 +1,523 @@ +package net.firedevops.firemud.gamesession.repository; + +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.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +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.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +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.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.TestContainerImages; +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; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Controlled Redis and test-PKI proof; the source peer is not a production Entity placement claim. */ +@Testcontainers(disabledWithoutDocker = true) +@Timeout(60) +@SuppressWarnings("resource") +class CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String PASSWORD = UUID.randomUUID().toString(); + private static final String NAMESPACE = "game-session-test"; + private static final String CLIENT_PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final String ENTITY_PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service"; + private static final int PORT = 6379; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID CANONICAL_REGION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REGION_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID NAMESPACE_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID CAPTURE_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID SESSION_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final String GRAPH_DIGEST = "a".repeat(64); + private static final String PREPARATION_DIGEST = "sha256:" + "b".repeat(64); + private static final Instant NOW = Instant.parse("2026-10-26T00:00:00Z"); + + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(PORT); + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Region binding bridge test CA", + new LoopbackMtlsTestPki.IdentitySpec("client", CLIENT_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec("entity-server", ENTITY_PEER, true)); + } + + @Test + void sameGrantAppliesAndReadsBackExactTypedEntityBindingThenPreservesForeignState() + throws Exception { + try (RedisFixture redis = RedisFixture.open()) { + var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var source = source(); + RuntimeIdentity runtimeIdentity = runtimeIdentity("instance-a"); + seedMeta(redis.admin(), source, "1"); + var grant = owner.acquire(source, 1L, Duration.ofSeconds(30), runtimeIdentity); + var status = status(source, grant, runtimeIdentity); + var actor = readActualEntityReference(); + String key = + CanonicalGameplayRegionRedisKeys.sessionBinding( + TENANT_ID, GAME_INSTANCE_ID, REGION_ID, actor.runtimeEntityId().value()); + String meta = CanonicalGameplayRegionRedisKeys.meta(TENANT_ID, GAME_INSTANCE_ID, REGION_ID); + var absent = + owner.probeSessionBinding( + grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); + assertThat(absent.state()) + .isEqualTo(CanonicalGameplayRegionLeaseRedisOwner.PreimageState.ABSENT); + owner.applySessionBinding(grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); + var exact = + owner.probeSessionBinding( + grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); + assertThat(exact.state()) + .isEqualTo(CanonicalGameplayRegionLeaseRedisOwner.PreimageState.EXACT); + var readback = + owner.readBackSessionBinding( + grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); + assertThat(readback.runtimeEntityId()).isEqualTo(actor.runtimeEntityId()); + assertThat(readback.sessionId()).isEqualTo(SESSION_ID.toString()); + assertThat(readback.bindingGeneration()).isEqualTo(java.math.BigInteger.ONE); + assertThat(redis.admin().hget(ascii(key), ascii("session_id"))) + .containsExactly(ascii(SESSION_ID.toString())); + assertThat(redis.admin().hget(ascii(key), ascii("binding_generation"))) + .containsExactly(ascii("1")); + + byte[] foreignSession = ascii("88888888-8888-4888-8888-888888888888"); + redis.admin().hset( + ascii(key), + java.util.Map.of( + ascii("session_id"), foreignSession, + ascii("binding_generation"), ascii("2"))); + assertThatThrownBy( + () -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + owner.applySessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().hget(ascii(key), ascii("session_id"))).containsExactly(foreignSession); + assertThat(redis.admin().hget(ascii(key), ascii("binding_generation"))) + .containsExactly(ascii("2")); + } + } + + @Test + void wrongOrMissingMetaAndExpiredLeaseFailWithoutCreatingBinding() throws Exception { + try (RedisFixture redis = RedisFixture.open()) { + var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var source = source(); + RuntimeIdentity runtimeIdentity = runtimeIdentity("instance-a"); + seedMeta(redis.admin(), source, "1"); + var grant = owner.acquire(source, 1L, Duration.ofSeconds(30), runtimeIdentity); + var status = status(source, grant, runtimeIdentity); + var actor = readActualEntityReference(); + String key = + CanonicalGameplayRegionRedisKeys.sessionBinding( + TENANT_ID, GAME_INSTANCE_ID, REGION_ID, actor.runtimeEntityId().value()); + String meta = CanonicalGameplayRegionRedisKeys.meta(TENANT_ID, GAME_INSTANCE_ID, REGION_ID); + redis.admin().del(ascii(meta)); + + assertThatThrownBy( + () -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); + + redis.admin().hset(ascii(meta), ascii("region_epoch"), ascii("2")); + assertThatThrownBy( + () -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); + + redis.admin().hset(ascii(meta), ascii("region_epoch"), ascii("1")); + redis.admin().pexpire(ascii(grant.key()), 0L); + assertThatThrownBy( + () -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); + } + } + + @Test + void bridgesTickZeroButRejectsExpiringMetaBeforeReadback() throws Exception { + try (RedisFixture redis = RedisFixture.open()) { + var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var source = source(); + RuntimeIdentity identity = runtimeIdentity("tick-zero"); + seedMeta(redis.admin(), source, "1"); + String meta = CanonicalGameplayRegionRedisKeys.meta(TENANT_ID, GAME_INSTANCE_ID, REGION_ID); + redis.admin().hset( + ascii(meta), + ascii("current_tick_id"), + ascii("0"), + ascii("current_tick_state"), + ascii("STAGED")); + var grant = owner.acquire(source, 1L, Duration.ofSeconds(30), identity); + var status = status(source, grant, identity); + var actor = readActualEntityReference(); + + owner.applySessionBinding( + grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); + assertThat(redis.admin().hget( + ascii(CanonicalGameplayRegionRedisKeys.sessionBinding( + TENANT_ID, GAME_INSTANCE_ID, REGION_ID, actor.runtimeEntityId().value())), + ascii("session_id"))) + .containsExactly(ascii(SESSION_ID.toString())); + + assertThat(redis.admin().pexpire(ascii(meta), 60_000L)).isTrue(); + assertThatThrownBy( + () -> + owner.readBackSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) + .isInstanceOf(IllegalStateException.class); + } + } + + private static CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference + readActualEntityReference() throws Exception { + var request = entityRequest(); + var service = + new CanonicalPreseededActorAssignmentServiceGrpc + .CanonicalPreseededActorAssignmentServiceImplBase() { + @Override + public void readPreseededActorRuntimeReference( + ReadPreseededActorRuntimeReferenceRequest request, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null || !CLIENT_PEER.equals(peer.uri())) { + observer.onError(io.grpc.Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + observer.onNext(entityResponse(request)); + observer.onCompleted(); + } + }; + Server server = server(service); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("localhost:" + server.getPort()); + try (var client = + new CanonicalPreseededActorRuntimeReferenceClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE)) { + client.init(); + return client.read(request); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static Server server( + CanonicalPreseededActorAssignmentServiceGrpc.CanonicalPreseededActorAssignmentServiceImplBase + service) + throws Exception { + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(pki.identity("entity-server")), + 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 entityRequest() { + return ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid("99999999-9999-4999-8999-999999999999") + .setCanonicalAccountUuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") + .setExpectedTarget( + PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid(TENANT_ID.toString()) + .setRealmUuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb") + .setWorldSlug("outer-reach") + .setRealmSlug("green-march") + .setGameInstanceId(GAME_INSTANCE_ID.toString()) + .setCatalogRevision(7L) + .setCanonicalVersionUuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc") + .setFrozenPolicyDigest("d".repeat(64)) + .setPlayableStateNamespaceUuid(NAMESPACE_ID.toString()) + .setPublishedReleaseBundleRef("release:bounded/v1") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .setCharacterUuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd") + .setIntentDigest("e".repeat(64)) + .build(); + } + + private static ReadPreseededActorRuntimeReferenceResponse entityResponse( + ReadPreseededActorRuntimeReferenceRequest request) { + return ReadPreseededActorRuntimeReferenceResponse.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(request.getAssignmentUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setCharacterUuid(request.getCharacterUuid()) + .setIntentDigest(request.getIntentDigest()) + .setExpectedTarget(request.getExpectedTarget()) + .setPublishedOwnerProofDigest("f".repeat(64)) + .setRuntimeEntityId(7301L) + .setProjectionGeneration(1) + .setProjectionFence(1) + .setCorePayload( + PreseededActorAssignmentCorePayload.newBuilder() + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .setDisplayName("Pilot One")) + .build(); + } + + private static CanonicalGameplayRegionRuntimeStatusRepository.Source source() { + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.fromString("10101010-1010-4010-8010-101010101010"), + NAMESPACE, + TENANT_ID, + "test-world", + GAME_INSTANCE_ID, + NAMESPACE_ID, + "SHARED", + true, + "bridge-test-request", + UUID.fromString("20202020-2020-4020-8020-202020202020"), + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new CanonicalGameplayRegionRuntimeStatusRepository.Source( + TENANT_ID, + GAME_INSTANCE_ID, + CANONICAL_REGION_ID, + REGION_ID, + 4L, + 9L, + lifecycleRequest, + CAPTURE_ID, + GRAPH_DIGEST, + PREPARATION_DIGEST); + } + + private static CanonicalGameplayRegionRuntimeStatus status( + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant, + RuntimeIdentity identity) { + return new CanonicalGameplayRegionRuntimeStatus( + source.tenantId(), + source.gameInstanceId(), + source.canonicalRegionId(), + source.regionId(), + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId()), + source.lifecycleEpoch(), + source.lifecycleRowVersion(), + source.lifecycleRequest(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + 1L, + java.math.BigInteger.ONE, + grant.tokenCorrelation(), + identity.service(), + identity.serviceInstanceId(), + false, + null, + -1L, + NOW); + } + + private static RuntimeIdentity runtimeIdentity(String instanceId) { + return new RuntimeIdentity( + "game-session-service", instanceId, "localhost", NOW, "test", "test-sha", "test-image"); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static void seedMeta( + RedisCommands admin, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + String epoch) { + admin.hset( + ascii(CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())), + ascii("region_epoch"), + ascii(epoch), + ascii("current_tick_id"), + ascii("-1"), + ascii("current_tick_state"), + ascii("APPLIED")); + } + + private static final class RedisFixture implements AutoCloseable { + private final RedisClient administrator; + private final RedisClient ownerClient; + private final StatefulRedisConnection adminConnection; + private final RedisCommands admin; + private final RedisScriptCatalog catalog; + + private RedisFixture( + RedisClient administrator, + RedisClient ownerClient, + StatefulRedisConnection adminConnection, + RedisCommands admin, + RedisScriptCatalog catalog) { + this.administrator = administrator; + this.ownerClient = ownerClient; + this.adminConnection = adminConnection; + this.admin = admin; + this.catalog = catalog; + } + + static RedisFixture open() { + RedisClient administrator = createClient(null, null); + StatefulRedisConnection adminConnection = + administrator.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + admin.flushdb(); + admin.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern("tick-executor-lease:*") + .keyPattern("tick:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRE) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HSET)); + RedisClient ownerClient = createClient(PRINCIPAL, PASSWORD); + RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + List.of( + new CanonicalGameplayRegionLeaseRedisScriptContribution(), + new CanonicalGameplayRegionBindingBridgeRedisScriptContribution())); + return new RedisFixture(administrator, ownerClient, adminConnection, admin, catalog); + } + + private static RedisClient createClient(String username, String password) { + RedisURI.Builder builder = + RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(PORT)) + .withTimeout(Duration.ofSeconds(3)); + if (username != null) builder.withAuthentication(username, password); + RedisClient client = RedisClient.create(builder.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + RedisClient ownerClient() { + return ownerClient; + } + + RedisCommands admin() { + return admin; + } + + RedisScriptCatalog catalog() { + return catalog; + } + + @Override + public void close() { + adminConnection.close(); + ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index e1a3a42ac0..c39e3d630d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -100,11 +100,14 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws var redisOwner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); WorldFixture world = WorldFixture.open(); + ControlledStableIncarnationSource incarnationSource = + new ControlledStableIncarnationSource(); var bindingEvidence = provisionalEvidence(world.request()); var bindingInventory = mock(CanonicalGameplayBindingInventoryRepository.class); when(bindingInventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(bindingEvidence); - var firstOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-a"); + var firstOwner = + owner(bindingInventory, statusRepository, redisOwner, world, "instance-a", incarnationSource); var qualifiedSource = source(world.originalEvidence()); byte[] redisKey = ascii( @@ -112,6 +115,11 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws qualifiedSource.tenantId(), qualifiedSource.gameInstanceId(), qualifiedSource.regionId())); + String initialMetaKey = + CanonicalGameplayRegionRedisKeys.meta( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId()); try { TransactionSynchronizationManager.initSynchronization(); @@ -132,7 +140,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws when(wrongTargetInventory.readProvisionalCasEvidence(TRANSITION_ID)) .thenReturn(wrongTargetEvidence); var wrongTargetOwner = - owner(wrongTargetInventory, statusRepository, redisOwner, world, "wrong-target"); + owner(wrongTargetInventory, statusRepository, redisOwner, world, "wrong-target", incarnationSource); assertThatThrownBy( () -> wrongTargetOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); @@ -145,12 +153,28 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws when(wrongEpochInventory.readProvisionalCasEvidence(TRANSITION_ID)) .thenReturn(wrongEpochEvidence); var wrongEpochOwner = - owner(wrongEpochInventory, statusRepository, redisOwner, world, "wrong-epoch"); + owner(wrongEpochInventory, statusRepository, redisOwner, world, "wrong-epoch", incarnationSource); assertThatThrownBy(() -> wrongEpochOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().type(redisKey)).isEqualTo("none"); assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + var unavailableIncarnationOwner = + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "unavailable-incarnation", + CanonicalGameplayRegionIncarnationSource.unavailable()); + assertThatThrownBy( + () -> + unavailableIncarnationOwner.installForTransition( + TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().type(redisKey)).isEqualTo("none"); + assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + try { TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())) @@ -161,30 +185,119 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(redis.admin().type(redisKey)).isEqualTo("none"); assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + world.setAfterRead(2, incarnationSource::changeRecoveryEvidence); + assertThatThrownBy( + () -> firstOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + Record retainedPreparation = + dsl.fetchOne( + "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", + TRANSITION_ID); + assertThat(retainedPreparation).isNotNull(); + assertThat(retainedPreparation.get("phase", String.class)).isEqualTo("REDIS_INITIALIZED"); + UUID initialTimelineOperationId = + retainedPreparation.get("initialization_operation_id", UUID.class); + String initialTimelineSourceDigest = + retainedPreparation.get("preparation_digest", String.class); + assertThat(redis.admin().hlen(ascii(initialMetaKey))).isEqualTo(5L); + assertThat(redis.admin().pttl(ascii(initialMetaKey))).isEqualTo(-1L); + world.resetReads(); + incarnationSource.restoreRecoveryEvidence(); + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); + var firstInstallation = firstOwner.installForTransition(TRANSITION_ID, world.request()); var firstStatus = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(firstStatus.regionEpoch()).isEqualTo(1L); assertThat(firstStatus.lifecycleEpoch()).isEqualTo(7L); assertThat(firstStatus.lastCommittedTickId()).isEqualTo(-1L); + assertThat(redis.admin().hlen(ascii(initialMetaKey))).isEqualTo(5L); + assertThat(redis.admin().pttl(ascii(initialMetaKey))).isEqualTo(-1L); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("region_epoch"))) + .containsExactly(ascii("1")); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_id"))) + .containsExactly(ascii("-1")); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_state"))) + .containsExactly(ascii("APPLIED")); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("first_timeline_operation_id"))) + .containsExactly(ascii(initialTimelineOperationId.toString())); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("first_timeline_source_digest"))) + .containsExactly(ascii(initialTimelineSourceDigest)); + var currentIncarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(qualifiedSource)); + Record preparationRow = + dsl.fetchOne( + "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", + TRANSITION_ID); + assertThat(preparationRow).isNotNull(); + assertThat(preparationRow.get("phase", String.class)).isEqualTo("INSTALLED"); + assertThat(preparationRow.get("initialization_operation_id", UUID.class)) + .isEqualTo(initialTimelineOperationId); + assertThat(preparationRow.get("preparation_digest", String.class)) + .isEqualTo(initialTimelineSourceDigest); + assertThat(preparationRow.get("stable_incarnation_scope_bytes", byte[].class)) + .containsExactly(currentIncarnation.scopeBytes()); + assertThat(preparationRow.get("stable_incarnation_source_bytes", byte[].class)) + .containsExactly(currentIncarnation.stableCanonicalBytes()); + assertThat(preparationRow.get("stable_incarnation_qualification_bytes", byte[].class)) + .containsExactly( + currentIncarnation.timelineInitializationQualification().canonicalBytes()); Long sequenceAfterInstall = fenceSequenceValue(dsl); + assertThat( + statusRepository.installOwner( + qualifiedSource, + firstStatus.regionEpoch(), + firstStatus, + firstStatus.leaseTokenCorrelation(), + firstStatus.ownerService(), + firstStatus.ownerInstanceId(), + NOW.plusSeconds(1))) + .isEqualTo(firstStatus); + assertThat(fenceSequenceValue(dsl)).isEqualTo(sequenceAfterInstall); firstOwner.revalidateBeforeBridge(firstInstallation); firstOwner.revalidateBeforeBridge(firstInstallation); assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); assertThat(fenceSequenceValue(dsl)).isEqualTo(sequenceAfterInstall); + assertThat(redis.admin().pexpire(ascii(initialMetaKey), 60_000L)).isTrue(); + assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(firstInstallation)) + .isInstanceOf(IllegalStateException.class); + assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); + assertThat(redis.admin().persist(ascii(initialMetaKey))).isTrue(); assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(firstInstallation)) .isInstanceOf(IllegalStateException.class); assertThat(statusRepository.find(qualifiedSource)).contains(firstStatus); - var secondOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-b"); + dsl.execute( + "UPDATE game_session_region_runtime_status" + + " SET last_committed_tick_batch_id = 'batch-0', last_committed_tick_id = 0" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId()); + redis.admin().hset( + ascii(CanonicalGameplayRegionRedisKeys.meta( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId())), + ascii("current_tick_id"), + ascii("0"), + ascii("current_tick_state"), + ascii("APPLIED"), + ascii("current_tick_terminal_at_ms"), + ascii("1792972800000")); + var secondOwner = + owner(bindingInventory, statusRepository, redisOwner, world, "instance-b", incarnationSource); secondOwner.installForTransition(TRANSITION_ID, world.request()); var secondStatus = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(secondStatus.executorFence()).isGreaterThan(firstStatus.executorFence()); assertThat(secondStatus.regionEpoch()).isEqualTo(firstStatus.regionEpoch()); - assertThat(secondStatus.lastCommittedTickId()).isEqualTo(-1L); + assertThat(secondStatus.lastCommittedTickId()).isZero(); + assertThat(secondStatus.lastCommittedTickBatchId()).isEqualTo("batch-0"); assertThat(secondStatus.ownerInstanceId()).isEqualTo("instance-b"); assertThatThrownBy(() -> firstOwner.revalidateBeforeBridge(firstInstallation)) .isInstanceOf(IllegalStateException.class); @@ -197,10 +310,22 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws qualifiedSource.tenantId(), qualifiedSource.gameInstanceId(), qualifiedSource.regionId()); + redis.admin().hset( + ascii(CanonicalGameplayRegionRedisKeys.meta( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId())), + ascii("current_tick_id"), + ascii("8"), + ascii("current_tick_state"), + ascii("APPLIED"), + ascii("current_tick_terminal_at_ms"), + ascii("1792972800000")); var progressed = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); - var thirdOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-c"); + var thirdOwner = + owner(bindingInventory, statusRepository, redisOwner, world, "instance-c", incarnationSource); var thirdInstallation = thirdOwner.installForTransition(TRANSITION_ID, world.request()); var thirdStatus = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(thirdStatus.executorFence()).isGreaterThan(progressed.executorFence()); @@ -210,10 +335,32 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(thirdStatus.ownerInstanceId()).isEqualTo("instance-c"); assertThat(thirdInstallation).isNotNull(); + byte[] liveLeaseBeforeIncarnationChange = redis.admin().get(redisKey); + Long fenceBeforeIncarnationChange = fenceSequenceValue(dsl); + incarnationSource.changeStorageGeneration("storage-generation-2"); + var changedIncarnationOwner = + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "changed-incarnation", + incarnationSource); + assertThatThrownBy( + () -> + changedIncarnationOwner.installForTransition( + TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().get(redisKey)).containsExactly(liveLeaseBeforeIncarnationChange); + assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); + assertThat(fenceSequenceValue(dsl)).isEqualTo(fenceBeforeIncarnationChange); + incarnationSource.restoreStorageGeneration(); + assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); WorldCanonicalInstanceLifecycleEvidence changed = changedEvidence(world.originalEvidence()); world.replaceOnRead(2, changed); - var fourthOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-d"); + var fourthOwner = + owner(bindingInventory, statusRepository, redisOwner, world, "instance-d", incarnationSource); assertThatThrownBy(() -> fourthOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); @@ -221,7 +368,8 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); world.resetReads(); world.replaceOnRead(3, changed); - var fifthOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-e"); + var fifthOwner = + owner(bindingInventory, statusRepository, redisOwner, world, "instance-e", incarnationSource); assertThatThrownBy(() -> fifthOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); var installedBeforeChangedSourceGate = statusRepository.find(qualifiedSource).orElseThrow(); @@ -233,7 +381,8 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws world.resetReads(); world.setAfterRead(2, POSTGRES::stop); - var sixthOwner = owner(bindingInventory, statusRepository, redisOwner, world, "instance-f"); + var sixthOwner = + owner(bindingInventory, statusRepository, redisOwner, world, "instance-f", incarnationSource); assertThatThrownBy(() -> sixthOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(RuntimeException.class); assertThat(redis.admin().type(redisKey)).isEqualTo("string"); @@ -250,16 +399,95 @@ private static DriverManagerDataSource dataSource() { return dataSource; } + /** Controlled current-incarnation fixture; it does not attest production Redis custody. */ + private static CanonicalGameplayRegionIncarnationSource.StableEvidence stableIncarnation( + CanonicalGameplayRegionIncarnationSource.RegionScope scope, String storageGeneration) { + return stableIncarnation( + scope, storageGeneration, "e".repeat(64), "f".repeat(64), "1".repeat(64)); + } + + private static CanonicalGameplayRegionIncarnationSource.StableEvidence stableIncarnation( + CanonicalGameplayRegionIncarnationSource.RegionScope scope, + String storageGeneration, + String profileEvidenceDigest, + String recoveryEvidenceDigest, + String unfinishedWorkEvidenceDigest) { + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-deployment", + "deployment-generation-1", + List.of("node-a"), + "redis-build-1", + "script-registry-v1", + "a".repeat(64), + "READY", + "boot-1", + "startup-1", + storageGeneration, + "aof-1"); + return CanonicalGameplayRegionIncarnationSource.StableEvidence.fromCurrentSource( + scope, + "controlled-region-attestor", + "b".repeat(64), + deployment, + "c".repeat(64), + "d".repeat(64), + true, + "controlled-non-reset-profile-v1", + profileEvidenceDigest, + true, + recoveryEvidenceDigest, + true, + unfinishedWorkEvidenceDigest); + } + + private static final class ControlledStableIncarnationSource + implements CanonicalGameplayRegionIncarnationSource { + private CanonicalGameplayRegionIncarnationSource.StableEvidence current; + + @Override + public synchronized CanonicalGameplayRegionIncarnationSource.StableEvidence readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope scope) { + if (current == null) current = stableIncarnation(scope, "storage-generation-1"); + if (!current.scope().equals(scope)) throw new IllegalStateException("Controlled scope changed"); + return current; + } + + synchronized void changeStorageGeneration(String value) { + current = stableIncarnation(current.scope(), value); + } + + synchronized void restoreStorageGeneration() { + current = stableIncarnation(current.scope(), "storage-generation-1"); + } + + synchronized void changeRecoveryEvidence() { + current = + stableIncarnation( + current.scope(), + "storage-generation-1", + "e".repeat(64), + "0".repeat(64), + "1".repeat(64)); + } + + synchronized void restoreRecoveryEvidence() { + current = stableIncarnation(current.scope(), "storage-generation-1"); + } + } + private static CanonicalGameplayRegionLeaseOwner owner( CanonicalGameplayBindingInventoryRepository bindingInventory, CanonicalGameplayRegionRuntimeStatusRepository statusRepository, CanonicalGameplayRegionLeaseRedisOwner redisOwner, WorldFixture world, - String instanceId) { + String instanceId, + CanonicalGameplayRegionIncarnationSource incarnationSource) { return new CanonicalGameplayRegionLeaseOwner( bindingInventory, statusRepository, redisOwner, + incarnationSource, world.resolver(), new RuntimeIdentity( "game-session-service", @@ -540,6 +768,7 @@ static RedisFixture open() { .on() .addPassword(PASSWORD) .keyPattern("tick-executor-lease:*") + .keyPattern("tick:*") .addCommand(CommandType.HELLO) .addCommand(CommandType.PING) .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) @@ -547,6 +776,9 @@ static RedisFixture open() { .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) .addCommand(CommandType.EVALSHA) .addCommand(CommandType.TYPE) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HSET) + .addCommand(CommandType.HLEN) .addCommand(CommandType.PTTL) .addCommand(CommandType.GET) .addCommand(CommandType.SET) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java index 90f4d3ba9a..9974144749 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java @@ -60,6 +60,7 @@ void exactOpaqueLeaseGrantIsScopedRenewableAndFailsClosedAfterExpiry() { CanonicalGameplayRegionRedisKeys.lease( TENANT_ID, GAME_INSTANCE_ID_A, OPERATIONAL_REGION_ID)))) .isEqualTo("none"); + seedMeta(redis.admin(), firstSource); var firstGrant = owner.acquire(firstSource, 7L, Duration.ofSeconds(10), firstIdentity); byte[] firstKey = ascii(firstGrant.key()); byte[] firstValue = redis.admin().get(firstKey); @@ -77,8 +78,10 @@ void exactOpaqueLeaseGrantIsScopedRenewableAndFailsClosedAfterExpiry() { .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().get(firstKey)).containsExactly(firstValue); + var secondGameSource = source(GAME_INSTANCE_ID_B); + seedMeta(redis.admin(), secondGameSource); var secondGameGrant = - owner.acquire(source(GAME_INSTANCE_ID_B), 7L, Duration.ofSeconds(10), firstIdentity); + owner.acquire(secondGameSource, 7L, Duration.ofSeconds(10), firstIdentity); assertThat(secondGameGrant.key()).isNotEqualTo(firstGrant.key()); owner.requireCurrent(secondGameGrant); @@ -92,6 +95,37 @@ void exactOpaqueLeaseGrantIsScopedRenewableAndFailsClosedAfterExpiry() { } } + @Test + void acceptsTickZeroAndRejectsExpiringTimelineMetadata() { + try (RedisFixture redis = RedisFixture.open()) { + var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var source = source(GAME_INSTANCE_ID_A); + String metaKey = + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId()); + seedMeta(redis.admin(), source); + redis.admin().hset( + ascii(metaKey), + ascii("current_tick_id"), + ascii("0"), + ascii("current_tick_state"), + ascii("STAGED")); + + var grant = owner.acquire(source, 7L, Duration.ofSeconds(10), identity("tick-zero")); + owner.requireCurrent(grant); + owner.renew(grant, Duration.ofSeconds(10)); + + assertThat(redis.admin().pexpire(ascii(metaKey), 60_000L)).isTrue(); + assertThatThrownBy(() -> owner.requireCurrent(grant)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> owner.renew(grant, Duration.ofSeconds(10))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> owner.acquire(source, 7L, Duration.ofSeconds(10), identity("after-meta-ttl"))) + .isInstanceOf(IllegalStateException.class); + } + } + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final UUID GAME_INSTANCE_ID_A = UUID.fromString("22222222-2222-4222-8222-222222222222"); @@ -147,6 +181,20 @@ private static byte[] ascii(String value) { return value.getBytes(StandardCharsets.US_ASCII); } + private static void seedMeta( + RedisCommands admin, + CanonicalGameplayRegionRuntimeStatusRepository.Source source) { + admin.hset( + ascii(CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())), + ascii("region_epoch"), + ascii("7"), + ascii("current_tick_id"), + ascii("-1"), + ascii("current_tick_state"), + ascii("APPLIED")); + } + private static final class RedisFixture implements AutoCloseable { private final RedisClient administrator; private final RedisClient ownerClient; @@ -180,6 +228,7 @@ static RedisFixture open() { .on() .addPassword(PASSWORD) .keyPattern("tick-executor-lease:*") + .keyPattern("tick:*") .addCommand(CommandType.HELLO) .addCommand(CommandType.PING) .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) @@ -187,6 +236,7 @@ static RedisFixture open() { .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) .addCommand(CommandType.EVALSHA) .addCommand(CommandType.TYPE) + .addCommand(CommandType.HGET) .addCommand(CommandType.PTTL) .addCommand(CommandType.GET) .addCommand(CommandType.SET) From 2e9ea1fe20afbc02a976c9ae79de5e1634b2fd9f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:09:52 +1300 Subject: [PATCH 04/36] Repair region owner compilation and preserve atomic Redis fixtures --- ...GameplayBindingRegionBridgeObligation.java | 5 +- ...calGameplayBindingInventoryRepository.java | 105 ++++++++------- ...nicalGameplayRegionBindingBridgeOwner.java | 24 ++-- ...icalGameplayRegionBindingBridgeProofs.java | 6 +- ...onicalGameplayRegionIncarnationSource.java | 43 +++--- .../CanonicalGameplayRegionLeaseOwner.java | 21 ++- ...anonicalGameplayRegionLeaseRedisOwner.java | 95 +++++++------ .../CanonicalGameplayRegionRedisKeys.java | 3 +- ...GameplayRegionRuntimeStatusRepository.java | 38 +++--- ...nBindingBridgeRedisScriptContribution.java | 3 +- ...layRegionLeaseRedisScriptContribution.java | 3 +- ...ical_region_session_binding_bridge_ack.sql | 2 + ...indingBridgeRedisOwnerIntegrationTest.java | 82 ++++++++---- ...meplayRegionLeaseOwnerIntegrationTest.java | 126 ++++++++++++------ ...yRegionLeaseRedisOwnerIntegrationTest.java | 28 ++-- 15 files changed, 342 insertions(+), 242 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java index ee68ab1a9d..f62d513b93 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java @@ -4,7 +4,9 @@ import java.util.Objects; import java.util.UUID; -/** Durable region bridge obligation projection; a private repository receipt carries ACK authority. */ +/** + * Durable region bridge obligation projection; a private repository receipt carries ACK authority. + */ public record CanonicalGameplayBindingRegionBridgeObligation( UUID transitionId, CanonicalGameplayBindingRef bindingRef, @@ -87,6 +89,7 @@ public CanonicalGameplayBindingRegionBridgeObligation( null, null); } + public CanonicalGameplayBindingRegionBridgeObligation { requireNonNil(transitionId, "transitionId"); Objects.requireNonNull(bindingRef, "bindingRef"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 2156a5135e..f6723e77ef 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -2,8 +2,8 @@ import java.math.BigDecimal; import java.math.BigInteger; -import java.time.OffsetDateTime; import java.time.Instant; +import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; @@ -12,10 +12,6 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; -import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; -import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; -import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; -import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; @@ -35,9 +31,13 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.impl.DSL; @@ -338,19 +338,20 @@ CanonicalGameplayBindingRegionBridgeObligation prepareRegionBridge( existing.leaseTokenCorrelation(), ownerStatus.leaseTokenCorrelation()); if (sameGrant) return existing; return rewritePreparedBridgeForCurrentGrant( - transaction, currentRevision, currentEvidence, regionRow, existing, inputs, ownerStatus); + transaction, + currentRevision, + currentEvidence, + regionRow, + existing, + inputs, + ownerStatus); } if (preimage.state() != CanonicalGameplayRegionLeaseRedisOwner.PreimageState.ABSENT) { throw conflict("First region bridge operation requires a proven absent Redis preimage"); } UUID operationId = UUID.randomUUID(); return writePreparedBridge( - transaction, - currentRevision, - currentEvidence, - inputs, - ownerStatus, - operationId); + transaction, currentRevision, currentEvidence, inputs, ownerStatus, operationId); }); } @@ -378,8 +379,7 @@ RegionBridgeAcknowledgement acknowledgeRegionBridge( if (!matchesPreparedOperation(prepared, inputs) || !readback.runtimeEntityId().equals(runtimeReference.runtimeEntityId()) || !readback.sessionId().equals(expectedEvidence.candidate().identity().sessionId()) - || !readback.bindingGeneration() - .equals(expectedEvidence.candidate().bindingGeneration()) + || !readback.bindingGeneration().equals(expectedEvidence.candidate().bindingGeneration()) || readback.regionEpoch() != ownerStatus.regionEpoch() || !readback.executorFence().equals(ownerStatus.executorFence()) || !readback.leaseTokenCorrelation().equals(ownerStatus.leaseTokenCorrelation())) { @@ -416,7 +416,8 @@ RegionBridgeAcknowledgement acknowledgeRegionBridge( == CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { if (!ownerStatus.executorFence().equals(readback.executorFence()) || !current.redisReadbackDigest().equals(readback.digest())) { - throw conflict("A completed region acknowledgement has different readback provenance"); + throw conflict( + "A completed region acknowledgement has different readback provenance"); } return new RegionBridgeAcknowledgement(current); } @@ -513,27 +514,27 @@ private CanonicalGameplayBindingRegionBridgeObligation writePreparedBridge( writeRevisionRows(transaction, evidence, oldRevision, nextRevision); Object[] args = new Object[] { - operationId, - inputs.runtimeEntityId().value(), - inputs.projectionGeneration(), - inputs.projectionFence(), - inputs.workloadNamespace(), - inputs.assignmentId(), - inputs.assignmentIntentDigest(), - inputs.entityReferenceDigest(), - inputs.worldSourceDigest(), - inputs.canonicalRegionId(), - inputs.lifecycleEpoch(), - inputs.lifecycleRowVersion(), - inputs.captureId(), - inputs.graphSha256(), - inputs.preparationInputDigest(), - decimal(ownerStatus.executorFence()), - ownerStatus.leaseTokenCorrelation(), - decimal(nextRevision), - evidence.transition().transitionId(), - decimal(oldRevision) - }; + operationId, + inputs.runtimeEntityId().value(), + inputs.projectionGeneration(), + inputs.projectionFence(), + inputs.workloadNamespace(), + inputs.assignmentId(), + inputs.assignmentIntentDigest(), + inputs.entityReferenceDigest(), + inputs.worldSourceDigest(), + inputs.canonicalRegionId(), + inputs.lifecycleEpoch(), + inputs.lifecycleRowVersion(), + inputs.captureId(), + inputs.graphSha256(), + inputs.preparationInputDigest(), + decimal(ownerStatus.executorFence()), + ownerStatus.leaseTokenCorrelation(), + decimal(nextRevision), + evidence.transition().transitionId(), + decimal(oldRevision) + }; String sql = "UPDATE " + REGION_OBLIGATION @@ -701,19 +702,26 @@ private static BridgeInputs requireBridgeInputs( || !worldRequest.getUnknownFields().asMap().isEmpty() || !reference.target().equals(target) || !reference.assignmentUuid().toString().equals(worldRequest.getAssignmentUuid()) - || !reference.canonicalAccountUuid().toString().equals(worldRequest.getCanonicalAccountUuid()) + || !reference + .canonicalAccountUuid() + .toString() + .equals(worldRequest.getCanonicalAccountUuid()) || !reference.characterUuid().toString().equals(worldRequest.getCharacterUuid()) || !reference.intentDigest().equals(worldRequest.getAssignmentIntentDigest()) || !identity.accountId().toString().equals(worldRequest.getCanonicalAccountUuid()) || !identity.characterId().toString().equals(worldRequest.getCharacterUuid()) || !identity.tenantId().toString().equals(target.getCanonicalTenantUuid()) || !identity.gameInstanceId().toString().equals(target.getGameInstanceId()) - || !identity.playableStateNamespaceId() + || !identity + .playableStateNamespaceId() .toString() .equals(target.getPlayableStateNamespaceUuid()) || !"SHARED".equals(identity.playableStateScope()) || !reference.runtimeEntityId().tenantId().equals(identity.tenantId()) - || !reference.runtimeEntityId().gameInstanceId().equals(identity.gameInstanceId().toString()) + || !reference + .runtimeEntityId() + .gameInstanceId() + .equals(identity.gameInstanceId().toString()) || !identity.tenantId().equals(assignment.request().canonicalTenantId()) || !identity.gameInstanceId().equals(assignment.request().canonicalGameInstanceId()) || !identity.regionId().equals(assignment.operationalRegionId()) @@ -766,22 +774,28 @@ private static void requireCurrentRegionOwner( || !Objects.equals(row.get("canonical_region_id", UUID.class), expected.canonicalRegionId()) || !Objects.equals(row.get("tenant_region_tag", String.class), expected.tenantRegionTag()) || !Objects.equals(row.get("region_epoch", Long.class), expected.regionEpoch()) - || !Objects.equals(row.get("executor_fence", Long.class), expected.executorFence().longValueExact()) + || !Objects.equals( + row.get("executor_fence", Long.class), expected.executorFence().longValueExact()) || !Objects.equals( row.get("lease_token_correlation", String.class), expected.leaseTokenCorrelation()) || !Objects.equals(row.get("owner_service", String.class), expected.ownerService()) || !Objects.equals(row.get("owner_instance_id", String.class), expected.ownerInstanceId()) || !Objects.equals(row.get("lifecycle_epoch", Long.class), expected.lifecycleEpoch()) - || !Objects.equals(row.get("lifecycle_row_version", Long.class), expected.lifecycleRowVersion()) + || !Objects.equals( + row.get("lifecycle_row_version", Long.class), expected.lifecycleRowVersion()) || !Objects.equals(row.get("capture_id", UUID.class), expected.captureId()) || !Arrays.equals( row.get("lifecycle_request_bytes", byte[].class), expected.lifecycleRequest().canonicalBytes()) || !Objects.equals(row.get("graph_sha256", String.class), expected.graphSha256()) - || !Objects.equals(row.get("preparation_input_digest", String.class), expected.preparationInputDigest()) + || !Objects.equals( + row.get("preparation_input_digest", String.class), expected.preparationInputDigest()) || !Boolean.FALSE.equals(row.get("paused", Boolean.class)) - || !Objects.equals(row.get("last_committed_tick_id", Long.class), expected.lastCommittedTickId()) - || !Objects.equals(row.get("last_committed_tick_batch_id", String.class), expected.lastCommittedTickBatchId())) { + || !Objects.equals( + row.get("last_committed_tick_id", Long.class), expected.lastCommittedTickId()) + || !Objects.equals( + row.get("last_committed_tick_batch_id", String.class), + expected.lastCommittedTickBatchId())) { throw conflict("Durable region owner, timeline, or executor fence changed"); } } @@ -813,8 +827,7 @@ private record BridgeInputs( static final class RegionBridgeAcknowledgement { private final CanonicalGameplayBindingRegionBridgeObligation obligation; - private RegionBridgeAcknowledgement( - CanonicalGameplayBindingRegionBridgeObligation obligation) { + private RegionBridgeAcknowledgement(CanonicalGameplayBindingRegionBridgeObligation obligation) { if (obligation.status() != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { throw conflict("Only a persisted region bridge ACK can create its receipt"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java index fe2f1c877d..5e7ed8b0bf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java @@ -2,9 +2,9 @@ import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; -import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; /** Manual owner for the initial-NEW region binding mutation and its durable local ACK. */ final class CanonicalGameplayRegionBindingBridgeOwner { @@ -15,7 +15,8 @@ final class CanonicalGameplayRegionBindingBridgeOwner { CanonicalGameplayRegionLeaseOwner regionLeaseOwner, CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) { this.regionLeaseOwner = Objects.requireNonNull(regionLeaseOwner, "regionLeaseOwner"); - this.entityReferenceClient = Objects.requireNonNull(entityReferenceClient, "entityReferenceClient"); + this.entityReferenceClient = + Objects.requireNonNull(entityReferenceClient, "entityReferenceClient"); } /** Acquires the real region grant/fence, then performs the selected first-NEW bridge. */ @@ -25,7 +26,9 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement installA return bridge(regionLeaseOwner.installForTransition(transitionId, request)); } - /** Returns the closed same-grant capability so a lost bridge reply can retry without reacquire. */ + /** + * Returns the closed same-grant capability so a lost bridge reply can retry without reacquire. + */ CanonicalGameplayRegionLeaseOwner.Installation installForTransition( UUID transitionId, net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { @@ -60,8 +63,7 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( CanonicalGameplayRegionLeaseOwner.RegionBridgePreimage beforeWritePreimage = regionLeaseOwner.probeRegionSessionBinding(installation, beforeWriteReference); CanonicalGameplayBindingRegionBridgeObligation prepared = - regionLeaseOwner.prepareBridge( - installation, beforeWritePreimage, beforeWriteReference); + regionLeaseOwner.prepareBridge(installation, beforeWritePreimage, beforeWriteReference); regionLeaseOwner.applyRegionSessionBinding(installation, beforeWriteReference); CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference currentReference = @@ -70,8 +72,7 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( CanonicalGameplayRegionLeaseOwner.RegionBridgePreimage beforeReadbackPreimage = regionLeaseOwner.probeRegionSessionBinding(installation, currentReference); prepared = - regionLeaseOwner.prepareBridge( - installation, beforeReadbackPreimage, currentReference); + regionLeaseOwner.prepareBridge(installation, beforeReadbackPreimage, currentReference); CanonicalGameplayRegionLeaseRedisOwner.BindingReadback readback = regionLeaseOwner.readBackRegionSessionBinding( @@ -85,15 +86,10 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( throw unavailable(); } prepared = - regionLeaseOwner.prepareBridge( - installation, beforeAckPreimage, afterReadbackReference); + regionLeaseOwner.prepareBridge(installation, beforeAckPreimage, afterReadbackReference); return regionLeaseOwner.acknowledgeBridge( - installation, - prepared, - beforeAckPreimage.context(), - afterReadbackReference, - readback); + installation, prepared, beforeAckPreimage.context(), afterReadbackReference, readback); } private static ReadPreseededActorRuntimeReferenceRequest entityRequest( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java index da0fbcabc7..60016815c5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java @@ -6,11 +6,12 @@ import java.security.MessageDigest; import java.util.HexFormat; import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; -import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceResponse; /** Closed digest projections for exact bridge sources and independently observed readback. */ final class CanonicalGameplayRegionBindingBridgeProofs { @@ -105,7 +106,8 @@ static String initialMetaDigest(String tag, UUID operationId, String sourceDiges + operationId + "\nfirst_timeline_source_digest=" + sourceDigest; - return sha256(tag.getBytes(StandardCharsets.US_ASCII), baseline.getBytes(StandardCharsets.US_ASCII)); + return sha256( + tag.getBytes(StandardCharsets.US_ASCII), baseline.getBytes(StandardCharsets.US_ASCII)); } private static byte[] uuid(UUID value) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionIncarnationSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionIncarnationSource.java index 12d39d9568..5b354e0632 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionIncarnationSource.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionIncarnationSource.java @@ -58,8 +58,8 @@ byte[] canonicalBytes() { } /** - * Complete stable incarnation value. This carries the established deployment evidence shape; - * it does not verify a source, create a production provider, or reuse Account intent context. + * Complete stable incarnation value. This carries the established deployment evidence shape; it + * does not verify a source, create a production provider, or reuse Account intent context. */ record StableEvidence( RegionScope scope, @@ -79,17 +79,18 @@ record StableEvidence( requireDigest(coordOpsRoAclDigest); requireDigest(coordRedisConfigObservedDigest); if (!qualifiedNonResetProfile) throw unavailableException(); - Objects.requireNonNull(timelineInitializationQualification, "timelineInitializationQualification"); + Objects.requireNonNull( + timelineInitializationQualification, "timelineInitializationQualification"); if (targetDeploymentEvidence.canonicalNodeSet().size() > 2048 || scope.canonicalBytes().length > 4096 || stableValueBytes( - scope, - attestorBinding, - acceptedAttestationDigest, - targetDeploymentEvidence, - coordOpsRoAclDigest, - coordRedisConfigObservedDigest) - .length + scope, + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest) + .length > 65536 || timelineInitializationQualification.canonicalBytes().length > 8192 || !timelineInitializationQualification.matches( @@ -157,13 +158,14 @@ byte[] scopeBytes() { } byte[] stableCanonicalBytes() { - return CanonicalGameplayRegionIncarnationSource.canonicalBytes(stableValue( - scope, - attestorBinding, - acceptedAttestationDigest, - targetDeploymentEvidence, - coordOpsRoAclDigest, - coordRedisConfigObservedDigest)); + return CanonicalGameplayRegionIncarnationSource.canonicalBytes( + stableValue( + scope, + attestorBinding, + acceptedAttestationDigest, + targetDeploymentEvidence, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest)); } byte[] canonicalBytes() { @@ -187,7 +189,9 @@ String digest() { } } - /** Positive exact-scope evidence for all canonical first-metadata initialization prerequisites. */ + /** + * Positive exact-scope evidence for all canonical first-metadata initialization prerequisites. + */ record TimelineInitializationQualification( RegionScope scope, String stableIncarnationDigest, @@ -331,7 +335,8 @@ static String digestBytes(byte[] value) { } private static void requireText(String value) { - if (value == null || value.isBlank() || !value.equals(value.trim())) throw unavailableException(); + if (value == null || value.isBlank() || !value.equals(value.trim())) + throw unavailableException(); } private static void requireDigest(String value) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index b4199404a0..37cb5a4de6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -8,9 +8,9 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.runtime.RuntimeIdentity; -import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; @@ -101,7 +101,8 @@ Installation installForTransition( source, incarnation) || preparation.phase() - == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INSTALLED) { + == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .INSTALLED) { throw unavailable(); } Optional permit = @@ -137,9 +138,11 @@ Installation installForTransition( source, incarnation) || preparation.phase() - != CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INSTALLED + != CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .INSTALLED && preparation.phase() - != CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.REDIS_INITIALIZED) { + != CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .REDIS_INITIALIZED) { throw unavailable(); } grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); @@ -202,10 +205,8 @@ BridgeContext currentBridgeContext(Installation installation) { CanonicalGameplayBindingProvisionalCasEvidence evidence = readCurrentProvisionalEvidence(installation.transitionId); bindingInventory.requireSameProvisionalSource(installation.evidence, evidence); - ResolvedBridgeSource resolved = - resolveExactBridgeSource(installation.worldRequest, evidence); - CanonicalGameplayRegionRuntimeStatusRepository.Source currentSource = - resolved.source; + ResolvedBridgeSource resolved = resolveExactBridgeSource(installation.worldRequest, evidence); + CanonicalGameplayRegionRuntimeStatusRepository.Source currentSource = resolved.source; requireSameSource(installation.source, currentSource); requireSameIncarnation(installation.incarnation, readCurrentIncarnation(currentSource)); CanonicalGameplayRegionRuntimeStatus current = @@ -388,9 +389,7 @@ private CanonicalGameplayRegionIncarnationSource.StableEvidence readCurrentIncar incarnationSource.readCurrent(scope); if (current == null || !scope.equals(current.scope()) - || !current - .timelineInitializationQualification() - .matches(scope, current.digest())) { + || !current.timelineInitializationQualification().matches(scope, current.digest())) { throw unavailable(); } return current; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index 5a2b62af70..c28867a7fa 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -22,10 +22,10 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.common.runtime.RuntimeIdentity; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; -import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; -import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Manually composed region lease using the exact full-scope key, registered Lua, and readback. */ @@ -36,7 +36,8 @@ final class CanonicalGameplayRegionLeaseRedisOwner { private static final long COMMAND_TIMEOUT_MILLIS = 5_000L; private static final List LEASE_ARGUMENTS = List.of("schema", "token", "expectedRegionEpoch", "leaseTtlMs"); - private static final List READ_ARGUMENTS = List.of("schema", "token", "expectedRegionEpoch"); + private static final List READ_ARGUMENTS = + List.of("schema", "token", "expectedRegionEpoch"); private static final List EXPECTED_KEYS = List.of( new RedisScriptDescriptor.KeySpec( @@ -58,7 +59,13 @@ final class CanonicalGameplayRegionLeaseRedisOwner { "mayCreateFromAbsence"); private static final String BRIDGE_SCHEMA = "gs_region_binding_bridge/v1"; private static final List BRIDGE_ARGUMENTS = - List.of("schema", "action", "leaseToken", "expectedRegionEpoch", "sessionId", "bindingGeneration"); + List.of( + "schema", + "action", + "leaseToken", + "expectedRegionEpoch", + "sessionId", + "bindingGeneration"); private static final List BRIDGE_KEYS = List.of( new RedisScriptDescriptor.KeySpec( @@ -150,8 +157,12 @@ LeaseGrant initializeOrResumeTimeline( throw unavailable(); } LeaseGrant grant = - new LeaseGrant(preparation.source(), preparation.regionEpoch(), UUID.randomUUID().toString(), - ownerService, ownerInstance); + new LeaseGrant( + preparation.source(), + preparation.regionEpoch(), + UUID.randomUUID().toString(), + ownerService, + ownerInstance); long outcome = executeTimeline( grant, @@ -168,17 +179,13 @@ void verifyInitializedTimeline( LeaseGrant grant, CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation) { requireNoAmbientTransaction(); - if (!grant.source.equals(preparation.source()) || grant.regionEpoch != preparation.regionEpoch()) { + if (!grant.source.equals(preparation.source()) + || grant.regionEpoch != preparation.regionEpoch()) { throw unavailable(); } long outcome = executeTimeline( - grant, - "VERIFY", - preparation.operationId(), - preparation.sourceDigest(), - 1L, - false); + grant, "VERIFY", preparation.operationId(), preparation.sourceDigest(), 1L, false); if (outcome != 3L) throw unavailable(); } @@ -260,10 +267,12 @@ private long executeTimeline( byte[] script = scriptSource(descriptor); byte[][] keys = new byte[][] { - ascii(CanonicalGameplayRegionRedisKeys.lease( - source.tenantId(), source.gameInstanceId(), source.regionId())), - ascii(CanonicalGameplayRegionRedisKeys.meta( - source.tenantId(), source.gameInstanceId(), source.regionId())) + ascii( + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId())), + ascii( + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())) }; byte[][] arguments = new byte[][] { @@ -288,8 +297,9 @@ private static String absenceProofDigest( ascii("firemud.gs.region-timeline-absent/v1"), incarnation.scopeBytes(), incarnation.canonicalBytes(), - ascii(CanonicalGameplayRegionRedisKeys.tenantRegionTag( - source.tenantId(), source.gameInstanceId(), source.regionId())))); + ascii( + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId())))); } private static byte[] concat(byte[]... values) { @@ -312,8 +322,7 @@ void applySessionBinding( String sessionId, BigInteger bindingGeneration) { long outcome = - executeBinding( - grant, durableOwner, runtimeEntityId, sessionId, bindingGeneration, "APPLY"); + executeBinding(grant, durableOwner, runtimeEntityId, sessionId, bindingGeneration, "APPLY"); if (outcome != 1L && outcome != 2L) throw unavailable(); } @@ -325,8 +334,7 @@ BindingPreimage probeSessionBinding( String sessionId, BigInteger bindingGeneration) { long outcome = - executeBinding( - grant, durableOwner, runtimeEntityId, sessionId, bindingGeneration, "PROBE"); + executeBinding(grant, durableOwner, runtimeEntityId, sessionId, bindingGeneration, "PROBE"); if (outcome != 4L && outcome != 5L) throw unavailable(); return new BindingPreimage( runtimeEntityId, @@ -375,8 +383,7 @@ private long executeBinding( if (bindingGeneration.signum() <= 0 || bindingGeneration.toString().length() > 128 || sessionId == null - || !sessionId.matches( - "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + || !sessionId.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") || !"APPLY".equals(action) && !"READBACK".equals(action) && !"PROBE".equals(action)) { throw unavailable(); } @@ -386,13 +393,15 @@ private long executeBinding( byte[][] keys = new byte[][] { ascii(grant.key()), - ascii(CanonicalGameplayRegionRedisKeys.meta( - grant.source.tenantId(), grant.source.gameInstanceId(), grant.source.regionId())), - ascii(CanonicalGameplayRegionRedisKeys.sessionBinding( - grant.source.tenantId(), - grant.source.gameInstanceId(), - grant.source.regionId(), - runtimeEntityId.value())) + ascii( + CanonicalGameplayRegionRedisKeys.meta( + grant.source.tenantId(), grant.source.gameInstanceId(), grant.source.regionId())), + ascii( + CanonicalGameplayRegionRedisKeys.sessionBinding( + grant.source.tenantId(), + grant.source.gameInstanceId(), + grant.source.regionId(), + runtimeEntityId.value())) }; byte[][] arguments = new byte[][] { @@ -420,7 +429,8 @@ private static void requireGrantBackedStatus( || !status.captureId().equals(grant.source.captureId()) || !status.graphSha256().equals(grant.source.graphSha256()) || !status.preparationInputDigest().equals(grant.source.preparationInputDigest()) - || !status.tenantRegionTag() + || !status + .tenantRegionTag() .equals( CanonicalGameplayRegionRedisKeys.tenantRegionTag( grant.source.tenantId(), @@ -449,8 +459,9 @@ private long execute( byte[][] keys = new byte[][] { ascii(grant.key()), - ascii(CanonicalGameplayRegionRedisKeys.meta( - grant.source.tenantId(), grant.source.gameInstanceId(), grant.source.regionId())) + ascii( + CanonicalGameplayRegionRedisKeys.meta( + grant.source.tenantId(), grant.source.gameInstanceId(), grant.source.regionId())) }; byte[][] arguments = grant.arguments(includeTtl ? ttlMillis : null); if (arguments.length != expectedArguments.size()) throw unavailable(); @@ -465,9 +476,7 @@ private long executeInteger(byte[] script, byte[][] keys, byte[][] arguments) { requirePrincipal(await(commands.aclWhoami())); String loadedSha = await(commands.scriptLoad(script)); if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); - Long result = - await( - commands.evalsha(loadedSha, ScriptOutputType.INTEGER, keys, arguments)); + Long result = await(commands.evalsha(loadedSha, ScriptOutputType.INTEGER, keys, arguments)); if (result == null) throw unavailable(); return result; } catch (RuntimeException failure) { @@ -479,10 +488,10 @@ private RedisScriptDescriptor requireBridgeDescriptor() { try { RedisScriptDescriptor descriptor = catalog.require(CanonicalGameplayRegionBindingBridgeRedisScriptContribution.SCRIPT_ID); - if (!CanonicalGameplayRegionBindingBridgeRedisScriptContribution.SCRIPT_ID - .equals(descriptor.scriptId()) - || !CanonicalGameplayRegionBindingBridgeRedisScriptContribution.SCRIPT_PATH - .equals(descriptor.resourcePath()) + if (!CanonicalGameplayRegionBindingBridgeRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayRegionBindingBridgeRedisScriptContribution.SCRIPT_PATH.equals( + descriptor.resourcePath()) || !"game-session-service".equals(descriptor.owner()) || !PRINCIPAL.equals(descriptor.principal()) || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java index 13ccd21fb9..9e10b8a1dc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeys.java @@ -29,7 +29,8 @@ static String meta(UUID tenantId, UUID gameInstanceId, UUID regionId) { static String sessionBinding( UUID tenantId, UUID gameInstanceId, UUID regionId, long runtimeEntityId) { - if (runtimeEntityId <= 0L) throw new IllegalArgumentException("runtimeEntityId must be positive"); + if (runtimeEntityId <= 0L) + throw new IllegalArgumentException("runtimeEntityId must be positive"); return "tick:{" + tenantRegionTag(tenantId, gameInstanceId, regionId) + "}:session-binding:" diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index 76f78322ea..985336962a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -68,12 +68,7 @@ TimelinePreparation prepareInitialTimeline( if (absenceProof == null || !absenceProof.matches(source, incarnation)) throw unavailable(); InitialTimelineInputs inputs = requireInitialTimelineInputs( - evidence, - worldRequest, - resolvedRegion, - source, - incarnation, - absenceProof.digest()); + evidence, worldRequest, resolvedRegion, source, incarnation, absenceProof.digest()); try { TimelinePreparation prepared = dsl.transactionResult( @@ -92,7 +87,9 @@ TimelinePreparation prepareInitialTimeline( if (existingStatus != null) throw unavailable(); Record existingTransition = transaction.fetchOne( - "SELECT * FROM " + PREPARATION_TABLE + " WHERE transition_id = ? FOR UPDATE", + "SELECT * FROM " + + PREPARATION_TABLE + + " WHERE transition_id = ? FOR UPDATE", evidence.transition().transitionId()); if (existingTransition != null) { TimelinePreparation current = toTimelinePreparation(existingTransition); @@ -182,8 +179,9 @@ TimelinePreparation prepareInitialTimeline( Optional findTimelinePreparation(Source source) { requireNoAmbientTransaction(); Objects.requireNonNull(source, "source"); - String tag = CanonicalGameplayRegionRedisKeys.tenantRegionTag( - source.tenantId(), source.gameInstanceId(), source.regionId()); + String tag = + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId()); Record row = dsl.fetchOne( "SELECT * FROM " @@ -261,7 +259,8 @@ Optional beginInitialTimeline( OffsetDateTime.ofInstant(now, ZoneOffset.UTC), current.operationId); if (updated != 1) throw unavailable(); - return Optional.of(new InitialInitializationPermit(current.operationId, current.sourceDigest)); + return Optional.of( + new InitialInitializationPermit(current.operationId, current.sourceDigest())); }); } @@ -431,7 +430,8 @@ private static InitialTimelineInputs requireInitialTimelineInputs( || !identity.characterId().toString().equals(worldRequest.getCharacterUuid()) || !identity.tenantId().toString().equals(target.getCanonicalTenantUuid()) || !identity.gameInstanceId().toString().equals(target.getGameInstanceId()) - || !identity.playableStateNamespaceId() + || !identity + .playableStateNamespaceId() .toString() .equals(target.getPlayableStateNamespaceUuid()) || !"SHARED".equals(identity.playableStateScope()) @@ -507,15 +507,13 @@ private static boolean matchesPreparation( && Arrays.equals(preparation.incarnationScopeBytes, inputs.incarnationScopeBytes()) && Arrays.equals(preparation.incarnationSourceBytes, inputs.incarnationSourceBytes()) && Arrays.equals( - preparation.incarnationQualificationBytes, - inputs.incarnationQualificationBytes()) + preparation.incarnationQualificationBytes, inputs.incarnationQualificationBytes()) && preparation.incarnationDigest.equals(inputs.incarnationDigest()) && preparation.timelinePreimageState.equals("ABSENT") && preparation.absenceProofDigest.equals(inputs.absenceProofDigest()); } - private static boolean samePreparation( - TimelinePreparation expected, TimelinePreparation actual) { + private static boolean samePreparation(TimelinePreparation expected, TimelinePreparation actual) { return expected.operationId.equals(actual.operationId) && expected.transitionId.equals(actual.transitionId) && expected.source.equals(actual.source) @@ -991,7 +989,8 @@ private TimelinePreparation( this.sessionId = Objects.requireNonNull(sessionId, "sessionId"); this.bindingGeneration = Objects.requireNonNull(bindingGeneration, "bindingGeneration"); this.assignmentId = Objects.requireNonNull(assignmentId, "assignmentId"); - this.assignmentIntentDigest = Objects.requireNonNull(assignmentIntentDigest, "assignmentIntentDigest"); + this.assignmentIntentDigest = + Objects.requireNonNull(assignmentIntentDigest, "assignmentIntentDigest"); this.canonicalRegionId = Objects.requireNonNull(canonicalRegionId, "canonicalRegionId"); this.regionId = Objects.requireNonNull(regionId, "regionId"); this.tenantRegionTag = Objects.requireNonNull(tenantRegionTag, "tenantRegionTag"); @@ -1006,7 +1005,8 @@ private TimelinePreparation( Objects.requireNonNull(incarnationQualificationBytes, "incarnationQualificationBytes") .clone(); this.incarnationDigest = Objects.requireNonNull(incarnationDigest, "incarnationDigest"); - this.timelinePreimageState = Objects.requireNonNull(timelinePreimageState, "timelinePreimageState"); + this.timelinePreimageState = + Objects.requireNonNull(timelinePreimageState, "timelinePreimageState"); this.absenceProofDigest = Objects.requireNonNull(absenceProofDigest, "absenceProofDigest"); if (!incarnationDigest.equals( CanonicalGameplayRegionIncarnationSource.digestBytes(this.incarnationSourceBytes)) @@ -1069,8 +1069,7 @@ BigInteger executorFence() { return executorFence; } - boolean matchesIncarnation( - CanonicalGameplayRegionIncarnationSource.StableEvidence current) { + boolean matchesIncarnation(CanonicalGameplayRegionIncarnationSource.StableEvidence current) { return current != null && timelinePreimageState.equals("ABSENT") && Arrays.equals(incarnationScopeBytes, current.scopeBytes()) @@ -1084,7 +1083,6 @@ boolean matchesIncarnation( String absenceProofDigest() { return absenceProofDigest; } - } static final class InitialInitializationPermit { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java index bbb5794abe..03d3be3686 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java @@ -14,7 +14,8 @@ public final class CanonicalGameplayRegionBindingBridgeRedisScriptContribution implements RedisScriptContribution { public static final String SCRIPT_ID = "game-session.region-session-binding-bridge.v1"; - public static final String SCRIPT_PATH = "redis/lua/game-session-region-session-binding-bridge.lua"; + public static final String SCRIPT_PATH = + "redis/lua/game-session-region-session-binding-bridge.lua"; private static final String DESCRIPTOR_PATH = "/redis/scripts/game-session-region-session-binding-bridge.json"; private static final JsonMapper JSON = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java index 87beeada48..5ba434a32e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java @@ -40,7 +40,8 @@ public Collection descriptors() { read("/redis/scripts/game-session-region-lease-acquire.json", ACQUIRE_ID), read("/redis/scripts/game-session-region-lease-renew.json", RENEW_ID), read("/redis/scripts/game-session-region-lease-read.json", READ_ID), - read("/redis/scripts/game-session-region-timeline-initialize.json", TIMELINE_INITIALIZE_ID)); + read( + "/redis/scripts/game-session-region-timeline-initialize.json", TIMELINE_INITIALIZE_ID)); } private RedisScriptDescriptor read(String path, String id) { diff --git a/services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql b/services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql index 8f90318085..8958fbaf05 100644 --- a/services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql +++ b/services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql @@ -69,7 +69,9 @@ ALTER TABLE game_session_canonical_binding_region_bridge_obligation AND entity_projection_fence IS NOT NULL AND entity_projection_fence > 0 AND entity_workload_namespace IS NOT NULL + -- [jooq ignore start] AND entity_workload_namespace <> '' + -- [jooq ignore stop] AND assignment_uuid IS NOT NULL AND assignment_uuid <> '00000000-0000-0000-0000-000000000000'::uuid AND assignment_intent_digest IS NOT NULL diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java index 8edd15cc9d..4f5deeb4b6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java @@ -53,7 +53,9 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -/** Controlled Redis and test-PKI proof; the source peer is not a production Entity placement claim. */ +/** + * Controlled Redis and test-PKI proof; the source peer is not a production Entity placement claim. + */ @Testcontainers(disabledWithoutDocker = true) @Timeout(60) @SuppressWarnings("resource") @@ -113,18 +115,31 @@ void sameGrantAppliesAndReadsBackExactTypedEntityBindingThenPreservesForeignStat String meta = CanonicalGameplayRegionRedisKeys.meta(TENANT_ID, GAME_INSTANCE_ID, REGION_ID); var absent = owner.probeSessionBinding( - grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE); assertThat(absent.state()) .isEqualTo(CanonicalGameplayRegionLeaseRedisOwner.PreimageState.ABSENT); - owner.applySessionBinding(grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); + owner.applySessionBinding( + grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); var exact = owner.probeSessionBinding( - grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE); assertThat(exact.state()) .isEqualTo(CanonicalGameplayRegionLeaseRedisOwner.PreimageState.EXACT); var readback = owner.readBackSessionBinding( - grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE); assertThat(readback.runtimeEntityId()).isEqualTo(actor.runtimeEntityId()); assertThat(readback.sessionId()).isEqualTo(SESSION_ID.toString()); assertThat(readback.bindingGeneration()).isEqualTo(java.math.BigInteger.ONE); @@ -134,11 +149,12 @@ void sameGrantAppliesAndReadsBackExactTypedEntityBindingThenPreservesForeignStat .containsExactly(ascii("1")); byte[] foreignSession = ascii("88888888-8888-4888-8888-888888888888"); - redis.admin().hset( - ascii(key), - java.util.Map.of( - ascii("session_id"), foreignSession, - ascii("binding_generation"), ascii("2"))); + redis + .admin() + .hset( + ascii(key), + java.util.Map.of( + ascii("session_id"), foreignSession, ascii("binding_generation"), ascii("2"))); assertThatThrownBy( () -> owner.probeSessionBinding( @@ -157,7 +173,8 @@ void sameGrantAppliesAndReadsBackExactTypedEntityBindingThenPreservesForeignStat SESSION_ID.toString(), java.math.BigInteger.ONE)) .isInstanceOf(IllegalStateException.class); - assertThat(redis.admin().hget(ascii(key), ascii("session_id"))).containsExactly(foreignSession); + assertThat(redis.admin().hget(ascii(key), ascii("session_id"))) + .containsExactly(foreignSession); assertThat(redis.admin().hget(ascii(key), ascii("binding_generation"))) .containsExactly(ascii("2")); } @@ -225,22 +242,30 @@ void bridgesTickZeroButRejectsExpiringMetaBeforeReadback() throws Exception { RuntimeIdentity identity = runtimeIdentity("tick-zero"); seedMeta(redis.admin(), source, "1"); String meta = CanonicalGameplayRegionRedisKeys.meta(TENANT_ID, GAME_INSTANCE_ID, REGION_ID); - redis.admin().hset( - ascii(meta), - ascii("current_tick_id"), - ascii("0"), - ascii("current_tick_state"), - ascii("STAGED")); + redis + .admin() + .hset( + ascii(meta), + java.util.Map.of( + ascii("current_tick_id"), ascii("0"), + ascii("current_tick_state"), ascii("STAGED"))); var grant = owner.acquire(source, 1L, Duration.ofSeconds(30), identity); var status = status(source, grant, identity); var actor = readActualEntityReference(); owner.applySessionBinding( grant, status, actor.runtimeEntityId(), SESSION_ID.toString(), java.math.BigInteger.ONE); - assertThat(redis.admin().hget( - ascii(CanonicalGameplayRegionRedisKeys.sessionBinding( - TENANT_ID, GAME_INSTANCE_ID, REGION_ID, actor.runtimeEntityId().value())), - ascii("session_id"))) + assertThat( + redis + .admin() + .hget( + ascii( + CanonicalGameplayRegionRedisKeys.sessionBinding( + TENANT_ID, + GAME_INSTANCE_ID, + REGION_ID, + actor.runtimeEntityId().value())), + ascii("session_id"))) .containsExactly(ascii(SESSION_ID.toString())); assertThat(redis.admin().pexpire(ascii(meta), 60_000L)).isTrue(); @@ -424,14 +449,13 @@ private static void seedMeta( CanonicalGameplayRegionRuntimeStatusRepository.Source source, String epoch) { admin.hset( - ascii(CanonicalGameplayRegionRedisKeys.meta( - source.tenantId(), source.gameInstanceId(), source.regionId())), - ascii("region_epoch"), - ascii(epoch), - ascii("current_tick_id"), - ascii("-1"), - ascii("current_tick_state"), - ascii("APPLIED")); + ascii( + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())), + java.util.Map.of( + ascii("region_epoch"), ascii(epoch), + ascii("current_tick_id"), ascii("-1"), + ascii("current_tick_state"), ascii("APPLIED"))); } private static final class RedisFixture implements AutoCloseable { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index c39e3d630d..dcb3ebb999 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -100,14 +100,19 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws var redisOwner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); WorldFixture world = WorldFixture.open(); - ControlledStableIncarnationSource incarnationSource = - new ControlledStableIncarnationSource(); + ControlledStableIncarnationSource incarnationSource = new ControlledStableIncarnationSource(); var bindingEvidence = provisionalEvidence(world.request()); var bindingInventory = mock(CanonicalGameplayBindingInventoryRepository.class); when(bindingInventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(bindingEvidence); var firstOwner = - owner(bindingInventory, statusRepository, redisOwner, world, "instance-a", incarnationSource); + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-a", + incarnationSource); var qualifiedSource = source(world.originalEvidence()); byte[] redisKey = ascii( @@ -140,7 +145,13 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws when(wrongTargetInventory.readProvisionalCasEvidence(TRANSITION_ID)) .thenReturn(wrongTargetEvidence); var wrongTargetOwner = - owner(wrongTargetInventory, statusRepository, redisOwner, world, "wrong-target", incarnationSource); + owner( + wrongTargetInventory, + statusRepository, + redisOwner, + world, + "wrong-target", + incarnationSource); assertThatThrownBy( () -> wrongTargetOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); @@ -153,7 +164,13 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws when(wrongEpochInventory.readProvisionalCasEvidence(TRANSITION_ID)) .thenReturn(wrongEpochEvidence); var wrongEpochOwner = - owner(wrongEpochInventory, statusRepository, redisOwner, world, "wrong-epoch", incarnationSource); + owner( + wrongEpochInventory, + statusRepository, + redisOwner, + world, + "wrong-epoch", + incarnationSource); assertThatThrownBy(() -> wrongEpochOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().type(redisKey)).isEqualTo("none"); @@ -169,8 +186,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws CanonicalGameplayRegionIncarnationSource.unavailable()); assertThatThrownBy( () -> - unavailableIncarnationOwner.installForTransition( - TRANSITION_ID, world.request())) + unavailableIncarnationOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().type(redisKey)).isEqualTo("none"); assertThat(statusRepository.find(qualifiedSource)).isEmpty(); @@ -186,8 +202,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(statusRepository.find(qualifiedSource)).isEmpty(); world.setAfterRead(2, incarnationSource::changeRecoveryEvidence); - assertThatThrownBy( - () -> firstOwner.installForTransition(TRANSITION_ID, world.request())) + assertThatThrownBy(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); assertThat(statusRepository.find(qualifiedSource)).isEmpty(); Record retainedPreparation = @@ -279,19 +294,26 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws qualifiedSource.tenantId(), qualifiedSource.gameInstanceId(), qualifiedSource.regionId()); - redis.admin().hset( - ascii(CanonicalGameplayRegionRedisKeys.meta( - qualifiedSource.tenantId(), - qualifiedSource.gameInstanceId(), - qualifiedSource.regionId())), - ascii("current_tick_id"), - ascii("0"), - ascii("current_tick_state"), - ascii("APPLIED"), - ascii("current_tick_terminal_at_ms"), - ascii("1792972800000")); + redis + .admin() + .hset( + ascii( + CanonicalGameplayRegionRedisKeys.meta( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId())), + java.util.Map.of( + ascii("current_tick_id"), ascii("0"), + ascii("current_tick_state"), ascii("APPLIED"), + ascii("current_tick_terminal_at_ms"), ascii("1792972800000"))); var secondOwner = - owner(bindingInventory, statusRepository, redisOwner, world, "instance-b", incarnationSource); + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-b", + incarnationSource); secondOwner.installForTransition(TRANSITION_ID, world.request()); var secondStatus = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(secondStatus.executorFence()).isGreaterThan(firstStatus.executorFence()); @@ -310,22 +332,29 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws qualifiedSource.tenantId(), qualifiedSource.gameInstanceId(), qualifiedSource.regionId()); - redis.admin().hset( - ascii(CanonicalGameplayRegionRedisKeys.meta( - qualifiedSource.tenantId(), - qualifiedSource.gameInstanceId(), - qualifiedSource.regionId())), - ascii("current_tick_id"), - ascii("8"), - ascii("current_tick_state"), - ascii("APPLIED"), - ascii("current_tick_terminal_at_ms"), - ascii("1792972800000")); + redis + .admin() + .hset( + ascii( + CanonicalGameplayRegionRedisKeys.meta( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId())), + java.util.Map.of( + ascii("current_tick_id"), ascii("8"), + ascii("current_tick_state"), ascii("APPLIED"), + ascii("current_tick_terminal_at_ms"), ascii("1792972800000"))); var progressed = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); var thirdOwner = - owner(bindingInventory, statusRepository, redisOwner, world, "instance-c", incarnationSource); + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-c", + incarnationSource); var thirdInstallation = thirdOwner.installForTransition(TRANSITION_ID, world.request()); var thirdStatus = statusRepository.find(qualifiedSource).orElseThrow(); assertThat(thirdStatus.executorFence()).isGreaterThan(progressed.executorFence()); @@ -347,9 +376,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws "changed-incarnation", incarnationSource); assertThatThrownBy( - () -> - changedIncarnationOwner.installForTransition( - TRANSITION_ID, world.request())) + () -> changedIncarnationOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().get(redisKey)).containsExactly(liveLeaseBeforeIncarnationChange); assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); @@ -360,7 +387,13 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws WorldCanonicalInstanceLifecycleEvidence changed = changedEvidence(world.originalEvidence()); world.replaceOnRead(2, changed); var fourthOwner = - owner(bindingInventory, statusRepository, redisOwner, world, "instance-d", incarnationSource); + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-d", + incarnationSource); assertThatThrownBy(() -> fourthOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); assertThat(statusRepository.find(qualifiedSource)).contains(thirdStatus); @@ -369,7 +402,13 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws world.resetReads(); world.replaceOnRead(3, changed); var fifthOwner = - owner(bindingInventory, statusRepository, redisOwner, world, "instance-e", incarnationSource); + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-e", + incarnationSource); assertThatThrownBy(() -> fifthOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); var installedBeforeChangedSourceGate = statusRepository.find(qualifiedSource).orElseThrow(); @@ -382,7 +421,13 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws world.resetReads(); world.setAfterRead(2, POSTGRES::stop); var sixthOwner = - owner(bindingInventory, statusRepository, redisOwner, world, "instance-f", incarnationSource); + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "instance-f", + incarnationSource); assertThatThrownBy(() -> sixthOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(RuntimeException.class); assertThat(redis.admin().type(redisKey)).isEqualTo("string"); @@ -449,7 +494,8 @@ private static final class ControlledStableIncarnationSource public synchronized CanonicalGameplayRegionIncarnationSource.StableEvidence readCurrent( CanonicalGameplayRegionIncarnationSource.RegionScope scope) { if (current == null) current = stableIncarnation(scope, "storage-generation-1"); - if (!current.scope().equals(scope)) throw new IllegalStateException("Controlled scope changed"); + if (!current.scope().equals(scope)) + throw new IllegalStateException("Controlled scope changed"); return current; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java index 9974144749..7e59d85b5f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java @@ -104,12 +104,13 @@ void acceptsTickZeroAndRejectsExpiringTimelineMetadata() { CanonicalGameplayRegionRedisKeys.meta( source.tenantId(), source.gameInstanceId(), source.regionId()); seedMeta(redis.admin(), source); - redis.admin().hset( - ascii(metaKey), - ascii("current_tick_id"), - ascii("0"), - ascii("current_tick_state"), - ascii("STAGED")); + redis + .admin() + .hset( + ascii(metaKey), + java.util.Map.of( + ascii("current_tick_id"), ascii("0"), + ascii("current_tick_state"), ascii("STAGED"))); var grant = owner.acquire(source, 7L, Duration.ofSeconds(10), identity("tick-zero")); owner.requireCurrent(grant); @@ -185,14 +186,13 @@ private static void seedMeta( RedisCommands admin, CanonicalGameplayRegionRuntimeStatusRepository.Source source) { admin.hset( - ascii(CanonicalGameplayRegionRedisKeys.meta( - source.tenantId(), source.gameInstanceId(), source.regionId())), - ascii("region_epoch"), - ascii("7"), - ascii("current_tick_id"), - ascii("-1"), - ascii("current_tick_state"), - ascii("APPLIED")); + ascii( + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())), + java.util.Map.of( + ascii("region_epoch"), ascii("7"), + ascii("current_tick_id"), ascii("-1"), + ascii("current_tick_state"), ascii("APPLIED"))); } private static final class RedisFixture implements AutoCloseable { From 1994e6367f277ffb735db530460be334b413368f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:10:33 +1300 Subject: [PATCH 05/36] Place unpublished region migrations after protected realm owner --- ...untime_owner.sql => V1041__canonical_region_runtime_owner.sql} | 0 ...sql => V1042__canonical_region_session_binding_bridge_ack.sql} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename services/game-session-service/src/main/resources/db/migration/{V1037__canonical_region_runtime_owner.sql => V1041__canonical_region_runtime_owner.sql} (100%) rename services/game-session-service/src/main/resources/db/migration/{V1038__canonical_region_session_binding_bridge_ack.sql => V1042__canonical_region_session_binding_bridge_ack.sql} (100%) diff --git a/services/game-session-service/src/main/resources/db/migration/V1037__canonical_region_runtime_owner.sql b/services/game-session-service/src/main/resources/db/migration/V1041__canonical_region_runtime_owner.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V1037__canonical_region_runtime_owner.sql rename to services/game-session-service/src/main/resources/db/migration/V1041__canonical_region_runtime_owner.sql diff --git a/services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql b/services/game-session-service/src/main/resources/db/migration/V1042__canonical_region_session_binding_bridge_ack.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V1038__canonical_region_session_binding_bridge_ack.sql rename to services/game-session-service/src/main/resources/db/migration/V1042__canonical_region_session_binding_bridge_ack.sql From 0beb1c7d8acff0e141d909c5fa0396a4ade5c7e9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:40:35 +1300 Subject: [PATCH 06/36] wip(gameplay): preserve actual region composition and Human runtime fence --- .../game-session-service/runtime-and-data.md | 2 +- .../world-runtime-and-movement.md | 2 + ...eseededActorAssignmentIntegrationTest.java | 41 ++ .../game-session-service/build.gradle.kts | 1 + ...icalGameplayRegionBindingBridgeProofs.java | 7 - ...GameplayRegionRuntimeStatusRepository.java | 11 +- ...n_timeline_canonical_binding_ref_bound.sql | 14 + ...l_human_binding_decision_runtime_fence.sql | 458 ++++++++++++ ...ayDecisionRuntimeFenceIntegrationTest.java | 62 ++ ...indingBridgeRedisOwnerIntegrationTest.java | 1 - ...meplayRegionLeaseOwnerIntegrationTest.java | 27 +- ...GameplayRegionOwnerCompositionFixture.java | 548 ++++++++++++++ .../world-management-service/build.gradle.kts | 4 + ...ationOwnerCompositionCrossServiceTest.java | 686 +++++++++++++++++- 14 files changed, 1832 insertions(+), 32 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1043__region_timeline_canonical_binding_ref_bound.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1044__canonical_human_binding_decision_runtime_fence.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 4932aa541c..d6c88d5821 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -30,7 +30,7 @@ The sections below define the target-state runtime contract. Current implementat - Hidden same-type Game Session recovery within ADR 0013's qualifying conditions remains an implementation or proof gap; the target is to preserve the session through upstream rebind rather than require a player-visible re-`LOGIN` / re-`PLAY` cycle. - The live `startSession` path keeps the Game Session row and runtime projection `STARTING` until World confirms its fenced `PREPARING -> ACTIVE` transition, then records `RUNNING`; failures before an activation attempt use the existing pre-activation cleanup. Once activation may have been issued or committed, an activation error or ambiguous result, or a later local runtime-state save/finalization failure, retains both the runtime projection and local owner row as `STARTING`, and never calls stale-epoch `failPrepared` or deletes either record. A failure proven before any World termination request is issued may restore the prior `RUNNING` row and runtime state while the World remains `ACTIVE`; once a termination request may have been issued, an error or ambiguous result leaves the local row `STOPPING` and runtime projection absent. Confirmed World termination retries local `STOPPED` finalization and never restores `RUNNING`. Durable stable lifecycle-operation identity and lifecycle readback/reconciliation remain unimplemented, so these local fail-closed quarantines are not a replacement for the target durable lifecycle cleanup workflow. - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. -- Canonical region-bootstrap preparation consumes the exact World-owned operational region assignment through the existing workload-pinned lifecycle read, requiring an `ACTIVE` response bound to the complete requested target. This read-only preparation is unregistered and is not assignment allocation, a lifecycle reservation, tick authority, or proof that the current instance-scoped executor consumes the assignment. Game Session must still create a truly absent qualified timeline with `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`), install its actual acquired executor fence atomically, and revalidate the same lease before staging. Handoff and restart must preserve an existing timeline; decimal instance-derived region IDs and lease possession do not establish World assignment authority. +- The prepared, unregistered region owner consumes exact World initial-placement/currentness and lifecycle reads plus Entity’s authenticated runtime reference. It durably prepares a non-admitting initial timeline, conditionally installs complete same-slot initial Redis metadata and the actual region lease, installs the matching SQL executor fence, and records the first-NEW region bridge acknowledgement. The timeline begins at `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`); existing or reset state cannot be adopted as a new timeline. Original retries retain the preparation, source and lease evidence. Source and component tests are present, but the combined actual-owner qualification remains in progress. Forward V1043 preserves the original timeline migration while aligning its binding-reference carrier with the existing 6,144-byte physical codec bound; the canonical three-UUID frame is 133 bytes and cannot fit the former 128-byte check. Forward V1044 makes the existing lease-bound runtime fence consume the exact retained Human completion, matching `COMMITTED` initial attempt, current `OPEN` pointer and audit under the existing runtime row lock. The original run-owned checks remain owner-specific; absence of both qualified sources is refused. Combined actual-owner qualification remains in progress. This is manual owner preparation, not registered tick execution, final player binding or production admission. The [Redis owner contract](../../system-architecture-redis.md#key-naming-and-shard-discipline) remains authoritative for timeline and lease semantics. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). - The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index cf96ce8d71..55f1a10793 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -10,6 +10,8 @@ This is a non-normative implementation tracker for world runtime and movement. C The selected initial-room region read is now local source preparation in the existing World service, with the matching Game Session client and independent lifecycle resolver. It preserves immutable placement storage/results, checks the actual room-to-zone-to-region mappings and current initial room, and keeps every owner manually composed and unregistered. The production query uses the current `room_instance_row_id` column. R584 freshly passes 44 focused unit, controlled mTLS and PostgreSQL cases with zero failures, errors or skips; the native case executes `EXPLAIN` on the exact production query after actual migrations and verifies refusal. That is schema/refusal proof, not a positive authorized region selection. Its aggregate failed solely on the Game Session immutable-protobuf getter exposure warning. R587 applies a narrow suppression justified by generated protobuf immutability and passes the affected enabled main Checkstyle, SpotBugs and formatting checks; it does not repeat or relabel the 44 passing R584 cases. Independent inspection confirms both exact R584 PostgreSQL/Ryuk containers absent. Positive multi-region placement/replay still requires genuine authorized `ACTIVE`, hold, pointer and Entity receipt sources, and the player-binding gate consumer remains unfinished. No original end-to-end Gate testing or admission completion is claimed. +The next local region prerequisite now composes the actual #2973 committed World hold and Game Session initial terminal with Entity assignment/runtime projection, authenticated World placement/current region and lifecycle reads, and the Game Session initial timeline, region lease, SQL fence and durable bridge acknowledgement. Its positive state is owner-produced; Account lease, issuer reservation, deployment incarnation, staging/policy sources, run capability and test PKI remain controlled inputs. R661 executes 85 fresh cases with one failed full-composition case: actual Entity assignment, World placement and lifecycle reads succeed, then the lease-bound SQL runtime fence rejects the real Human completion because it still expects run-owned metadata. The corrected consumer is in forward V1044 and requires the retained Human receipt, matching committed initial attempt and current open pointer; its replacement combined gate is still pending. All 19 exact R661 containers are independently absent. No passing combined result is attributed yet. This does not claim registered tick execution, final player binding or production authority. + The [initial-placement API](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-player-location) is prepared as an unregistered owner service, transport and immediate Game Session client over the existing V1019 storage boundary. It receives the necessary existing canonical hold reader, Game Session terminal client and Common response decoder; their donor source remains preserved. The distinct World-only Entity receipt read supplies persisted assignment provenance without widening the Game Session roster allowlists. The component checkpoint `eee4a18057411d74ed3d25ddf19f44c7a78391e0` passes 65 fresh focused cases across R337, R338 and R340: 53 unit cases, ten controlled physical TLS cases, one actual Entity assignment/receipt-to-current-PostgreSQL case and one current-PostgreSQL World refusal case. R336–R339 retain their failed aggregate and separately passing component attribution. Affected enabled static analysis and formatting checks pass. 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 0ea0fa7404..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 @@ -596,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 = diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 195c9e6711..a7bdc11ad9 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -176,6 +176,7 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures*.class") include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture*.class") + include("net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture*.class") } from("src/main/resources") { include("redis/lua/game-session-issuer-bootstrap-partition-build.lua") diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java index 60016815c5..aec03fa9d0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.gamesession.repository; -import com.google.protobuf.MessageLite; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -146,12 +145,6 @@ static String redisReadbackDigest( return sha256(exact.getBytes(StandardCharsets.US_ASCII)); } - private static String sha256(MessageLite... values) { - byte[][] parts = new byte[values.length][]; - for (int index = 0; index < values.length; index++) parts[index] = values[index].toByteArray(); - return sha256(parts); - } - private static String sha256(byte[]... parts) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index 985336962a..f798f6b304 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.repository; +import java.math.BigDecimal; import java.math.BigInteger; import java.time.Instant; import java.time.LocalDateTime; @@ -137,7 +138,7 @@ TimelinePreparation prepareInitialTimeline( evidence.candidate().identity().runtimeGameInstanceId(), evidence.candidate().bindingRef().bytes(), evidence.candidate().identity().sessionId(), - evidence.candidate().bindingGeneration().toString(), + new BigDecimal(evidence.candidate().bindingGeneration()), source.canonicalRegionId(), source.regionId(), inputs.tenantRegionTag(), @@ -156,8 +157,8 @@ TimelinePreparation prepareInitialTimeline( inputs.incarnationQualificationBytes(), inputs.incarnationDigest(), inputs.absenceProofDigest(), - OffsetDateTime.ofInstant(now, ZoneOffset.UTC), - OffsetDateTime.ofInstant(now, ZoneOffset.UTC)); + java.sql.Timestamp.from(now), + java.sql.Timestamp.from(now)); Record inserted = transaction.fetchOne( "SELECT * FROM " + PREPARATION_TABLE + " WHERE transition_id = ?", @@ -256,7 +257,7 @@ Optional beginInitialTimeline( + PREPARATION_TABLE + " SET phase = 'INITIALIZING', updated_at = ?" + " WHERE initialization_operation_id = ? AND phase = 'PREPARED'", - OffsetDateTime.ofInstant(now, ZoneOffset.UTC), + java.sql.Timestamp.from(now), current.operationId); if (updated != 1) throw unavailable(); return Optional.of( @@ -375,7 +376,7 @@ private TimelinePreparation updatePreparationAfterRedis( leaseTokenCorrelation, executorFence, redisMetaDigest, - OffsetDateTime.ofInstant(now, ZoneOffset.UTC), + java.sql.Timestamp.from(now), current.operationId); if (updated != 1) throw unavailable(); return toTimelinePreparation( diff --git a/services/game-session-service/src/main/resources/db/migration/V1043__region_timeline_canonical_binding_ref_bound.sql b/services/game-session-service/src/main/resources/db/migration/V1043__region_timeline_canonical_binding_ref_bound.sql new file mode 100644 index 0000000000..6f1a65a223 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1043__region_timeline_canonical_binding_ref_bound.sql @@ -0,0 +1,14 @@ +-- The canonical length-prefixed bindingRef for three UUID identifiers is 133 bytes. +-- Preserve the original timeline migration and align its carrier bound with the existing +-- issuer/account physical bindingRef codecs rather than rejecting a valid first-NEW identity. +ALTER TABLE game_session_region_timeline_preparation + DROP CONSTRAINT ck_game_session_region_timeline_preparation_binding; + +ALTER TABLE game_session_region_timeline_preparation + ADD CONSTRAINT ck_game_session_region_timeline_preparation_binding CHECK ( + playable_state_scope = 'SHARED' + AND runtime_game_instance_id > 0 + AND octet_length(binding_ref) BETWEEN 1 AND 6144 + AND session_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND session_id <> '00000000-0000-0000-0000-000000000000' + AND binding_generation > 0); diff --git a/services/game-session-service/src/main/resources/db/migration/V1044__canonical_human_binding_decision_runtime_fence.sql b/services/game-session-service/src/main/resources/db/migration/V1044__canonical_human_binding_decision_runtime_fence.sql new file mode 100644 index 0000000000..492c65436e --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1044__canonical_human_binding_decision_runtime_fence.sql @@ -0,0 +1,458 @@ +-- Permit the immutable canonical Human completion as a second exact source for the existing +-- runtime fence. The run-owned route and every transition immutability check remain unchanged. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_running_runtime_for_lease_bound_binding_decision() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime_row game_instances%ROWTYPE; + approved_first_new_abort boolean := false; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from an existing PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + RETURN NEW; + END IF; + + -- Definitive Account abort is a permanent source, including after cleanup retries. + -- Inventory advancement may retain the source, but may never rewrite its decision. + IF OLD.status = 'ABORTED' AND OLD.admission_orphan_cleanup_id IS NOT NULL THEN + IF (to_jsonb(NEW) - 'inventory_revision') + IS DISTINCT FROM (to_jsonb(OLD) - 'inventory_revision') + OR NEW.inventory_revision < OLD.inventory_revision THEN + RAISE EXCEPTION 'Definitive first-NEW Account abort source is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_terminal_source_immutable'; + END IF; + RETURN NEW; + END IF; + + IF OLD.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND OLD.admission_lease_id IS NOT NULL THEN + IF OLD.status = 'PROVISIONAL' + AND NEW.status = 'ABORTED' + AND OLD.admission_lease_kind = 'NEW_BINDING' + AND OLD.expected_prior_binding_ref IS NULL + AND OLD.expected_prior_binding_generation IS NULL + AND OLD.admission_orphan_cleanup_id IS NULL + AND NEW.admission_orphan_cleanup_id IS NOT NULL + AND NEW.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND NEW.inventory_revision > OLD.inventory_revision THEN + approved_first_new_abort := true; + ELSIF NEW.status NOT IN ('PROVISIONAL', 'AMBIGUOUS') + OR (OLD.status = 'AMBIGUOUS' AND NEW.status <> 'AMBIGUOUS') THEN + RAISE EXCEPTION 'A lease-bound runtime fence cannot be released without definitive first-NEW Account abort evidence' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_terminal_owner_required'; + END IF; + + IF approved_first_new_abort + AND ROW( + NEW.transition_id, NEW.tenant_id, NEW.playable_state_namespace_id, + NEW.character_id, NEW.expected_prior_binding_ref, + NEW.expected_prior_binding_generation, NEW.candidate_binding_ref, + NEW.candidate_binding_generation, NEW.candidate_account_index_fence, + NEW.issuer_reservation_id, NEW.created_at, + NEW.account_coverage_state, NEW.account_coverage_operation_id, + NEW.account_coverage_lifecycle, NEW.account_coverage_operation_fence, + NEW.account_admission_fence_kind, NEW.account_admission_fence, + NEW.historical_account_admission_fence_kind, + NEW.historical_account_admission_fence, NEW.resolved_scope_kind, + NEW.resolved_scope_account_id, NEW.account_coverage_fence, + NEW.account_coverage_generation, NEW.account_inventory_snapshot_revision + ) IS DISTINCT FROM ROW( + OLD.transition_id, OLD.tenant_id, OLD.playable_state_namespace_id, + OLD.character_id, OLD.expected_prior_binding_ref, + OLD.expected_prior_binding_generation, OLD.candidate_binding_ref, + OLD.candidate_binding_generation, OLD.candidate_account_index_fence, + OLD.issuer_reservation_id, OLD.created_at, + OLD.account_coverage_state, OLD.account_coverage_operation_id, + OLD.account_coverage_lifecycle, OLD.account_coverage_operation_fence, + OLD.account_admission_fence_kind, OLD.account_admission_fence, + OLD.historical_account_admission_fence_kind, + OLD.historical_account_admission_fence, OLD.resolved_scope_kind, + OLD.resolved_scope_account_id, OLD.account_coverage_fence, + OLD.account_coverage_generation, OLD.account_inventory_snapshot_revision + ) THEN + RAISE EXCEPTION 'First-NEW abort cannot change its transition, Account-control, or inventory source' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_transition_source_immutable'; + END IF; + + IF NOT approved_first_new_abort + AND NEW.admission_orphan_cleanup_id IS DISTINCT FROM OLD.admission_orphan_cleanup_id THEN + RAISE EXCEPTION 'A lease-bound cleanup identity requires the exact first-NEW Account abort transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_abort_cleanup_identity'; + END IF; + + IF ROW( + NEW.admission_request_id, + NEW.admission_lease_id, + NEW.admission_lease_fence, + NEW.admission_lease_kind, + NEW.admission_lease_digest, + NEW.admission_lease_evidence, + NEW.admission_resume_episode_id, + NEW.admission_expected_old_binding_generation, + NEW.admission_lease_expires_at, + NEW.admission_target_namespace, + NEW.admission_target_tenant_slug, + NEW.admission_target_tenant_id, + NEW.admission_target_world_slug, + NEW.admission_target_world_display_name, + NEW.admission_target_realm_id, + NEW.admission_target_realm_slug, + NEW.admission_target_realm_display_name, + NEW.admission_target_game_session_tenant_id, + NEW.admission_target_game_instance_id, + NEW.admission_target_playable_state_namespace_id, + NEW.admission_target_playable_state_scope, + NEW.admission_target_canonical_game_instance_id, + NEW.admission_target_canonical_version_id, + NEW.admission_target_runtime_version_id, + NEW.admission_target_catalog_revision, + NEW.admission_target_pointer_version, + NEW.admission_target_pointer_snapshot_digest, + NEW.admission_target_active_world_epoch, + NEW.admission_target_initial_admission_request_id, + NEW.admission_target_initial_admission_request_digest, + NEW.admission_target_origin_kind, + NEW.admission_target_expected_prior_pointer_version, + NEW.admission_target_hold_id, + NEW.admission_target_hold_fence, + NEW.admission_target_hold_binding_digest, + NEW.admission_target_audit_event_id, + NEW.admission_target_owner_proof_digest, + NEW.admission_target_owner_proof_outcome, + NEW.admission_target_positive_durable_abort, + NEW.admission_target_terminal_at, + NEW.admission_target_character_creation_policy + ) IS DISTINCT FROM ROW( + OLD.admission_request_id, + OLD.admission_lease_id, + OLD.admission_lease_fence, + OLD.admission_lease_kind, + OLD.admission_lease_digest, + OLD.admission_lease_evidence, + OLD.admission_resume_episode_id, + OLD.admission_expected_old_binding_generation, + OLD.admission_lease_expires_at, + OLD.admission_target_namespace, + OLD.admission_target_tenant_slug, + OLD.admission_target_tenant_id, + OLD.admission_target_world_slug, + OLD.admission_target_world_display_name, + OLD.admission_target_realm_id, + OLD.admission_target_realm_slug, + OLD.admission_target_realm_display_name, + OLD.admission_target_game_session_tenant_id, + OLD.admission_target_game_instance_id, + OLD.admission_target_playable_state_namespace_id, + OLD.admission_target_playable_state_scope, + OLD.admission_target_canonical_game_instance_id, + OLD.admission_target_canonical_version_id, + OLD.admission_target_runtime_version_id, + OLD.admission_target_catalog_revision, + OLD.admission_target_pointer_version, + OLD.admission_target_pointer_snapshot_digest, + OLD.admission_target_active_world_epoch, + OLD.admission_target_initial_admission_request_id, + OLD.admission_target_initial_admission_request_digest, + OLD.admission_target_origin_kind, + OLD.admission_target_expected_prior_pointer_version, + OLD.admission_target_hold_id, + OLD.admission_target_hold_fence, + OLD.admission_target_hold_binding_digest, + OLD.admission_target_audit_event_id, + OLD.admission_target_owner_proof_digest, + OLD.admission_target_owner_proof_outcome, + OLD.admission_target_positive_durable_abort, + OLD.admission_target_terminal_at, + OLD.admission_target_character_creation_policy + ) THEN + RAISE EXCEPTION 'A lease-bound runtime fence decision is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_decision_immutable'; + END IF; + ELSIF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + IF OLD.status <> 'PREPARED' + OR OLD.admission_lease_id IS NOT NULL + OR OLD.admission_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from the exact PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + ELSE + RETURN NEW; + END IF; + + -- This SELECT is in the same transaction as markProvisional's transition UPDATE. Its row + -- lock serializes the decision with stop/replacement/deletion and is retained through commit. + SELECT runtime.* + INTO runtime_row + FROM game_instances runtime + JOIN game_session_canonical_instance_launch launch + ON launch.game_session_tenant_id = runtime.tenant_id + AND launch.game_instance_id = runtime.id + AND launch.game_instance_uuid = runtime.game_instance_uuid + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = NEW.candidate_binding_ref + AND candidate.tenant_id = launch.canonical_tenant_id + AND candidate.runtime_game_instance_id = runtime.id + AND candidate.game_instance_id = runtime.game_instance_uuid + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = launch.target_namespace + AND catalog.canonical_tenant_id = launch.canonical_tenant_id + AND catalog.realm_id = launch.canonical_realm_id + AND catalog.world_slug = launch.world_slug + AND catalog.playable_state_namespace_id = launch.playable_state_namespace_id + AND catalog.catalog_revision = NEW.admission_target_catalog_revision + WHERE runtime.tenant_id = NEW.admission_target_game_session_tenant_id + AND runtime.id = NEW.admission_target_game_instance_id + AND runtime.status = 'RUNNING' + AND runtime.game_instance_uuid = NEW.admission_target_canonical_game_instance_id + AND runtime.version_id = NEW.admission_target_runtime_version_id + AND runtime.game_template_id = launch.game_template_id + AND runtime.launch_descriptor_id = launch.launch_descriptor_id + AND runtime.release_bundle_id = launch.release_bundle_id + AND runtime.generation_config_revision = launch.generation_config_revision + AND runtime.version_state_epoch = launch.version_state_epoch + AND ( + ( + -- Preserve the original run-owned source exactly for its owner route. + runtime.run_owned_start_active_epoch = NEW.admission_target_active_world_epoch + AND runtime.run_owned_start_request_id = launch.control_plane_request_id + AND runtime.run_owned_start_published_release_bundle_ref = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef' + ) + OR ( + -- Human STARTING -> RUNNING rows retain their own immutable positive receipt. They + -- do not copy run-owned launch fields; a missing or conflicting route fails closed. + NEW.admission_target_owner_proof_outcome = 'COMMITTED' + AND NEW.admission_target_positive_durable_abort IS FALSE + AND runtime.run_owned_start_preparing_epoch IS NULL + AND runtime.run_owned_start_active_epoch IS NULL + AND runtime.run_owned_start_request_id IS NULL + AND runtime.run_owned_start_request_digest IS NULL + AND runtime.run_owned_start_published_release_bundle_ref IS NULL + AND EXISTS ( + SELECT 1 + FROM game_session_canonical_human_runtime_completion completion + JOIN game_session_canonical_initial_admission_attempt attempt + ON attempt.target_namespace = completion.target_namespace + AND attempt.initial_admission_request_id = completion.initial_admission_request_id + AND attempt.request_digest = completion.request_digest + AND attempt.canonical_tenant_id = completion.canonical_tenant_id + AND attempt.world_slug = completion.world_slug + AND attempt.realm_id = completion.realm_id + AND attempt.playable_state_namespace_id = completion.playable_state_namespace_id + AND attempt.playable_state_scope = completion.playable_state_scope + AND attempt.canonical_game_instance_id = completion.canonical_game_instance_id + AND attempt.canonical_version_id = completion.canonical_version_id + AND attempt.game_session_tenant_id = completion.game_session_tenant_id + AND attempt.game_instance_id = completion.game_instance_id + AND attempt.expected_catalog_revision = completion.expected_catalog_revision + AND attempt.origin_kind = completion.origin_kind + AND attempt.expected_prior_pointer_version IS NOT DISTINCT FROM + completion.expected_prior_pointer_version + AND attempt.active_lifecycle_epoch = completion.active_lifecycle_epoch + AND attempt.hold_id = completion.hold_id + AND attempt.hold_fence = completion.hold_fence + AND attempt.hold_binding_digest = completion.hold_binding_digest + AND attempt.status = 'COMMITTED' + AND attempt.pointer_id IS NOT NULL + AND attempt.pointer_version = NEW.admission_target_pointer_version + AND attempt.audit_event_id = NEW.admission_target_audit_event_id + AND attempt.commit_proof_digest = NEW.admission_target_owner_proof_digest + AND attempt.terminal_at = NEW.admission_target_terminal_at + JOIN gameplay_admission_pointer pointer + ON pointer.id = attempt.pointer_id + AND pointer.representation_version = 3 + AND pointer.target_namespace = attempt.target_namespace + AND pointer.canonical_tenant_id = attempt.canonical_tenant_id + AND pointer.realm_id = attempt.realm_id + AND pointer.world_slug = attempt.world_slug + AND pointer.playable_state_namespace_id = attempt.playable_state_namespace_id + AND pointer.state_scope = attempt.playable_state_scope + AND pointer.canonical_game_instance_id = attempt.canonical_game_instance_id + AND pointer.canonical_version_id = attempt.canonical_version_id + AND pointer.runtime_version_id = attempt.runtime_version_id + AND pointer.tenant_id = attempt.game_session_tenant_id + AND pointer.game_instance_id = attempt.game_instance_id + AND pointer.pointer_version = attempt.pointer_version + AND pointer.catalog_revision = attempt.expected_catalog_revision + AND pointer.initial_admission_request_id = attempt.initial_admission_request_id + AND pointer.initial_admission_request_digest = attempt.request_digest + AND pointer.initial_admission_origin_kind = attempt.origin_kind + AND pointer.initial_admission_prior_pointer_version IS NOT DISTINCT FROM + attempt.expected_prior_pointer_version + AND pointer.initial_admission_active_epoch = attempt.active_lifecycle_epoch + AND pointer.initial_admission_hold_id = attempt.hold_id + AND pointer.initial_admission_hold_fence = attempt.hold_fence + AND pointer.initial_admission_hold_binding_digest = attempt.hold_binding_digest + AND pointer.admission_state = 'OPEN' + JOIN gameplay_admission_pointer_event event + ON event.id = attempt.audit_event_id + AND event.representation_version = 3 + AND event.target_namespace = attempt.target_namespace + AND event.canonical_tenant_id = attempt.canonical_tenant_id + AND event.realm_id = attempt.realm_id + AND event.world_slug = attempt.world_slug + AND event.playable_state_namespace_id = attempt.playable_state_namespace_id + AND event.state_scope = attempt.playable_state_scope + AND event.canonical_game_instance_id = attempt.canonical_game_instance_id + AND event.canonical_version_id = attempt.canonical_version_id + AND event.runtime_version_id = attempt.runtime_version_id + AND event.tenant_id = attempt.game_session_tenant_id + AND event.game_instance_id = attempt.game_instance_id + AND event.pointer_version = attempt.pointer_version + AND event.catalog_revision = attempt.expected_catalog_revision + AND event.initial_admission_request_id = attempt.initial_admission_request_id + AND event.control_plane_request_id = attempt.initial_admission_request_id + AND event.initial_admission_request_digest = attempt.request_digest + AND event.initial_admission_origin_kind = attempt.origin_kind + AND event.initial_admission_prior_pointer_version IS NOT DISTINCT FROM + attempt.expected_prior_pointer_version + AND event.initial_admission_active_epoch = attempt.active_lifecycle_epoch + AND event.initial_admission_hold_id = attempt.hold_id + AND event.initial_admission_hold_fence = attempt.hold_fence + AND event.initial_admission_hold_binding_digest = attempt.hold_binding_digest + AND event.admission_state = 'OPEN' + AND event.prepared_version_upgrade_id IS NULL + WHERE completion.target_namespace = NEW.admission_target_namespace + AND completion.initial_admission_request_id = + NEW.admission_target_initial_admission_request_id + AND completion.request_digest = + NEW.admission_target_initial_admission_request_digest + AND completion.canonical_tenant_id = NEW.admission_target_tenant_id + AND completion.world_slug = NEW.admission_target_world_slug + AND completion.realm_id = NEW.admission_target_realm_id + AND completion.playable_state_namespace_id = + NEW.admission_target_playable_state_namespace_id + AND completion.playable_state_scope = NEW.admission_target_playable_state_scope + AND completion.canonical_game_instance_id = + NEW.admission_target_canonical_game_instance_id + AND completion.canonical_version_id = NEW.admission_target_canonical_version_id + AND completion.active_lifecycle_epoch = NEW.admission_target_active_world_epoch + AND completion.expected_catalog_revision = NEW.admission_target_catalog_revision + AND completion.origin_kind = NEW.admission_target_origin_kind + AND completion.expected_prior_pointer_version IS NOT DISTINCT FROM + NEW.admission_target_expected_prior_pointer_version + AND completion.hold_id = NEW.admission_target_hold_id + AND completion.hold_fence = NEW.admission_target_hold_fence + AND completion.hold_binding_digest = NEW.admission_target_hold_binding_digest + AND completion.game_session_tenant_id = runtime.tenant_id + AND completion.game_instance_id = runtime.id + AND completion.game_session_tenant_id = NEW.admission_target_game_session_tenant_id + AND completion.game_instance_id = NEW.admission_target_game_instance_id + AND completion.control_plane_request_id = launch.control_plane_request_id + AND completion.captured_starting_row_version = launch.captured_starting_row_version + AND completion.completed_running_row_version = runtime.row_version + AND completion.launch_descriptor_id = launch.launch_descriptor_id + AND completion.descriptor_request_digest = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' + AND completion.descriptor_result_digest = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' + AND completion.release_attestation_digest = + launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' + AND completion.world_lifecycle_state = 'ACTIVE' + AND pointer.target_namespace = NEW.admission_target_namespace + AND pointer.canonical_tenant_id = NEW.admission_target_tenant_id + AND pointer.realm_id = NEW.admission_target_realm_id + AND pointer.world_slug = NEW.admission_target_world_slug + AND pointer.world_display_name = catalog.source_world_display_name + AND pointer.realm_slug = NEW.admission_target_realm_slug + AND pointer.realm_display_name = catalog.realm_display_name + AND pointer.playable_state_namespace_id = + NEW.admission_target_playable_state_namespace_id + AND pointer.state_scope = NEW.admission_target_playable_state_scope + AND pointer.canonical_game_instance_id = + NEW.admission_target_canonical_game_instance_id + AND pointer.canonical_version_id = NEW.admission_target_canonical_version_id + AND pointer.runtime_version_id = NEW.admission_target_runtime_version_id + AND pointer.tenant_id = NEW.admission_target_game_session_tenant_id + AND pointer.game_instance_id = NEW.admission_target_game_instance_id + AND pointer.pointer_version = NEW.admission_target_pointer_version + AND pointer.catalog_revision = NEW.admission_target_catalog_revision + AND pointer.initial_admission_request_id = + NEW.admission_target_initial_admission_request_id + AND pointer.initial_admission_request_digest = + NEW.admission_target_initial_admission_request_digest + AND pointer.initial_admission_origin_kind = NEW.admission_target_origin_kind + AND pointer.initial_admission_prior_pointer_version IS NOT DISTINCT FROM + NEW.admission_target_expected_prior_pointer_version + AND pointer.initial_admission_active_epoch = NEW.admission_target_active_world_epoch + AND pointer.initial_admission_hold_id = NEW.admission_target_hold_id + AND pointer.initial_admission_hold_fence = NEW.admission_target_hold_fence + AND pointer.initial_admission_hold_binding_digest = + NEW.admission_target_hold_binding_digest + AND pointer.admission_state = 'OPEN' + AND pointer.visible = catalog.visible + AND pointer.public_production_realm = catalog.public_production + AND pointer.character_creation_policy = + NEW.admission_target_character_creation_policy + AND pointer.requires_character_selection IS NULL + AND pointer.last_updated_by = 'game-session-canonical-initial-admission' + AND pointer.last_update_reason = 'World-held initial admission' + AND pointer.prepared_version_upgrade_id IS NULL + ) + ) + ) + AND launch.target_namespace = NEW.admission_target_namespace + AND launch.canonical_tenant_id = NEW.admission_target_tenant_id + AND launch.canonical_realm_id = NEW.admission_target_realm_id + AND catalog.tenant_slug = NEW.admission_target_tenant_slug + AND catalog.world_slug = NEW.admission_target_world_slug + AND catalog.source_world_display_name = NEW.admission_target_world_display_name + AND catalog.realm_slug = NEW.admission_target_realm_slug + AND catalog.realm_display_name = NEW.admission_target_realm_display_name + AND launch.playable_state_namespace_id = NEW.admission_target_playable_state_namespace_id + AND launch.playable_state_scope = NEW.admission_target_playable_state_scope + AND launch.version_id = NEW.admission_target_runtime_version_id + AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.admission_target_canonical_version_id::text + AND catalog.visible + AND catalog.public_production + AND catalog.state_scope = 'SHARED' + AND launch.public_production + AND launch.playable_state_scope = 'SHARED' + AND launch.captured_starting_row_version <= runtime.row_version + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'targetNamespace' + = launch.target_namespace + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'controlPlaneRequestId' + = launch.control_plane_request_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'canonicalTenantId' + = launch.canonical_tenant_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'worldSlug' + = launch.world_slug + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'gameTemplateId' + = launch.game_template_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'launchDescriptorId' + = launch.launch_descriptor_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionId' + = launch.version_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'releaseBundleId' + = launch.release_bundle_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'generationConfigRevision' + = launch.generation_config_revision + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionStateEpoch' + = launch.version_state_epoch::text + FOR UPDATE OF runtime; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Lease-bound binding decision requires the exact current RUNNING launch row and candidate identity' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_exact_running_launch_required'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java index 3abd1c8598..4da5a81f36 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java @@ -253,6 +253,68 @@ void stoppedRuntimeCannotAcquireLeaseBoundBindingFence() { } } + @Test + void runningRuntimeWithoutRetainedHumanCompletionOrRunOwnedMetadataCannotAcquireFence() { + String schema = "gs_runtime_fence_unowned_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); + byte[] candidateRef = seedCandidateAndPreparedTransition(dsl, target, CandidateMismatch.NONE); + + assertThat( + dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1," + + " run_owned_start_request_id = NULL, run_owned_start_request_digest = NULL," + + " run_owned_start_published_release_bundle_ref = NULL," + + " run_owned_start_preparing_epoch = NULL, run_owned_start_active_epoch = NULL" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .isEqualTo(1); + + assertThatThrownBy(() -> markProvisional(dsl, target, candidateRef)) + .hasMessageContaining("exact current RUNNING launch row and candidate identity"); + + var runtimeReadback = + dsl.fetchSingle( + "SELECT status, row_version, run_owned_start_request_id," + + " run_owned_start_request_digest, run_owned_start_published_release_bundle_ref," + + " run_owned_start_preparing_epoch, run_owned_start_active_epoch" + + " FROM game_instances WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + assertThat(runtimeReadback.get("status", String.class)).isEqualTo("RUNNING"); + assertThat(runtimeReadback.get("row_version", Long.class)).isEqualTo(2L); + assertThat(runtimeReadback.get("run_owned_start_request_id", String.class)).isNull(); + assertThat(runtimeReadback.get("run_owned_start_request_digest", String.class)).isNull(); + assertThat(runtimeReadback.get("run_owned_start_published_release_bundle_ref", String.class)) + .isNull(); + assertThat(runtimeReadback.get("run_owned_start_preparing_epoch", Long.class)).isNull(); + assertThat(runtimeReadback.get("run_owned_start_active_epoch", Long.class)).isNull(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) AS actual_count" + + " FROM game_session_canonical_human_runtime_completion" + + " WHERE target_namespace = ? AND initial_admission_request_id = ?", + target.targetNamespace(), + target.initialAdmissionRequestId()) + .get("actual_count", Long.class)) + .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE candidate_binding_ref = ?", + candidateRef) + .get("status", String.class)) + .isEqualTo("PREPARED"); + } finally { + dropSchema(schema); + } + } + @Test void mismatchedCandidateTenantRuntimeOrCanonicalInstanceCannotAcquireFence() { String schema = "gs_runtime_fence_candidate_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java index 4f5deeb4b6..267f8f1697 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java @@ -112,7 +112,6 @@ void sameGrantAppliesAndReadsBackExactTypedEntityBindingThenPreservesForeignStat String key = CanonicalGameplayRegionRedisKeys.sessionBinding( TENANT_ID, GAME_INSTANCE_ID, REGION_ID, actor.runtimeEntityId().value()); - String meta = CanonicalGameplayRegionRedisKeys.meta(TENANT_ID, GAME_INSTANCE_ID, REGION_ID); var absent = owner.probeSessionBinding( grant, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index dcb3ebb999..6733a16df9 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -35,6 +36,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClient; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; @@ -202,14 +204,19 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(statusRepository.find(qualifiedSource)).isEmpty(); world.setAfterRead(2, incarnationSource::changeRecoveryEvidence); - assertThatThrownBy(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())) - .isInstanceOf(IllegalStateException.class); + Throwable recoveryDriftFailure = + catchThrowable(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())); + assertThat(recoveryDriftFailure).isInstanceOf(IllegalStateException.class); assertThat(statusRepository.find(qualifiedSource)).isEmpty(); Record retainedPreparation = dsl.fetchOne( "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", TRANSITION_ID); - assertThat(retainedPreparation).isNotNull(); + assertThat(retainedPreparation) + .as( + "Timeline preparation must precede recovery drift; original failure: %s", + recoveryDriftFailure.getCause()) + .isNotNull(); assertThat(retainedPreparation.get("phase", String.class)).isEqualTo("REDIS_INITIALIZED"); UUID initialTimelineOperationId = retainedPreparation.get("initialization_operation_id", UUID.class); @@ -464,7 +471,7 @@ private static CanonicalGameplayRegionIncarnationSource.StableEvidence stableInc List.of("node-a"), "redis-build-1", "script-registry-v1", - "a".repeat(64), + "sha256:" + "a".repeat(64), "READY", "boot-1", "startup-1", @@ -562,6 +569,12 @@ private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidenc var candidate = mock(CanonicalGameplayBindingInventoryEntry.class); var identity = mock(CanonicalGameplayBindingIdentity.class); var target = request.getExpectedTarget(); + UUID gameInstanceId = UUID.fromString(target.getGameInstanceId()); + UUID sessionId = + UUID.nameUUIDFromBytes( + ("region-owner-session-" + TRANSITION_ID).getBytes(StandardCharsets.UTF_8)); + CanonicalGameplayBindingRef bindingRef = + CanonicalGameplayBindingRef.of(tenantId, gameInstanceId, sessionId.toString()); when(evidence.transition()).thenReturn(transition); when(evidence.candidate()).thenReturn(candidate); when(transition.status()) @@ -569,12 +582,16 @@ private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidenc when(transition.transitionId()).thenReturn(TRANSITION_ID); when(candidate.lifecycle()) .thenReturn(CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL); + when(candidate.bindingRef()).thenReturn(bindingRef); + when(candidate.bindingGeneration()).thenReturn(BigInteger.ONE); when(candidate.transitionId()).thenReturn(TRANSITION_ID); when(candidate.identity()).thenReturn(identity); when(identity.accountId()).thenReturn(UUID.fromString(request.getCanonicalAccountUuid())); when(identity.characterId()).thenReturn(UUID.fromString(request.getCharacterUuid())); when(identity.tenantId()).thenReturn(tenantId); - when(identity.gameInstanceId()).thenReturn(UUID.fromString(target.getGameInstanceId())); + when(identity.gameInstanceId()).thenReturn(gameInstanceId); + when(identity.runtimeGameInstanceId()).thenReturn(23L); + when(identity.sessionId()).thenReturn(sessionId.toString()); when(identity.playableStateNamespaceId()) .thenReturn(UUID.fromString(target.getPlayableStateNamespaceUuid())); when(identity.playableStateScope()).thenReturn("SHARED"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java new file mode 100644 index 0000000000..ca5e7c13f9 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -0,0 +1,548 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import org.jooq.DSLContext; + +/** + * Test-only wrapper for the package-private Game Session region owners. It starts from an actual + * current World/Entity source and the actual SQL transition repository; only the upstream Account + * lease carrier, issuer reservation, and stable Redis incarnation are controlled test evidence. + */ +public final class CanonicalGameplayRegionOwnerCompositionFixture { + private static final String REDIS_PRINCIPAL = "gamesession_region_owner_app"; + private static final String REDIS_PASSWORD = UUID.randomUUID().toString(); + private static final String REGION_ATTESTATION = "controlled-region-owner-composition"; + + private CanonicalGameplayRegionOwnerCompositionFixture() {} + + /** + * Creates one real first-NEW provisional candidate from the exact placement selector, installs + * the first region timeline and SQL fence, then retries the same binding bridge as a lost reply. + */ + public static Proof installAndBridge( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) + throws Exception { + UUID transitionId = UUID.randomUUID(); + UUID sessionId = UUID.randomUUID(); + var resolved = worldRegionResolver.resolve(worldRequest); + requireExactCurrentTarget(worldRequest, currentTarget); + var identity = + new CanonicalGameplayBindingIdentity( + UUID.fromString(worldRequest.getCanonicalAccountUuid()), + currentTarget.canonicalTenantId(), + currentTarget.playableStateNamespaceId(), + UUID.fromString(worldRequest.getCharacterUuid()), + currentTarget.playableStateScope(), + currentTarget.canonicalGameInstanceId(), + currentTarget.gameInstanceId(), + sessionId.toString(), + resolved.operationalRegionId(), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(64)); + + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + establishActualLegacyDisposition(dsl); + var transitionRequest = + new CanonicalGameplayBindingTransitionRequest( + transitionId, + UUID.randomUUID(), + identity, + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE), + null, + null); + var prepared = inventory.prepare(transitionRequest); + AccountGameplayAdmissionLeaseEvidence lease = + controlledNewBindingLease(identity, currentTarget, prepared.bindingGeneration()); + var decision = + new CanonicalGameplayAdmissionDecision( + transitionId, lease, identity, prepared.bindingGeneration(), null, currentTarget); + inventory.markProvisional(inventory.readProvisionalCasEvidence(transitionId), decision); + + try (var redis = RegionRedis.open(redisHost, redisPort)) { + var scriptCatalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayRegionLeaseRedisScriptContribution())); + var stableSource = new ControlledStableIncarnationSource(); + var runtimeIdentity = + new RuntimeIdentity( + "game-session-service", + "region-owner-composition", + "localhost", + Instant.now(), + "test", + "test", + "controlled-test-image"); + var bridgeOwner = + CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( + dsl, + redis.ownerClient(), + scriptCatalog, + stableSource, + worldRegionResolver, + entityReferenceClient, + runtimeIdentity, + Duration.ofSeconds(30), + Clock.systemUTC()); + var installation = bridgeOwner.installForTransition(transitionId, worldRequest); + var firstAcknowledgement = bridgeOwner.bridge(installation); + var lostReplyRetry = bridgeOwner.bridge(installation); + var acknowledged = firstAcknowledgement.obligation(); + var replayed = lostReplyRetry.obligation(); + if (!acknowledged.equals(replayed) + || acknowledged.status() + != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { + throw new IllegalStateException("Exact first-NEW region bridge retry changed its SQL ACK"); + } + var status = + new CanonicalGameplayRegionRuntimeStatusRepository(dsl) + .find(installation.source) + .orElseThrow(); + if (status.paused() + || status.regionEpoch() != 1L + || status.lastCommittedTickId() != -1L + || !"game-session-service".equals(status.ownerService())) { + throw new IllegalStateException("Initial region SQL fence is not the expected live owner"); + } + byte[] currentTickState = + redis + .admin() + .hget( + ascii( + CanonicalGameplayRegionRedisKeys.meta( + identity.tenantId(), + identity.gameInstanceId(), + resolved.canonicalRegionInstanceId())), + ascii("current_tick_state")); + if (!Arrays.equals(currentTickState, ascii("APPLIED"))) { + throw new IllegalStateException("Canonical Redis initial timeline metadata is absent"); + } + return new Proof( + transitionId, + sessionId, + identity.regionId(), + resolved.canonicalRegionInstanceId(), + status.lifecycleEpoch(), + status.lifecycleRowVersion(), + status.regionEpoch(), + status.executorFence(), + acknowledged.bridgeOperationId(), + acknowledged.runtimeEntityId(), + acknowledged.entityProjectionGeneration(), + acknowledged.entityProjectionFence(), + acknowledged.entityReferenceDigest(), + acknowledged.worldSourceDigest(), + acknowledged.redisReadbackDigest(), + acknowledged.inventoryRevision(), + acknowledged.acknowledgedAt(), + acknowledged.equals(replayed)); + } + } + + private static void requireExactCurrentTarget( + CanonicalInitialPlayerLocationRequest worldRequest, CanonicalPlayableTarget target) { + var expected = worldRequest.getExpectedTarget(); + if (!target.targetNamespace().equals("firemud") + || !target.canonicalTenantId().toString().equals(expected.getCanonicalTenantUuid()) + || !target.realmId().toString().equals(expected.getRealmUuid()) + || !target.worldSlug().equals(expected.getWorldSlug()) + || !target.realmSlug().equals(expected.getRealmSlug()) + || !target.canonicalGameInstanceId().toString().equals(expected.getGameInstanceId()) + || target.catalogRevision() != expected.getCatalogRevision() + || !target.canonicalVersionId().toString().equals(expected.getCanonicalVersionUuid()) + || !target + .playableStateNamespaceId() + .toString() + .equals(expected.getPlayableStateNamespaceUuid()) + || !target + .playableStateScope() + .equals( + expected.getPlayableStateScope() + == net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED + ? "SHARED" + : expected.getPlayableStateScope() + == net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_ISOLATED + ? "ISOLATED" + : "UNSPECIFIED")) { + throw new IllegalArgumentException("World placement is not the exact current GS target"); + } + } + + private static AccountGameplayAdmissionLeaseEvidence controlledNewBindingLease( + CanonicalGameplayBindingIdentity identity, + CanonicalPlayableTarget target, + BigInteger bindingGeneration) { + Instant now = Instant.now(); + long nowMillis = now.toEpochMilli(); + long nowSeconds = now.getEpochSecond(); + UUID requestId = UUID.randomUUID(); + UUID leaseId = UUID.randomUUID(); + String account = identity.accountId().toString(); + String tenant = identity.tenantId().toString(); + + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", requestId.toString()); + carrier.put("leaseId", leaseId.toString()); + carrier.put("leaseFence", "1"); + carrier.put("leaseKind", "NEW_BINDING"); + + Map scope = new LinkedHashMap<>(); + scope.put("accountId", account); + scope.put("tenantId", tenant); + scope.put("realmId", target.realmId().toString()); + scope.put("worldSlug", target.worldSlug()); + scope.put("realmSlug", target.realmSlug()); + scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + scope.put("playableStateScope", target.playableStateScope()); + scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + scope.put("characterId", identity.characterId().toString()); + scope.put("sessionId", identity.sessionId()); + scope.put("bindingGeneration", bindingGeneration.toString()); + scope.put("catalogRevision", Long.toString(target.catalogRevision())); + scope.put("pointerVersion", Long.toString(target.pointerVersion())); + scope.put("regionId", identity.regionId().toString()); + scope.put("regionEpoch", identity.regionEpoch().toString()); + carrier.put("bindingScope", scope); + + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(tenant, "1"), + "membershipAuthorityGeneration", Map.of(tenant, "1"), + "privateRealmGrantVersions", List.of())); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", "ACTIVE", + "membershipVersion", Map.of(tenant, "1"), + "membershipAuthorityGeneration", "1")); + + String prefix = "account:auth-authority:v1:"; + List> checkpoints = new ArrayList<>(); + for (var coordinate : + List.of( + Map.entry(prefix + "account/" + account, "0"), + Map.entry(prefix + "issuer/" + GameSessionAccountDelegationProfile.ISSUER, "0"), + Map.entry(prefix + "membership/" + account + "/" + tenant, "1"), + Map.entry(prefix + "tenant/" + tenant, "1"))) { + checkpoints.add( + Map.of("outboxStreamKey", coordinate.getKey(), "outboxSequence", coordinate.getValue())); + } + checkpoints.sort(Comparator.comparing(value -> value.get("outboxStreamKey"))); + carrier.put("outboxCheckpoints", checkpoints); + + carrier.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", account), + Map.entry("operationId", UUID.randomUUID().toString()), + Map.entry("issuanceRequestId", UUID.randomUUID().toString()), + Map.entry("tokenJti", UUID.randomUUID().toString()), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", GameSessionAccountDelegationProfile.PROFILE), + Map.entry("issuedAt", Long.toString(nowSeconds)), + Map.entry("notBefore", Long.toString(nowSeconds)), + Map.entry("expiresAt", Long.toString(nowSeconds + 30)))); + carrier.put("evaluatedAt", Long.toString(nowMillis)); + carrier.put("expiresAt", Long.toString(nowMillis + 10_000L)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + /** Actual migration state machine over the selected controlled empty legacy cohort. */ + private static void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "controlled-cluster-uid", + "controlled-namespace-uid", + "controlled-producer-pod-uid", + "controlled-container-id", + "controlled-node-uid", + "123456789", + 42L, + "controlled-postgres-volume-uid", + "controlled-redis-run-id", + "controlled-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storageIdentity.equals(expected)) { + throw new IllegalStateException("Controlled source storage identity changed"); + } + } + }; + var migrated = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + requireEmptyCanonical(canonical); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + requireEmptyCanonical(canonical); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); + if (migrated.state() != CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + throw new IllegalStateException("Actual legacy migration owner did not publish VERIFIED"); + } + } + + private static void requireEmptyCanonical( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot + canonical) { + if (!canonical.bindings().isEmpty() + || !canonical.reservations().isEmpty() + || !canonical.transitions().isEmpty() + || !canonical.accountIndexObligations().isEmpty() + || !canonical.issuerIndexObligations().isEmpty() + || !canonical.regionBridgeObligations().isEmpty()) { + throw new IllegalStateException("Controlled empty-cohort collaborator found GS state"); + } + } + + private static CanonicalGameplayRegionIncarnationSource.StableEvidence + controlledStableIncarnation(CanonicalGameplayRegionIncarnationSource.RegionScope scope) { + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-region-deployment", + "deployment-generation-1", + List.of("node-a"), + "redis-build-1", + "script-registry-v1", + "sha256:" + "a".repeat(64), + "READY", + "boot-1", + "startup-1", + "storage-generation-1", + "aof-1"); + return CanonicalGameplayRegionIncarnationSource.StableEvidence.fromCurrentSource( + scope, + REGION_ATTESTATION, + "b".repeat(64), + deployment, + "c".repeat(64), + "d".repeat(64), + true, + "controlled-non-reset-profile-v1", + "e".repeat(64), + true, + "f".repeat(64), + true, + "1".repeat(64)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + public record Proof( + UUID transitionId, + UUID sessionId, + UUID operationalRegionId, + UUID canonicalRegionId, + long lifecycleEpoch, + long lifecycleRowVersion, + long regionEpoch, + BigInteger executorFence, + UUID bridgeOperationId, + Long runtimeEntityId, + Long entityProjectionGeneration, + Long entityProjectionFence, + String entityReferenceDigest, + String worldSourceDigest, + String redisReadbackDigest, + BigInteger acknowledgedInventoryRevision, + Instant acknowledgedAt, + boolean exactLostReplyRetry) {} + + private static final class ControlledStableIncarnationSource + implements CanonicalGameplayRegionIncarnationSource { + @Override + public StableEvidence readCurrent(RegionScope scope) { + return controlledStableIncarnation(scope); + } + } + + private static final class RegionRedis implements AutoCloseable { + private final RedisClient administrator; + private final RedisClient ownerClient; + private final StatefulRedisConnection adminConnection; + private final RedisCommands admin; + + private RegionRedis( + RedisClient administrator, + RedisClient ownerClient, + StatefulRedisConnection adminConnection, + RedisCommands admin) { + this.administrator = administrator; + this.ownerClient = ownerClient; + this.adminConnection = adminConnection; + this.admin = admin; + } + + static RegionRedis open(String host, int port) { + var baseUri = RedisURI.Builder.redis(host, port).withTimeout(Duration.ofSeconds(5)).build(); + RedisClient administrator = RedisClient.create(baseUri); + StatefulRedisConnection adminConnection = + administrator.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + admin.aclSetuser( + REDIS_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(REDIS_PASSWORD) + .keyPattern("tick-executor-lease:*") + .keyPattern("tick:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HSET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRE)); + RedisURI ownerUri = + RedisURI.Builder.redis(host, port) + .withTimeout(Duration.ofSeconds(5)) + .withAuthentication(REDIS_PRINCIPAL, REDIS_PASSWORD) + .build(); + return new RegionRedis(administrator, RedisClient.create(ownerUri), adminConnection, admin); + } + + RedisClient ownerClient() { + return ownerClient; + } + + RedisCommands admin() { + return admin; + } + + @Override + public void close() { + adminConnection.close(); + ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } +} diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index b160ad6920..a703fd85e0 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -27,6 +27,10 @@ dependencies { "crossServiceTestImplementation", project(mapOf("path" to ":game-session-service", "configuration" to "gameSessionClassesProof")) ) + add( + "crossServiceTestImplementation", + project(mapOf("path" to ":entity-management-service", "configuration" to "entityClassesProof")) + ) add("crossServiceTestImplementation", testFixtures(project(":common-test-support"))) add("crossServiceTestImplementation", "io.grpc:grpc-util:${libs.versions.grpc.get()}") } 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 57145cb695..bc4471d99a 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 @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.awaitility.Awaitility.await; +import static org.mockito.Mockito.when; import com.google.protobuf.Empty; import com.google.protobuf.util.JsonFormat; @@ -11,6 +12,7 @@ import io.grpc.CallOptions; import io.grpc.Context; import io.grpc.ForwardingServerCall; +import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Server; @@ -22,8 +24,10 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.protobuf.ProtoUtils; import io.grpc.stub.ClientCalls; import io.grpc.stub.ServerCalls; @@ -33,6 +37,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; @@ -47,6 +52,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -73,6 +79,8 @@ import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationHistoricalReadService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementService; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; import net.firedevops.firemud.common.account.startsession.AccountInitialAdmissionSettlementReadInput; import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionClient; import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; @@ -109,9 +117,11 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceReadClient; +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.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; @@ -130,20 +140,40 @@ import net.firedevops.firemud.common.world.GrpcWorldOriginalStartSessionProtectedActivationClient; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadClient; +import net.firedevops.firemud.entitymanagement.config.PreseededActorAssignmentConfiguration; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAccountIdentityPort; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload.ActorKind; +import net.firedevops.firemud.entitymanagement.service.PreseededActorStagingEligibilityPort; +import net.firedevops.firemud.entitymanagement.service.impl.CanonicalPreseededActorAssignmentGrpcService; +import net.firedevops.firemud.entitymanagement.v1.AssignPreseededActorRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPreseededActorAssignmentServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClient; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import net.firedevops.firemud.gamesession.client.GrpcAccountStartSessionAdmissionProtectionClient; import net.firedevops.firemud.gamesession.client.WorldCanonicalInitialAdmissionHoldClient; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; import net.firedevops.firemud.gamesession.repository.AccountInitialAdmissionProtectionBindingRepository; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRegionOwnerCompositionFixture; import net.firedevops.firemud.gamesession.repository.CanonicalHumanRuntimeCompletionRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; @@ -157,6 +187,9 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.service.AccountInitialAdmissionSettlementReadService; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalRegionBootstrapAssignmentResolver; import net.firedevops.firemud.gamesession.service.impl.AccountInitialAdmissionSettlementReadGrpcService; import net.firedevops.firemud.gamesession.service.impl.AuthenticatedCanonicalInitialAdmissionWorldVerifier; import net.firedevops.firemud.gamesession.service.impl.CanonicalGameInstanceLaunchAssociationReadGrpcService; @@ -168,6 +201,7 @@ import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.client.EntityPreseededActorAssignmentReceiptClient; import net.firedevops.firemud.worldmanagement.client.GameSessionCanonicalInitialAdmissionOwnerClient; import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionCanonicalInitialAdmissionOwnerClient; import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository; @@ -178,6 +212,7 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import net.firedevops.firemud.worldmanagement.service.impl.WorldDraftDesignDigestServiceImpl; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; @@ -191,6 +226,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -198,6 +234,11 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.ssl.SslManagerBundle; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -206,6 +247,8 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; @@ -223,10 +266,15 @@ * operation/terminal/release and complete-launch inputs, logging claims, creator/environment/signer * provisioning, and ephemeral PKI are controlled upstream evidence. This proves World owner storage * with those stipulated inputs, not a genuine GDS producer or authority. The positive composition - * additionally proves actual Account participation settlement, authenticated activation protection, - * guarded World ACTIVE storage, and exact Account activation settlement. No genuine Human - * issuer/environment, registered endpoint, runtime admission or Entity proof is asserted. The small - * test-only World socket invokes the typed preparation owner directly, not assembly. + * additionally proves actual Account participation and admission settlement, authenticated + * activation protection, guarded World ACTIVE storage, exact Account activation settlement, actual + * Entity assignment/projection, authenticated World placement/currentness reads, and the selected + * Game Session first-NEW region grant, SQL fence, and durable bridge acknowledgement. Account + * staging and published-policy source evidence, the Account lease carrier, issuer reservation, + * stable Redis deployment-incarnation evidence, and loopback PKI remain controlled test inputs; + * this does not establish genuine Human issuer/environment authority, production PKI, registered + * endpoint activation, or runtime admission. The small test-only World socket invokes the typed + * preparation owner directly, not assembly. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -2926,9 +2974,600 @@ private static void exerciseCoupledCanonicalInitialAdmission( var finalWorldState = worldHoldOwner.readState(identity, lifecycleRequest).orElseThrow(); assertThat(finalWorldState.holdStatus().name()).isEqualTo("COMMITTED"); + composeActualEntityWorldRegionPrerequisite( + gs, + world, + proofDirectory, + pki, + factory, + gsEndpoints, + association, + identity, + request, + accountUuid); } } + /** + * Extends the retained 2973 COMMITTED hold through actual Entity assignment, World placement, + * authenticated current World reads, and the selected Game Session first-NEW region owners. + * Account staging and published-policy evidence plus the one-use run capability remain controlled + * local test inputs; the selected OPEN route and terminal are read from actual Game Session SQL. + */ + private static void composeActualEntityWorldRegionPrerequisite( + Database gs, + Database world, + Path proofDirectory, + WorldOriginalStartSessionPreparationProofPki worldPki, + GrpcChannelFactory channels, + ServiceEndpointsProperties gsEndpoints, + WorldCanonicalInstanceAssociation association, + WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity, + CanonicalInitialAdmissionRequest admissionRequest, + UUID accountUuid) + throws Exception { + var catalogs = new GameSessionCanonicalRealmCatalogRepository(gs.dsl()); + var admissionOwner = + new CanonicalInitialAdmissionRepository( + gs.dsl(), + catalogs, + new GameSessionCanonicalAdmissionPointerRepository( + gs.dsl(), catalogs, new GameplayAdmissionPointerEventRepository(gs.dsl()))); + var launchOwner = new CanonicalGameInstanceLaunchAssociationRepository(gs.dsl(), NAMESPACE); + var routeReader = + new CanonicalPlayerRouteReadService(NAMESPACE, catalogs, admissionOwner, launchOwner); + CanonicalPlayableTarget currentTarget = + routeReader.readCurrentTarget(association.identity().canonicalTenantId()); + assertThat(currentTarget.ownerProofOutcome()) + .isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(currentTarget.pointerVersion()).isEqualTo(1L); + assertThat(currentTarget.holdId()).isEqualTo(holdIdentity.holdId()); + assertThat(currentTarget.holdFence()).isEqualTo(holdIdentity.holdFence()); + assertThat(currentTarget.initialAdmissionRequestId()) + .isEqualTo(admissionRequest.initialAdmissionRequestId()); + assertThat(currentTarget.initialAdmissionRequestDigest()) + .isEqualTo(admissionRequest.requestDigest()); + assertThat(currentTarget.activeWorldEpoch()) + .isEqualTo(holdIdentity.request().activeLifecycleEpoch()); + assertThat(currentTarget.canonicalGameInstanceId()) + .isEqualTo(association.identity().canonicalGameInstanceId()); + + UUID assignmentUuid = UUID.randomUUID(); + String displayName = "Region Owner Player"; + String frozenPolicyDigest = "d".repeat(64); + String releaseBundleRef = association.worldPrepareFields().publishedReleaseBundleRef(); + var assignmentTarget = + new PreseededActorAssignmentExpectedTarget( + currentTarget.canonicalTenantId(), + currentTarget.realmId(), + currentTarget.worldSlug(), + currentTarget.realmSlug(), + currentTarget.canonicalGameInstanceId().toString(), + currentTarget.catalogRevision(), + currentTarget.canonicalVersionId(), + frozenPolicyDigest, + currentTarget.playableStateNamespaceId(), + releaseBundleRef, + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED); + var assignmentRequest = + new PreseededActorAssignmentRequest( + assignmentUuid, + accountUuid, + new PreseededActorCorePayload(ActorKind.PLAYER, displayName), + assignmentTarget); + + var entityPkiDirectory = + Files.createDirectories(proofDirectory.resolve("entity-region-owner-pki")); + var entityPki = + LoopbackMtlsTestPki.create( + entityPkiDirectory, + "Controlled Entity region-owner composition test CA", + new IdentitySpec( + "entity-server", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service", + true), + new IdentitySpec( + "game-session-client", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + false), + new IdentitySpec( + "world-management-client", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", + false)); + Files.setPosixFilePermissions( + entityPkiDirectory.resolve("test-ca.crt"), + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + String trustRootFingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(entityPki.caCertificate().getEncoded())); + Path capabilityDirectory = + Files.createDirectories(proofDirectory.resolve("entity-region-capability")); + Files.setPosixFilePermissions( + capabilityDirectory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE)); + Path capability = capabilityDirectory.resolve("assignment-grant.json"); + writeRegionAssignmentCapability( + capability, + assignmentRequest, + "region-owner-composition", + "firemud-region-owner-composition", + trustRootFingerprint); + + var managers = Mockito.mock(SslManagerBundle.class); + when(managers.getTrustManagers()) + .thenReturn(entityPki.trustManagerFactory().getTrustManagers()); + var activeBundle = Mockito.mock(SslBundle.class); + when(activeBundle.getManagers()).thenReturn(managers); + var activeBundles = Mockito.mock(SslBundles.class); + when(activeBundles.getBundle("firemud-grpc")).thenReturn(activeBundle); + var entityConfiguration = new PreseededActorAssignmentConfiguration(); + var assignmentAuthority = + entityConfiguration.runOwnedPreseededAssignmentAuthorityFromCapability( + capability.toString(), + "region-owner-composition", + "firemud-region-owner-composition", + NAMESPACE, + entityPkiDirectory.resolve("test-ca.crt").toString(), + "firemud-grpc", + activeBundles); + + var accountIdentity = + new RuntimeAccountIdentityEvidence( + 1, NAMESPACE, assignmentUuid, accountUuid, 23L, "ACCOUNT_REPOSITORY_INSERT"); + var staging = + AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + assignmentUuid, + accountUuid, + currentTarget.canonicalTenantId(), + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + java.time.Instant.now(), + "ACCOUNT_REPOSITORY_INSERT", + "ACTIVE", + "ACTIVE", + true, + "EXPLICIT_JOIN", + 1L, + 1L, + "FRESH_GAME_DESIGN", + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + 1L, + UUID.randomUUID(), + "sha256:" + "b".repeat(64), + false); + var currentEntityTarget = + new PreseededActorAssignmentOwnerEvidence( + assignmentUuid, + accountUuid, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + staging.observedAt(), + staging.membershipAuthorityGeneration(), + staging.eligibilityDecisionDigest(), + currentTarget.canonicalTenantId(), + currentTarget.realmId(), + currentTarget.worldSlug(), + currentTarget.realmSlug(), + currentTarget.canonicalGameInstanceId().toString(), + currentTarget.catalogRevision(), + currentTarget.canonicalVersionId(), + frozenPolicyDigest, + currentTarget.playableStateNamespaceId(), + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + staging.authoritySnapshotDigest(), + currentTarget.ownerProofDigest().substring("sha256:".length()), + releaseBundleRef); + PreseededActorAccountIdentityPort identityPort = + (requestedAccount, requestedAssignment) -> { + if (!accountUuid.toString().equals(requestedAccount) + || !assignmentUuid.toString().equals(requestedAssignment)) { + throw new IllegalStateException("Controlled Account identity selector changed"); + } + return accountIdentity; + }; + PreseededActorStagingEligibilityPort stagingPort = + (requestedAccount, requestedTenant, requestedAssignment) -> { + if (!accountUuid.toString().equals(requestedAccount) + || !currentTarget.canonicalTenantId().toString().equals(requestedTenant) + || !assignmentUuid.toString().equals(requestedAssignment)) { + throw new IllegalStateException("Controlled Account staging selector changed"); + } + return staging; + }; + PreseededActorAssignmentOwnerEvidencePort targetPort = + (request, observedIdentity, observedStaging) -> { + if (!assignmentRequest.equals(request) + || !accountIdentity.equals(observedIdentity) + || !staging.equals(observedStaging)) { + throw new IllegalStateException("Controlled Game Session evidence selector changed"); + } + return currentEntityTarget; + }; + + try (var entityDatabase = database(GS, "entity-management-service", false)) { + var characterRepository = + transactionalCharacterRepository( + new CharacterRepository(entityDatabase.dsl()), entityDatabase.manager()); + var assignmentService = + entityConfiguration.preseededActorAssignmentService( + assignmentAuthority, identityPort, stagingPort, targetPort, characterRepository); + var receiptService = + entityConfiguration.preseededActorAssignmentReceiptService(characterRepository); + var assignmentFailure = new AtomicReference(); + var observedAssignmentService = Mockito.spy(assignmentService); + Mockito.doAnswer( + invocation -> { + try { + return invocation.callRealMethod(); + } catch (RuntimeException failure) { + assignmentFailure.set(failure); + throw failure; + } + }) + .when(observedAssignmentService) + .assign(Mockito.any(PreseededActorAssignmentRequest.class)); + CanonicalPreseededActorAssignmentGrpcService entityHandler = + entityConfiguration.canonicalPreseededActorAssignmentGrpcService( + NAMESPACE, observedAssignmentService, receiptService); + var entityServerFactory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + entityPki.keyManagerFactory(entityPki.identity("entity-server")), + entityPki.trustManagerFactory(), + io.grpc.TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + entityServerFactory.addService( + ServerInterceptors.intercept( + entityHandler, + entityConfiguration.canonicalPreseededActorAssignmentPeerInterceptor(NAMESPACE), + new GrpcPeerIdentityInterceptor())); + Server entityServer = entityServerFactory.createServer().start(); + try { + ManagedChannel assignmentChannel = + entityChannel(entityPki, "game-session-client", entityServer.getPort()); + try { + var wireRequest = toWire(assignmentRequest); + net.firedevops.firemud.entitymanagement.v1.AssignPreseededActorResponse assigned; + try { + assigned = + CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub(assignmentChannel) + .assignPreseededActor(wireRequest); + } catch (StatusRuntimeException failure) { + throw new AssertionError( + "Actual Entity assignment failed before region composition", + assignmentFailure.get() == null ? failure : assignmentFailure.get()); + } + assertThat(assigned.getOutcome()) + .isEqualTo( + net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentOutcome + .PRESEEDED_ACTOR_ASSIGNMENT_OUTCOME_ASSIGNED); + assertThat(assigned.getIntentDigest()) + .isEqualTo(assignmentRequest.mutationIntentDigest()); + var assignmentRetry = + CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub(assignmentChannel) + .assignPreseededActor(wireRequest); + assertThat(assignmentRetry.toByteArray()).containsExactly(assigned.toByteArray()); + var runtimeReferenceSelector = + ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(assignmentUuid.toString()) + .setCanonicalAccountUuid(accountUuid.toString()) + .setCharacterUuid(assigned.getCharacterUuid()) + .setIntentDigest(assignmentRequest.mutationIntentDigest()) + .setExpectedTarget(toWire(assignmentTarget)) + .build(); + ManagedChannel worldPeerChannel = + entityChannel(entityPki, "world-management-client", entityServer.getPort()); + try { + assertThatThrownBy( + () -> + CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub( + worldPeerChannel) + .readPreseededActorRuntimeReference(runtimeReferenceSelector)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + shutdown(worldPeerChannel); + } + + var entityEndpoints = new ServiceEndpointsProperties(); + entityEndpoints.setEntityManagementService("127.0.0.1:" + entityServer.getPort()); + var associationRepository = + new WorldCanonicalInstanceAssociationRepository( + world.dsl(), + new WorldCompleteLaunchBindingRepository(world.dsl()), + new WorldAuthoredSourceIntakeRepository(world.dsl()), + new WorldAuthoredVersionIdentityRepository(world.dsl())); + var lifecycleRepository = + new WorldCanonicalInstanceLifecycleReadRepository( + world.dsl(), world.manager(), associationRepository); + var holdRepository = + new WorldCanonicalInitialAdmissionHoldRepository( + world.dsl(), world.manager(), associationRepository, lifecycleRepository); + var locationRepository = + new WorldCanonicalInitialPlayerLocationRepository( + world.dsl(), world.manager(), lifecycleRepository); + var entityReceiptClient = + new EntityPreseededActorAssignmentReceiptClient( + entityEndpoints, + entityPki.clientProperties( + entityPkiDirectory, entityPki.identity("world-management-client")), + channels, + NAMESPACE); + var gsOwnerClient = + new GrpcGameSessionCanonicalInitialAdmissionOwnerClient( + gsEndpoints, worldPki.client("world-management-service"), channels, NAMESPACE); + entityReceiptClient.init(); + gsOwnerClient.init(); + var worldLocationOwner = + new CanonicalInitialPlayerLocationService( + NAMESPACE, + associationRepository, + holdRepository, + locationRepository, + gsOwnerClient, + entityReceiptClient); + var worldLocationGrpc = + new CanonicalInitialPlayerLocationGrpcService(NAMESPACE, worldLocationOwner); + BindableService authenticatedWorldLocationGrpc = + () -> + ServerInterceptors.intercept( + worldLocationGrpc, + new CanonicalInitialPlayerLocationPeerInterceptor(NAMESPACE)); + Server worldLocationServer = + server( + "world-management-service", + worldPki, + authenticatedWorldLocationGrpc, + new WorldCanonicalInstanceLifecycleReadGrpcService( + lifecycleRepository, NAMESPACE)); + try { + var worldEndpoints = new ServiceEndpointsProperties(); + worldEndpoints.setWorldManagementService("127.0.0.1:" + worldLocationServer.getPort()); + var initialLocationClient = + new CanonicalInitialPlayerLocationClient( + worldEndpoints, worldPki.client("game-session-service"), channels, NAMESPACE); + var lifecycleClient = + new WorldCanonicalInstanceLifecycleClient( + worldEndpoints, worldPki.client("game-session-service"), channels, NAMESPACE); + var runtimeReferenceClient = + new CanonicalPreseededActorRuntimeReferenceClient( + entityEndpoints, + entityPki.clientProperties( + entityPkiDirectory, entityPki.identity("game-session-client")), + channels, + NAMESPACE); + try (initialLocationClient; + lifecycleClient; + runtimeReferenceClient) { + initialLocationClient.init(); + lifecycleClient.init(); + runtimeReferenceClient.init(); + var placementRequest = + toWorldLocationRequest( + currentTarget, + assignmentRequest, + assignmentTarget, + assigned.getCharacterUuid(), + holdIdentity); + var placed = initialLocationClient.placeInitialPlayer(placementRequest); + assertThat(placed.getOutcome()) + .isEqualTo( + net.firedevops.firemud.worldmanagement.v1 + .CanonicalInitialPlayerLocationOutcome + .CANONICAL_INITIAL_PLAYER_LOCATION_OUTCOME_APPLIED); + var placementRetry = initialLocationClient.placeInitialPlayer(placementRequest); + assertThat(placementRetry.toByteArray()).containsExactly(placed.toByteArray()); + + var regionResolver = + new CanonicalInitialPlayerLocationRegionResolver( + initialLocationClient, + new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); + var worldRegion = regionResolver.resolve(placementRequest); + assertThat(worldRegion.lifecycleAssignment().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(worldRegion.lifecycleAssignment().lifecycleEpoch()) + .isEqualTo(currentTarget.activeWorldEpoch()); + assertThat(worldRegion.operationalRegionId()).isNotEqualTo(new UUID(0L, 0L)); + + var regionProof = + CanonicalGameplayRegionOwnerCompositionFixture.installAndBridge( + gs.dsl(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + placementRequest, + currentTarget, + regionResolver, + runtimeReferenceClient); + assertThat(regionProof.operationalRegionId()) + .isEqualTo(worldRegion.operationalRegionId()); + assertThat(regionProof.canonicalRegionId()) + .isEqualTo(worldRegion.canonicalRegionInstanceId()); + assertThat(regionProof.lifecycleEpoch()) + .isEqualTo(worldRegion.lifecycleAssignment().lifecycleEpoch()); + assertThat(regionProof.executorFence()).isPositive(); + assertThat(regionProof.bridgeOperationId()).isNotNull(); + assertThat(regionProof.runtimeEntityId()).isPositive(); + assertThat(regionProof.entityProjectionGeneration()).isPositive(); + assertThat(regionProof.entityProjectionFence()).isPositive(); + assertThat(regionProof.entityReferenceDigest()).hasSize(64); + assertThat(regionProof.worldSourceDigest()).hasSize(64); + assertThat(regionProof.redisReadbackDigest()).hasSize(64); + assertThat(regionProof.acknowledgedInventoryRevision()).isPositive(); + assertThat(regionProof.acknowledgedAt()).isNotNull(); + assertThat(regionProof.exactLostReplyRetry()).isTrue(); + } + } finally { + shutdown(worldLocationServer); + entityReceiptClient.close(); + gsOwnerClient.close(); + } + } finally { + shutdown(assignmentChannel); + } + } finally { + shutdown(entityServer); + } + } + } + + private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( + CanonicalPlayableTarget currentTarget, + PreseededActorAssignmentRequest assignmentRequest, + PreseededActorAssignmentExpectedTarget assignmentTarget, + String characterUuid, + WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity) { + return CanonicalInitialPlayerLocationRequest.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(UUID.randomUUID().toString()) + .setExpectedTarget(toWire(assignmentTarget)) + .setCanonicalAccountUuid(assignmentRequest.canonicalAccountUuid().toString()) + .setCharacterUuid(characterUuid) + .setAssignmentUuid(assignmentRequest.assignmentUuid().toString()) + .setAssignmentIntentDigest(assignmentRequest.mutationIntentDigest()) + .setInitialAdmissionHoldUuid(holdIdentity.holdId().toString()) + .setInitialAdmissionHoldFence(holdIdentity.holdFence().toString()) + .setInitialAdmissionRequestId(holdIdentity.request().initialAdmissionRequestId()) + .setInitialAdmissionRequestDigest(holdIdentity.request().initialAdmissionRequestDigest()) + .setActiveLifecycleEpoch(holdIdentity.request().activeLifecycleEpoch()) + .setTerminalProofDigest(currentTarget.ownerProofDigest()) + .setCommittedPointerVersion(currentTarget.pointerVersion()) + .setAuditEventId(currentTarget.auditEventId()) + .build(); + } + + private static AssignPreseededActorRequest toWire(PreseededActorAssignmentRequest request) { + var target = request.expectedTarget(); + return AssignPreseededActorRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(request.assignmentUuid().toString()) + .setCanonicalAccountUuid(request.canonicalAccountUuid().toString()) + .setExpectedTarget(toWire(target)) + .setCorePayload( + net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentCorePayload + .newBuilder() + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .setDisplayName(request.corePayload().displayName()) + .build()) + .setMutationIntentDigest(request.mutationIntentDigest()) + .build(); + } + + private static net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget + toWire(PreseededActorAssignmentExpectedTarget target) { + return net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget + .newBuilder() + .setCanonicalTenantUuid(target.canonicalTenantUuid().toString()) + .setRealmUuid(target.realmUuid().toString()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceId(target.gameInstanceId()) + .setCatalogRevision(target.catalogRevision()) + .setCanonicalVersionUuid(target.canonicalVersionUuid().toString()) + .setFrozenPolicyDigest(target.frozenPolicyDigest()) + .setPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .setPublishedReleaseBundleRef(target.publishedReleaseBundleRef()) + .setPlayableStateScope(target.playableStateScope()) + .build(); + } + + private static void writeRegionAssignmentCapability( + Path capability, + PreseededActorAssignmentRequest request, + String runId, + String project, + String trustRootFingerprint) + throws Exception { + var target = request.expectedTarget(); + String body = + """ + {\ + "schema": "firemud.run-owned-preseeded-actor-assignment.v3",%n\ + "runId": "%s",%n\ + "composeProjectName": "%s",%n\ + "action": "PRESEEDED_ACTOR_ASSIGNMENT",%n\ + "trustedGameSessionUriSan": "spiffe://firemud/ns/%s/sa/game-session-service",%n\ + "trustedGameSessionNamespace": "%s",%n\ + "assignmentUuid": "%s",%n\ + "canonicalAccountUuid": "%s",%n\ + "expectedTarget": {%n\ + "canonicalTenantUuid": "%s",%n\ + "realmUuid": "%s",%n\ + "worldSlug": "%s",%n\ + "realmSlug": "%s",%n\ + "gameInstanceId": "%s",%n\ + "catalogRevision": %d,%n\ + "canonicalVersionUuid": "%s",%n\ + "frozenPolicyDigest": "%s",%n\ + "playableStateNamespaceUuid": "%s",%n\ + "publishedReleaseBundleRef": "%s",%n\ + "playableStateScope": "%s"%n\ + },%n\ + "corePayload": {"actorKind": "PLAYER", "displayName": "%s"},%n\ + "intentDigest": "%s",%n\ + "entityServerTrustRootSha256": "%s"%n\ + }%n\ + """ + .formatted( + runId, + project, + NAMESPACE, + NAMESPACE, + request.assignmentUuid(), + request.canonicalAccountUuid(), + target.canonicalTenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceId(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.frozenPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope().name(), + request.corePayload().displayName(), + request.mutationIntentDigest(), + trustRootFingerprint); + Files.writeString(capability, body); + Files.setPosixFilePermissions( + capability, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + } + + private static io.grpc.ManagedChannel entityChannel( + LoopbackMtlsTestPki.Pki pki, String identityAlias, int port) throws Exception { + var identity = pki.identity(identityAlias); + return NettyChannelBuilder.forAddress("127.0.0.1", port) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forClient() + .trustManager(pki.caCertificate()) + .keyManager(identity.privateKey(), identity.certificate())) + .build()) + .build(); + } + private static WorldCanonicalInstancePreparation.Input preparationInputs( Database world, Database gs, @@ -3439,6 +4078,11 @@ private static void shutdown(Server server) throws InterruptedException { assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); } + private static void shutdown(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + private static void assertPendingActivationState(DSLContext world) { assertThat(world.fetch("SELECT status FROM world_instance").getValues("status", String.class)) .containsExactly("PREPARING"); @@ -3464,6 +4108,17 @@ private static Map> rows(DSLContext dsl, String... tables) return result; } + private static CharacterRepository transactionalCharacterRepository( + CharacterRepository target, PlatformTransactionManager manager) { + var transactions = new TransactionInterceptor(); + transactions.setTransactionManager(manager); + transactions.setTransactionAttributeSource(new AnnotationTransactionAttributeSource()); + var proxy = new ProxyFactory(target); + proxy.setProxyTargetClass(true); + proxy.addAdvice(transactions); + return (CharacterRepository) proxy.getProxy(); + } + private static Database database(PostgreSQLContainer postgres, String service, boolean saga) { String schema = "original_prepare_" + UUID.randomUUID().toString().replace("-", ""); var source = @@ -3479,15 +4134,20 @@ private static Database database(PostgreSQLContainer postgres, String service "filesystem:" + repositoryRoot() .resolve("services/common-saga/src/main/resources/db/migration/saga")); - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .placeholders(Map.of("serviceSchema", schema)) - .locations(locations.toArray(String[]::new)) - .load() - .migrate(); + var migrations = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .placeholders(Map.of("serviceSchema", schema)) + .locations(locations.toArray(String[]::new)); + if ("entity-management-service".equals(service)) { + migrations + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + } + migrations.load().migrate(); var manager = new DataSourceTransactionManager(source); var write = new TransactionTemplate(manager); write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); From 0593e847debe5b807b9a8707e5c08ebf12e65292 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 06:11:31 +1300 Subject: [PATCH 07/36] fix(gameplay): repair actual Human-to-region bridge composition --- .../game-session-service/build.gradle.kts | 14 +++++- ...calGameplayBindingInventoryRepository.java | 8 ++-- .../CanonicalGameplayRegionLeaseOwner.java | 6 ++- ...l_human_binding_decision_runtime_fence.sql | 25 +++++++--- ...ayDecisionRuntimeFenceIntegrationTest.java | 46 ++++++++++--------- ...GameplayRegionOwnerCompositionFixture.java | 11 +++-- 6 files changed, 73 insertions(+), 37 deletions(-) diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 3aeba814be..566b804b28 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -162,7 +162,7 @@ val gameSessionMigrationDriverDist = } } -// Cross-service proof exports owner classes and the exact member-repair script/descriptor. +// Cross-service proof exports owner classes and the exact companion Redis resources they consume. // Application configuration, service registration and Flyway resources remain excluded. val gameSessionClassesProofJar by tasks.registering(Jar::class) { archiveClassifier.set("classes-proof") @@ -188,6 +188,18 @@ val gameSessionClassesProofJar by tasks.registering(Jar::class) { include("redis/lua/game-session-issuer-binding-local-retirement.lua") include("redis/scripts/game-session-issuer-binding-local-retirement.json") } + from("src/main/resources") { + include("redis/lua/game-session-region-lease-acquire.lua") + include("redis/scripts/game-session-region-lease-acquire.json") + include("redis/lua/game-session-region-lease-renew.lua") + include("redis/scripts/game-session-region-lease-renew.json") + include("redis/lua/game-session-region-lease-read.lua") + include("redis/scripts/game-session-region-lease-read.json") + include("redis/lua/game-session-region-timeline-initialize.lua") + include("redis/scripts/game-session-region-timeline-initialize.json") + include("redis/lua/game-session-region-session-binding-bridge.lua") + include("redis/scripts/game-session-region-session-binding-bridge.json") + } } val gameSessionClassesProof by configurations.creating { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index f6723e77ef..13c10b9b7c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -5,6 +5,7 @@ import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -371,6 +372,7 @@ RegionBridgeAcknowledgement acknowledgeRegionBridge( Objects.requireNonNull(prepared, "prepared"); Objects.requireNonNull(readback, "readback"); Objects.requireNonNull(acknowledgedAt, "acknowledgedAt"); + Instant persistedAcknowledgedAt = acknowledgedAt.truncatedTo(ChronoUnit.MICROS); CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence = readProvisionalCasEvidence(prepared.transitionId()); BridgeInputs inputs = @@ -429,12 +431,12 @@ RegionBridgeAcknowledgement acknowledgeRegionBridge( "UPDATE " + REGION_OBLIGATION + " SET status = 'ACKNOWLEDGED', redis_readback_digest = ?," - + " acknowledged_at = ?, inventory_revision = ?" + + " acknowledged_at = ?::timestamptz, inventory_revision = ?" + " WHERE transition_id = ? AND status = 'REQUIRED'" + " AND bridge_operation_id = ? AND executor_fence = ?" + " AND lease_token_correlation = ? AND inventory_revision = ?", readback.digest(), - OffsetDateTime.ofInstant(acknowledgedAt, ZoneOffset.UTC), + OffsetDateTime.ofInstant(persistedAcknowledgedAt, ZoneOffset.UTC), decimal(nextRevision), prepared.transitionId(), prepared.bridgeOperationId(), @@ -456,7 +458,7 @@ RegionBridgeAcknowledgement acknowledgeRegionBridge( || !acknowledged.executorFence().equals(ownerStatus.executorFence()) || !acknowledged.leaseTokenCorrelation().equals(ownerStatus.leaseTokenCorrelation()) || !acknowledged.redisReadbackDigest().equals(readback.digest()) - || !acknowledged.acknowledgedAt().equals(acknowledgedAt) + || !acknowledged.acknowledgedAt().equals(persistedAcknowledgedAt) || !acknowledged.inventoryRevision().equals(nextRevision)) { throw conflict("Region bridge acknowledgement did not survive exact SQL readback"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 37cb5a4de6..71977ec08d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -288,7 +288,11 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement acknowle requireOwnedContext(installation, finalContext); if (!context.status.equals(finalContext.status) || !context.source.equals(finalContext.source) - || !context.resolvedRegion.equals(finalContext.resolvedRegion)) { + || !CanonicalGameplayRegionBindingBridgeProofs.worldSourceDigest( + installation.worldRequest, context.resolvedRegion) + .equals( + CanonicalGameplayRegionBindingBridgeProofs.worldSourceDigest( + installation.worldRequest, finalContext.resolvedRegion))) { throw unavailable(); } return bindingInventory.acknowledgeRegionBridge( diff --git a/services/game-session-service/src/main/resources/db/migration/V1044__canonical_human_binding_decision_runtime_fence.sql b/services/game-session-service/src/main/resources/db/migration/V1044__canonical_human_binding_decision_runtime_fence.sql index 492c65436e..a9ab86d0c7 100644 --- a/services/game-session-service/src/main/resources/db/migration/V1044__canonical_human_binding_decision_runtime_fence.sql +++ b/services/game-session-service/src/main/resources/db/migration/V1044__canonical_human_binding_decision_runtime_fence.sql @@ -234,15 +234,13 @@ BEGIN launch.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef' ) OR ( - -- Human STARTING -> RUNNING rows retain their own immutable positive receipt. They - -- do not copy run-owned launch fields; a missing or conflicting route fails closed. + -- Human STARTING -> RUNNING rows retain their own immutable positive receipt and + -- original StartSession identity. The request/digest/release columns bind that + -- source identity; run-owned lifecycle epochs remain absent. NEW.admission_target_owner_proof_outcome = 'COMMITTED' AND NEW.admission_target_positive_durable_abort IS FALSE AND runtime.run_owned_start_preparing_epoch IS NULL AND runtime.run_owned_start_active_epoch IS NULL - AND runtime.run_owned_start_request_id IS NULL - AND runtime.run_owned_start_request_digest IS NULL - AND runtime.run_owned_start_published_release_bundle_ref IS NULL AND EXISTS ( SELECT 1 FROM game_session_canonical_human_runtime_completion completion @@ -273,6 +271,22 @@ BEGIN AND attempt.audit_event_id = NEW.admission_target_audit_event_id AND attempt.commit_proof_digest = NEW.admission_target_owner_proof_digest AND attempt.terminal_at = NEW.admission_target_terminal_at + JOIN game_session_start_session_operator_attempt original + ON original.target_namespace = completion.target_namespace + AND original.owner_attempt_id = completion.original_owner_attempt_id + AND original.owner_mutation_id = completion.original_owner_mutation_id + AND original.owner_fence = completion.original_owner_fence + AND original.canonical_tenant_id = completion.canonical_tenant_id + AND original.control_plane_request_id = launch.control_plane_request_id + AND original.post_authorization_execution_tuple = + completion.original_start_session_tuple + AND original.account_redemption_projection = + completion.account_redemption_projection + AND runtime.run_owned_start_request_id = original.control_plane_request_id + AND runtime.run_owned_start_request_digest = original.mutation_digest + AND runtime.run_owned_start_published_release_bundle_ref = + launch.complete_launch_binding_evidence -> 'descriptor' + ->> 'publishedReleaseBundleRef' JOIN gameplay_admission_pointer pointer ON pointer.id = attempt.pointer_id AND pointer.representation_version = 3 @@ -402,7 +416,6 @@ BEGIN AND pointer.requires_character_selection IS NULL AND pointer.last_updated_by = 'game-session-canonical-initial-admission' AND pointer.last_update_reason = 'World-held initial admission' - AND pointer.prepared_version_upgrade_id IS NULL ) ) ) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java index 4da5a81f36..78851664f6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java @@ -254,8 +254,8 @@ void stoppedRuntimeCannotAcquireLeaseBoundBindingFence() { } @Test - void runningRuntimeWithoutRetainedHumanCompletionOrRunOwnedMetadataCannotAcquireFence() { - String schema = "gs_runtime_fence_unowned_" + UUID.randomUUID().toString().replace("-", ""); + void freshSourceBoundRuntimeWithoutHumanCompletionCannotLoseRunOwnedLaunchProvenance() { + String schema = "gs_runtime_fence_runowned_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); try { migrate(schema, dataSource); @@ -264,19 +264,22 @@ void runningRuntimeWithoutRetainedHumanCompletionOrRunOwnedMetadataCannotAcquire CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); byte[] candidateRef = seedCandidateAndPreparedTransition(dsl, target, CandidateMismatch.NONE); - assertThat( - dsl.execute( - "UPDATE game_instances SET row_version = row_version + 1," - + " run_owned_start_request_id = NULL, run_owned_start_request_digest = NULL," - + " run_owned_start_published_release_bundle_ref = NULL," - + " run_owned_start_preparing_epoch = NULL, run_owned_start_active_epoch = NULL" - + " WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId())) - .isEqualTo(1); - - assertThatThrownBy(() -> markProvisional(dsl, target, candidateRef)) - .hasMessageContaining("exact current RUNNING launch row and candidate identity"); + // A fresh source-bound RUNNING row cannot be stripped of its run-owned launch association. + // The V26 deferred guard rejects that impossible setup before V1044's lease-bound fence runs. + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1," + + " run_owned_start_request_id = NULL," + + " run_owned_start_request_digest = NULL," + + " run_owned_start_published_release_bundle_ref = NULL," + + " run_owned_start_preparing_epoch = NULL," + + " run_owned_start_active_epoch = NULL" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .hasMessageContaining( + "Fresh Game Session instance requires one exact complete launch association"); var runtimeReadback = dsl.fetchSingle( @@ -287,13 +290,14 @@ void runningRuntimeWithoutRetainedHumanCompletionOrRunOwnedMetadataCannotAcquire target.gameSessionTenantId(), target.gameInstanceId()); assertThat(runtimeReadback.get("status", String.class)).isEqualTo("RUNNING"); - assertThat(runtimeReadback.get("row_version", Long.class)).isEqualTo(2L); - assertThat(runtimeReadback.get("run_owned_start_request_id", String.class)).isNull(); - assertThat(runtimeReadback.get("run_owned_start_request_digest", String.class)).isNull(); + assertThat(runtimeReadback.get("row_version", Long.class)).isEqualTo(1L); + assertThat(runtimeReadback.get("run_owned_start_request_id", String.class)) + .isEqualTo(target.controlPlaneRequestId()); + assertThat(runtimeReadback.get("run_owned_start_request_digest", String.class)).isNotNull(); assertThat(runtimeReadback.get("run_owned_start_published_release_bundle_ref", String.class)) - .isNull(); - assertThat(runtimeReadback.get("run_owned_start_preparing_epoch", Long.class)).isNull(); - assertThat(runtimeReadback.get("run_owned_start_active_epoch", Long.class)).isNull(); + .isEqualTo(target.publishedReleaseBundleRef()); + assertThat(runtimeReadback.get("run_owned_start_preparing_epoch", Long.class)).isNotNull(); + assertThat(runtimeReadback.get("run_owned_start_active_epoch", Long.class)).isNotNull(); assertThat( dsl.fetchSingle( "SELECT count(*) AS actual_count" diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index ca5e7c13f9..f0ef2dd7a8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -36,6 +36,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; @@ -47,7 +48,7 @@ * lease carrier, issuer reservation, and stable Redis incarnation are controlled test evidence. */ public final class CanonicalGameplayRegionOwnerCompositionFixture { - private static final String REDIS_PRINCIPAL = "gamesession_region_owner_app"; + private static final String REDIS_PRINCIPAL = "gamesession_coord_app"; private static final String REDIS_PASSWORD = UUID.randomUUID().toString(); private static final String REGION_ATTESTATION = "controlled-region-owner-composition"; @@ -115,7 +116,9 @@ public static Proof installAndBridge( try (var redis = RegionRedis.open(redisHost, redisPort)) { var scriptCatalog = RedisScriptCatalog.fromContributions( - List.of(new CanonicalGameplayRegionLeaseRedisScriptContribution())); + List.of( + new CanonicalGameplayRegionLeaseRedisScriptContribution(), + new CanonicalGameplayRegionBindingBridgeRedisScriptContribution())); var stableSource = new ControlledStableIncarnationSource(); var runtimeIdentity = new RuntimeIdentity( @@ -163,9 +166,7 @@ public static Proof installAndBridge( .hget( ascii( CanonicalGameplayRegionRedisKeys.meta( - identity.tenantId(), - identity.gameInstanceId(), - resolved.canonicalRegionInstanceId())), + identity.tenantId(), identity.gameInstanceId(), status.regionId())), ascii("current_tick_state")); if (!Arrays.equals(currentTickState, ascii("APPLIED"))) { throw new IllegalStateException("Canonical Redis initial timeline metadata is absent"); From 8dae7176b28866c8881ed9aa4ddc5cf9aa126692 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 06:33:45 +1300 Subject: [PATCH 08/36] docs(gameplay): record qualified actual region owner composition --- .../microservices/game-session-service/runtime-and-data.md | 2 +- .../implementation-tracking/world-runtime-and-movement.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 8b478d34f8..e56f5ebdeb 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -30,7 +30,7 @@ The sections below define the target-state runtime contract. Current implementat - Hidden same-type Game Session recovery within ADR 0013's qualifying conditions remains an implementation or proof gap; the target is to preserve the session through upstream rebind rather than require a player-visible re-`LOGIN` / re-`PLAY` cycle. - The live `startSession` path keeps the Game Session row and runtime projection `STARTING` until World confirms its fenced `PREPARING -> ACTIVE` transition, then records `RUNNING`; failures before an activation attempt use the existing pre-activation cleanup. Once activation may have been issued or committed, an activation error or ambiguous result, or a later local runtime-state save/finalization failure, retains both the runtime projection and local owner row as `STARTING`, and never calls stale-epoch `failPrepared` or deletes either record. A failure proven before any World termination request is issued may restore the prior `RUNNING` row and runtime state while the World remains `ACTIVE`; once a termination request may have been issued, an error or ambiguous result leaves the local row `STOPPING` and runtime projection absent. Confirmed World termination retries local `STOPPED` finalization and never restores `RUNNING`. Durable stable lifecycle-operation identity and lifecycle readback/reconciliation remain unimplemented, so these local fail-closed quarantines are not a replacement for the target durable lifecycle cleanup workflow. - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. -- The prepared, unregistered region owner consumes exact World initial-placement/currentness and lifecycle reads plus Entity’s authenticated runtime reference. It durably prepares a non-admitting initial timeline, conditionally installs complete same-slot initial Redis metadata and the actual region lease, installs the matching SQL executor fence, and records the first-NEW region bridge acknowledgement. The timeline begins at `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`); existing or reset state cannot be adopted as a new timeline. Original retries retain the preparation, source and lease evidence. Source and component tests are present, but the combined actual-owner qualification remains in progress. Forward V1043 preserves the original timeline migration while aligning its binding-reference carrier with the existing 6,144-byte physical codec bound; the canonical three-UUID frame is 133 bytes and cannot fit the former 128-byte check. Forward V1044 makes the existing lease-bound runtime fence consume the exact retained Human completion, matching `COMMITTED` initial attempt, current `OPEN` pointer and audit under the existing runtime row lock. The original run-owned checks remain owner-specific; absence of both qualified sources is refused. Combined actual-owner qualification remains in progress. This is manual owner preparation, not registered tick execution, final player binding or production admission. The [Redis owner contract](../../system-architecture-redis.md#key-naming-and-shard-discipline) remains authoritative for timeline and lease semantics. +- The prepared, unregistered region owner consumes exact World initial-placement/currentness and lifecycle reads plus Entity’s authenticated runtime reference. It durably prepares a non-admitting initial timeline, conditionally installs complete same-slot initial Redis metadata and the actual region lease, installs the matching SQL executor fence, and records the first-NEW region bridge acknowledgement. The timeline begins at `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`); existing or reset state cannot be adopted as a new timeline. Original retries retain the preparation, source and lease evidence. The controlled authenticated actual-owner composition now has focused local proof; the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-initial-player-location-preparation) records its scope and remaining public qualification. Forward V1043 preserves the original timeline migration while aligning its binding-reference carrier with the existing 6,144-byte physical codec bound; the canonical three-UUID frame is 133 bytes and cannot fit the former 128-byte check. Forward V1044 makes the existing lease-bound runtime fence consume the exact retained Human completion, matching `COMMITTED` initial attempt, current `OPEN` pointer and audit under the existing runtime row lock. The original run-owned checks remain owner-specific; absence of both qualified sources is refused. This is manual owner preparation, not registered tick execution, final player binding or production admission. The [Redis owner contract](../../system-architecture-redis.md#key-naming-and-shard-discipline) remains authoritative for timeline and lease semantics. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). - The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 55f1a10793..aa0a72aa6a 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for world runtime and movement. C The selected initial-room region read is now local source preparation in the existing World service, with the matching Game Session client and independent lifecycle resolver. It preserves immutable placement storage/results, checks the actual room-to-zone-to-region mappings and current initial room, and keeps every owner manually composed and unregistered. The production query uses the current `room_instance_row_id` column. R584 freshly passes 44 focused unit, controlled mTLS and PostgreSQL cases with zero failures, errors or skips; the native case executes `EXPLAIN` on the exact production query after actual migrations and verifies refusal. That is schema/refusal proof, not a positive authorized region selection. Its aggregate failed solely on the Game Session immutable-protobuf getter exposure warning. R587 applies a narrow suppression justified by generated protobuf immutability and passes the affected enabled main Checkstyle, SpotBugs and formatting checks; it does not repeat or relabel the 44 passing R584 cases. Independent inspection confirms both exact R584 PostgreSQL/Ryuk containers absent. Positive multi-region placement/replay still requires genuine authorized `ACTIVE`, hold, pointer and Entity receipt sources, and the player-binding gate consumer remains unfinished. No original end-to-end Gate testing or admission completion is claimed. -The next local region prerequisite now composes the actual #2973 committed World hold and Game Session initial terminal with Entity assignment/runtime projection, authenticated World placement/current region and lifecycle reads, and the Game Session initial timeline, region lease, SQL fence and durable bridge acknowledgement. Its positive state is owner-produced; Account lease, issuer reservation, deployment incarnation, staging/policy sources, run capability and test PKI remain controlled inputs. R661 executes 85 fresh cases with one failed full-composition case: actual Entity assignment, World placement and lifecycle reads succeed, then the lease-bound SQL runtime fence rejects the real Human completion because it still expects run-owned metadata. The corrected consumer is in forward V1044 and requires the retained Human receipt, matching committed initial attempt and current open pointer; its replacement combined gate is still pending. All 19 exact R661 containers are independently absent. No passing combined result is attributed yet. This does not claim registered tick execution, final player binding or production authority. +The selected local region prerequisite now composes the actual #2973 committed World hold and Game Session initial terminal with Entity assignment/runtime projection, authenticated World placement/current region and lifecycle reads, and the Game Session initial timeline, region lease, SQL executor fence and durable bridge acknowledgement with exact lost-reply replay. R705 freshly passes 92 cases (46 unit, 40 PostgreSQL/Redis and six cross-service cases) at `0df28a1bdbcdc7ae3507d456fa7f72afb7fa1065`, receiving the actual #2973 parent `4d188b6488aeed9535a5b4acb97eeda6dc823d87`; the selected comparison contains 83 owned paths. Enabled affected static analysis, formatting, link and Markdown checks pass. All 20 observed test containers are independently confirmed absent. The consumer preserves the original run-owned source and separately verifies the immutable Human owner/completion, matching committed attempt and current open pointer/audit. The real bridge compares complete World evidence by the existing closed digest, persists its acknowledgement at SQL timestamp precision, and reads the initial metadata under the operational region identity. Historical R661 and subsequent failed aggregates remain retained; they do not provide current passing attribution. Account lease, issuer reservation, deployment incarnation, staging/policy sources, run capability and test PKI remain controlled inputs. This is complete controlled manual owner composition, with replacement public CI still required; it does not claim registered tick execution, the final player binding/five-key CAS, production authority, or the separately parked end-to-end Gate work. The [initial-placement API](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-player-location) is prepared as an unregistered owner service, transport and immediate Game Session client over the existing V1019 storage boundary. It receives the necessary existing canonical hold reader, Game Session terminal client and Common response decoder; their donor source remains preserved. The distinct World-only Entity receipt read supplies persisted assignment provenance without widening the Game Session roster allowlists. From 2e9ad87a869b12d859f23b8ea364a7376190d122 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:17:31 +1300 Subject: [PATCH 09/36] docs(gameplay): record current-parent region qualification and skip recovery --- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index aa0a72aa6a..507ff4bd7b 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -12,6 +12,8 @@ The selected initial-room region read is now local source preparation in the exi The selected local region prerequisite now composes the actual #2973 committed World hold and Game Session initial terminal with Entity assignment/runtime projection, authenticated World placement/current region and lifecycle reads, and the Game Session initial timeline, region lease, SQL executor fence and durable bridge acknowledgement with exact lost-reply replay. R705 freshly passes 92 cases (46 unit, 40 PostgreSQL/Redis and six cross-service cases) at `0df28a1bdbcdc7ae3507d456fa7f72afb7fa1065`, receiving the actual #2973 parent `4d188b6488aeed9535a5b4acb97eeda6dc823d87`; the selected comparison contains 83 owned paths. Enabled affected static analysis, formatting, link and Markdown checks pass. All 20 observed test containers are independently confirmed absent. The consumer preserves the original run-owned source and separately verifies the immutable Human owner/completion, matching committed attempt and current open pointer/audit. The real bridge compares complete World evidence by the existing closed digest, persists its acknowledgement at SQL timestamp precision, and reads the initial metadata under the operational region identity. Historical R661 and subsequent failed aggregates remain retained; they do not provide current passing attribution. Account lease, issuer reservation, deployment incarnation, staging/policy sources, run capability and test PKI remain controlled inputs. This is complete controlled manual owner composition, with replacement public CI still required; it does not claim registered tick execution, the final player binding/five-key CAS, production authority, or the separately parked end-to-end Gate work. +The next receiving checkpoint at `63bfad5b657d6fafc2880345355074e68b3945e2` receives #2973 `bea4f4dd555a6536e5d09a7a04b54e3a8f5bc6a6` and still contains the same 83 owned paths. Eighty-one owned postimages are unchanged; the two shared files receive the qualified retained-abort validation correction and settlement-read fixture wire bound. R714 exits successfully with 73 executed passing cases and 19 skipped Game Session native cases; the skip cause is unproven and that run alone is not full qualification. R715 then freshly executes and passes all 19 skipped cases, with no failures, errors or skips. Across R714/R715, all 92 selected methods have passing execution on unchanged production postimages, including the actual Human-to-region owner composition. Enabled affected static analysis, formatting and documentation checks pass. All 14 observed R714 and seven R715 containers are independently absent. The same controlled-source, unregistered-runtime and final-player-CAS limits remain; current public CI is still required. + The [initial-placement API](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-player-location) is prepared as an unregistered owner service, transport and immediate Game Session client over the existing V1019 storage boundary. It receives the necessary existing canonical hold reader, Game Session terminal client and Common response decoder; their donor source remains preserved. The distinct World-only Entity receipt read supplies persisted assignment provenance without widening the Game Session roster allowlists. The component checkpoint `eee4a18057411d74ed3d25ddf19f44c7a78391e0` passes 65 fresh focused cases across R337, R338 and R340: 53 unit cases, ten controlled physical TLS cases, one actual Entity assignment/receipt-to-current-PostgreSQL case and one current-PostgreSQL World refusal case. R336–R339 retain their failed aggregate and separately passing component attribution. Affected enabled static analysis and formatting checks pass. From 3c12325dcd066fc0e28a84119d3e4c9030f9d2f0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:49:17 +1300 Subject: [PATCH 10/36] docs(gameplay): record final protected-parent region proof --- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index f65f6897e8..a1304fe99a 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -14,6 +14,8 @@ The selected local region prerequisite now composes the actual #2973 committed W The next receiving checkpoint at `63bfad5b657d6fafc2880345355074e68b3945e2` receives #2973 `bea4f4dd555a6536e5d09a7a04b54e3a8f5bc6a6` and still contains the same 83 owned paths. Eighty-one owned postimages are unchanged; the two shared files receive the qualified retained-abort validation correction and settlement-read fixture wire bound. R714 exits successfully with 73 executed passing cases and 19 skipped Game Session native cases; the skip cause is unproven and that run alone is not full qualification. R715 then freshly executes and passes all 19 skipped cases, with no failures, errors or skips. Across R714/R715, all 92 selected methods have passing execution on unchanged production postimages, including the actual Human-to-region owner composition. Enabled affected static analysis, formatting and documentation checks pass. All 14 observed R714 and seven R715 containers are independently absent. The same controlled-source, unregistered-runtime and final-player-CAS limits remain; current public CI is still required. +Final receiving checkpoint `cc90e783280a99aa6c247e32377fd7cf283be9c4` receives published #2973 `8e15d7af318808a5cab6c460da22db917f66dbb2` and #3310 `8cf137b8fb31be2728978e1397ffce7012bf313e`. Its 83-path comparison preserves all 82 owned source postimages from the qualified boundary; only this shared tracker receives parent proof attribution. R720 freshly passes the actual Human-to-region composed owner case and all seven runtime-fence cases, with zero failures, errors or skips and enabled affected static analysis, formatting and documentation checks. All eight R720 observed containers are independently absent. This is current-parent receiving proof supplementing the separately scoped 92-method qualification above. Controlled authority, registration, tick execution, final player CAS, production custody/PKI and activation limits remain unchanged. + The [initial-placement API](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-player-location) is prepared as an unregistered owner service, transport and immediate Game Session client over the existing V1019 storage boundary. It receives the necessary existing canonical hold reader, Game Session terminal client and Common response decoder; their donor source remains preserved. The distinct World-only Entity receipt read supplies persisted assignment provenance without widening the Game Session roster allowlists. The component checkpoint `eee4a18057411d74ed3d25ddf19f44c7a78391e0` passes 65 fresh focused cases across R337, R338 and R340: 53 unit cases, ten controlled physical TLS cases, one actual Entity assignment/receipt-to-current-PostgreSQL case and one current-PostgreSQL World refusal case. R336–R339 retain their failed aggregate and separately passing component attribution. Affected enabled static analysis and formatting checks pass. From 32997487ab118bdf6557d390ba2601b837b2f7c7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:24:37 +1300 Subject: [PATCH 11/36] test(gameplay): qualify retained roster migration fixture recovery --- design/project-management/ai-observations.md | 2 +- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ ...onicalGameplayRosterRetentionPostgresIntegrationTest.java | 5 ++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a52c2264e7..471d770689 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -451,5 +451,5 @@ Entry format: - `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: the one-file fixture correction is prepared; consolidated native/static validation remains pending. + - 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/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index a1304fe99a..f7f0f30d3e 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -16,6 +16,8 @@ The next receiving checkpoint at `63bfad5b657d6fafc2880345355074e68b3945e2` rece Final receiving checkpoint `cc90e783280a99aa6c247e32377fd7cf283be9c4` receives published #2973 `8e15d7af318808a5cab6c460da22db917f66dbb2` and #3310 `8cf137b8fb31be2728978e1397ffce7012bf313e`. Its 83-path comparison preserves all 82 owned source postimages from the qualified boundary; only this shared tracker receives parent proof attribution. R720 freshly passes the actual Human-to-region composed owner case and all seven runtime-fence cases, with zero failures, errors or skips and enabled affected static analysis, formatting and documentation checks. All eight R720 observed containers are independently absent. This is current-parent receiving proof supplementing the separately scoped 92-method qualification above. Controlled authority, registration, tick execution, final player CAS, production custody/PKI and activation limits remain unchanged. +The first region-PR CI repair preserves the intentional V1011/V1017 Entity roster-retention migration fixtures. They now seed explicitly historical assignment receipts, actors and snapshots without calling the fresh V1022 projection allocator before upgrade; current-schema assignments still use the production owner. No applied migration or production compatibility/backfill path changes. R722 executes 584 Entity methods: 454 unit and 65 native cases pass, while 46 retention setup cases expose a placeholder error in the new fixture and 19 other native cases fail PostgreSQL connection setup. R723 corrects only the placeholder and freshly passes all 65 affected native cases with zero failures, errors or skips. All 584 distinct methods therefore have passing execution across the two runs; the failed full-check aggregate stays retained. Enabled affected static analysis and formatting pass. This is current-parent fixture and regression proof; replacement public CI is still required. + The [initial-placement API](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-player-location) is prepared as an unregistered owner service, transport and immediate Game Session client over the existing V1019 storage boundary. It receives the necessary existing canonical hold reader, Game Session terminal client and Common response decoder; their donor source remains preserved. The distinct World-only Entity receipt read supplies persisted assignment provenance without widening the Game Session roster allowlists. The component checkpoint `eee4a18057411d74ed3d25ddf19f44c7a78391e0` passes 65 fresh focused cases across R337, R338 and R340: 53 unit cases, ten controlled physical TLS cases, one actual Entity assignment/receipt-to-current-PostgreSQL case and one current-PostgreSQL World refusal case. R336–R339 retain their failed aggregate and separately passing component attribution. Affected enabled static analysis and formatting checks pass. 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 930c9f9b35..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 @@ -3284,7 +3284,7 @@ private void seedHistoricalV1011AssignmentActorAndSnapshotWithoutProjection() { + "VALUES (?, ?, ?, 'ACCOUNT_DATABASE_INSERT', 1, 'dev', 51, 'ELIGIBLE', " + "clock_timestamp(), 4, ?, ?, 'PRESEEDED_ACTOR_STAGING', " + "'CURRENT_AT_REVALIDATION', ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, " - + "'CANONICAL_UUID', ?, ?, ?, ?, ?, 'PENDING')", + + "'CANONICAL_UUID', ?, ?, ?, ?, ?, ?, 'PENDING')", assignment, request.mutationIntentDigest(), binding.canonicalAccountUuid(), @@ -3337,8 +3337,7 @@ private PreseededActorAssignmentRequest assignmentRequest(UUID assignment) { return new PreseededActorAssignmentRequest( assignment, binding.canonicalAccountUuid(), - new PreseededActorCorePayload( - PreseededActorCorePayload.ActorKind.PLAYER, "Retained Actor"), + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Retained Actor"), new PreseededActorAssignmentExpectedTarget( target.tenantUuid(), target.realmUuid(), From e2e94ba40253d945d38e0a7416ebef68507cb9df Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:31:46 +1300 Subject: [PATCH 12/36] Prepare retained region ACK abort and multi-binding owner reuse --- ...calGameplayBindingInventoryRepository.java | 12 +- ...nicalGameplayRegionBindingBridgeOwner.java | 13 + .../CanonicalGameplayRegionLeaseOwner.java | 106 +++- ...GameplayRegionRuntimeStatusRepository.java | 91 +++- ...1__retained_region_bridge_abort_source.sql | 231 +++++++++ ...GameplayRegionOwnerCompositionFixture.java | 475 +++++++++++++++++- ...untimeStatusRepositoryIntegrationTest.java | 89 ++++ ...ationOwnerCompositionCrossServiceTest.java | 202 +++++++- 8 files changed, 1189 insertions(+), 30 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1044.1__retained_region_bridge_abort_source.sql diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index cfcefb1751..f5f28bf649 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -737,7 +737,9 @@ private static BridgeInputs requireBridgeInputs( || !assignment.captureId().equals(ownerStatus.captureId()) || !assignment.graphSha256().equals(ownerStatus.graphSha256()) || !assignment.preparationInputDigest().equals(ownerStatus.preparationInputDigest()) - || !assignment.request().equals(ownerStatus.lifecycleRequest()) + || !CanonicalGameplayRegionRuntimeStatusRepository + .sameLifecycleRequestExceptReadRequestId( + assignment.request(), ownerStatus.lifecycleRequest()) || assignment.lifecycleEpoch() != ownerStatus.lifecycleEpoch() || assignment.lifecycleRowVersion() != ownerStatus.lifecycleRowVersion() || ownerStatus.paused() @@ -2304,7 +2306,8 @@ private static void requireRetainedFirstNewAbortObligations( || !transition.issuerReservationId().equals(issuer.get("reservation_id", UUID.class)) || !transition.bindingGeneration().equals(readBigInteger(issuer, "binding_generation")) || !revision.equals(readBigInteger(issuer, "inventory_revision")) - || !"REQUIRED".equals(region.get("status", String.class)) + || (!"REQUIRED".equals(region.get("status", String.class)) + && !"ACKNOWLEDGED".equals(region.get("status", String.class))) || !Arrays.equals(bindingRef, region.get("binding_ref", byte[].class)) || !transition.bindingGeneration().equals(readBigInteger(region, "binding_generation")) || !candidate.accountId().equals(region.get("account_id", UUID.class)) @@ -2326,6 +2329,11 @@ private static void requireRetainedFirstNewAbortObligations( != 1) { throw conflict("Aborted first-NEW source lost a required retained index obligation"); } + if ("ACKNOWLEDGED".equals(region.get("status", String.class))) { + // Decode the complete retained ACK with the existing closed carrier contract. The exact + // candidate, identity and revision checks above remain independent of cleanup or admission. + toRegionObligation(region); + } if ("ACKNOWLEDGED".equals(account.get("status", String.class))) { // This is historical ADD/readback evidence, never account-member removal or cleanup proof. Record repair = findMemberRepairOperation(transaction, transitionId, false); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java index 5e7ed8b0bf..ccea6e95ed 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java @@ -35,6 +35,19 @@ CanonicalGameplayRegionLeaseOwner.Installation installForTransition( return regionLeaseOwner.installForTransition(transitionId, request); } + /** + * Installs another per-binding bridge under a still-current region installation created by this + * same manually composed owner. The supplied handle carries private grant authority; no token is + * accepted or reconstructed by the caller. + */ + CanonicalGameplayRegionLeaseOwner.Installation installForTransition( + CanonicalGameplayRegionLeaseOwner.Installation existingRegionInstallation, + UUID transitionId, + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { + return regionLeaseOwner.installForTransition( + existingRegionInstallation, transitionId, request); + } + /** Executes only an exact first-NEW bridge from a privately created region installation. */ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( CanonicalGameplayRegionLeaseOwner.Installation installation) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 71977ec08d..149d345312 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -61,6 +61,14 @@ final class CanonicalGameplayRegionLeaseOwner { */ Installation installForTransition( UUID transitionId, CanonicalInitialPlayerLocationRequest worldRequest) { + return installForTransition(null, transitionId, worldRequest); + } + + /** Installs another binding under a still-current private region grant. */ + Installation installForTransition( + Installation existingRegionInstallation, + UUID transitionId, + CanonicalInitialPlayerLocationRequest worldRequest) { requireNoAmbientTransaction(); Objects.requireNonNull(transitionId, "transitionId"); Objects.requireNonNull(worldRequest, "worldRequest"); @@ -78,7 +86,9 @@ Installation installForTransition( CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; CanonicalGameplayRegionLeaseRedisOwner.LeaseGrant grant; + boolean reusingRegionGrant = false; if (prior == null) { + if (existingRegionInstallation != null) throw unavailable(); preparation = statusRepository.findTimelinePreparation(source).orElse(null); if (preparation == null) { CanonicalGameplayRegionLeaseRedisOwner.TimelineAbsenceProof absenceProof = @@ -130,24 +140,55 @@ Installation installForTransition( statusRepository .findTimelinePreparation(source) .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); - if (!statusRepository.matchesTimelinePreparation( - preparation, - evidence, - worldRequest, - initialResolved.resolvedRegion, - source, - incarnation) - || preparation.phase() - != CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase - .INSTALLED - && preparation.phase() - != CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase - .REDIS_INITIALIZED) { + boolean sameInitializationAttempt = + preparation.transitionId().equals(evidence.transition().transitionId()); + boolean matchesInitialization = + sameInitializationAttempt + ? statusRepository.matchesTimelinePreparation( + preparation, + evidence, + worldRequest, + initialResolved.resolvedRegion, + source, + incarnation) + : statusRepository.matchesInstalledTimelineInitialization( + preparation, source, incarnation); + boolean resumablePhase = + sameInitializationAttempt + ? preparation.phase() + == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .INSTALLED + || preparation.phase() + == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .REDIS_INITIALIZED + : preparation.phase() + == CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase + .INSTALLED; + if (!matchesInitialization || !resumablePhase) { throw unavailable(); } - grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); + if (existingRegionInstallation == null) { + grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); + } else { + requireReusableRegionGrant( + existingRegionInstallation, + source, + incarnation, + prior, + expectedRegionEpoch); + grant = existingRegionInstallation.grant; + reusingRegionGrant = true; + } + } + if (reusingRegionGrant) { + redisOwner.requireGrantScope( + grant, + existingRegionInstallation.source, + expectedRegionEpoch, + runtimeIdentity); + } else { + redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); } - redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); CanonicalGameplayRegionRuntimeStatusRepository.Source afterAcquire = resolveExactSource(worldRequest, readCurrentProvisionalEvidence(transitionId)); requireSameSource(source, afterAcquire); @@ -191,6 +232,41 @@ Installation installForTransition( transitionId, worldRequest, evidence, source, incarnation, preparation, grant, installed); } + private void requireReusableRegionGrant( + Installation existing, + CanonicalGameplayRegionRuntimeStatusRepository.Source candidateSource, + CanonicalGameplayRegionIncarnationSource.StableEvidence currentIncarnation, + CanonicalGameplayRegionRuntimeStatus currentStatus, + long expectedRegionEpoch) { + if (existing == null + || !existing.owner.equals(this) + || !CanonicalGameplayRegionRuntimeStatusRepository.sameRegionSource( + existing.source, candidateSource) + || existing.status == null + || !existing.status.equals(currentStatus) + || currentStatus.paused() + || existing.status.regionEpoch() != expectedRegionEpoch) { + throw unavailable(); + } + requireSameIncarnation(existing.incarnation, currentIncarnation); + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation persistedPreparation = + statusRepository + .findTimelinePreparation(existing.preparation.source()) + .orElseThrow(CanonicalGameplayRegionLeaseOwner::unavailable); + if (!statusRepository.matchesCurrentInstalledTimelineInitialization( + existing.preparation, + persistedPreparation, + candidateSource, + currentIncarnation, + currentStatus)) { + throw unavailable(); + } + redisOwner.requireGrantScope( + existing.grant, existing.source, expectedRegionEpoch, runtimeIdentity); + redisOwner.requireCurrent(existing.grant); + redisOwner.verifyInitializedTimeline(existing.grant, persistedPreparation); + } + /** * Revalidates the same SQL source, World assignment and acquired lease before any later bridge. */ diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index f798f6b304..8046b1857a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -193,12 +193,63 @@ Optional findTimelinePreparation(Source source) { source.regionId()); if (row == null) return Optional.empty(); TimelinePreparation preparation = toTimelinePreparation(row); - if (!preparation.source.equals(source) || !preparation.tenantRegionTag.equals(tag)) { + if (!sameRegionSource(preparation.source, source) + || !preparation.tenantRegionTag.equals(tag)) { throw unavailable(); } return Optional.of(preparation); } + /** + * Matches the immutable region initialization source without treating a later lifecycle read's + * request correlation id as a different region. The stored first request and digest remain + * unchanged; all target, release, descriptor, lifecycle and region evidence stays exact. + */ + boolean matchesInstalledTimelineInitialization( + TimelinePreparation preparation, + Source source, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation) { + Objects.requireNonNull(preparation, "preparation"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(incarnation, "incarnation"); + String tag = + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + source.tenantId(), source.gameInstanceId(), source.regionId()); + return sameRegionSource(preparation.source, source) + && preparation.tenantRegionTag.equals(tag) + && preparation.matchesIncarnation(incarnation) + && preparation.regionEpoch == 1L + && preparation.lastCommittedTickId == -1L; + } + + boolean matchesCurrentInstalledTimelineInitialization( + TimelinePreparation expected, + TimelinePreparation current, + Source candidateSource, + CanonicalGameplayRegionIncarnationSource.StableEvidence incarnation, + CanonicalGameplayRegionRuntimeStatus status) { + Objects.requireNonNull(expected, "expectedPreparation"); + Objects.requireNonNull(current, "currentPreparation"); + Objects.requireNonNull(candidateSource, "candidateSource"); + Objects.requireNonNull(incarnation, "incarnation"); + Objects.requireNonNull(status, "status"); + String expectedMetaDigest = + CanonicalGameplayRegionBindingBridgeProofs.initialMetaDigest( + current.tenantRegionTag, current.operationId, current.sourceDigest()); + return samePreparation(expected, current) + && matchesInstalledTimelineInitialization(current, candidateSource, incarnation) + && current.phase == TimelinePreparationPhase.INSTALLED + && current.leaseTokenCorrelation != null + && current.leaseTokenCorrelation.equals(status.leaseTokenCorrelation()) + && current.executorFence != null + && status.executorFence().longValueExact() == current.executorFence + && current.redisMetaDigest != null + && current.redisMetaDigest.equals(expectedMetaDigest) + && matchesSource(status, current.source) + && status.regionEpoch() == current.regionEpoch + && status.lastCommittedTickId() == current.lastCommittedTickId; + } + boolean matchesTimelinePreparation( TimelinePreparation preparation, CanonicalGameplayBindingProvisionalCasEvidence evidence, @@ -809,12 +860,48 @@ private static boolean matchesSource(CanonicalGameplayRegionRuntimeStatus status && status.regionId().equals(source.regionId()) && status.lifecycleEpoch() == source.lifecycleEpoch() && status.lifecycleRowVersion() == source.lifecycleRowVersion() - && status.lifecycleRequest().equals(source.lifecycleRequest()) + && sameLifecycleRequestExceptReadRequestId( + status.lifecycleRequest(), source.lifecycleRequest()) && status.captureId().equals(source.captureId()) && status.graphSha256().equals(source.graphSha256()) && status.preparationInputDigest().equals(source.preparationInputDigest()); } + static boolean sameRegionSource(Source expected, Source actual) { + return expected.tenantId().equals(actual.tenantId()) + && expected.gameInstanceId().equals(actual.gameInstanceId()) + && expected.canonicalRegionId().equals(actual.canonicalRegionId()) + && expected.regionId().equals(actual.regionId()) + && expected.lifecycleEpoch() == actual.lifecycleEpoch() + && expected.lifecycleRowVersion() == actual.lifecycleRowVersion() + && sameLifecycleRequestExceptReadRequestId( + expected.lifecycleRequest(), actual.lifecycleRequest()) + && expected.captureId().equals(actual.captureId()) + && expected.graphSha256().equals(actual.graphSha256()) + && expected.preparationInputDigest().equals(actual.preparationInputDigest()); + } + + static boolean sameLifecycleRequestExceptReadRequestId( + WorldCanonicalInstanceLifecycleEvidence.Request expected, + WorldCanonicalInstanceLifecycleEvidence.Request actual) { + return expected.schemaVersion() == actual.schemaVersion() + && expected.targetNamespace().equals(actual.targetNamespace()) + && expected.canonicalTenantId().equals(actual.canonicalTenantId()) + && expected.worldSlug().equals(actual.worldSlug()) + && expected.canonicalGameInstanceId().equals(actual.canonicalGameInstanceId()) + && expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) + && expected.playableStateScope().equals(actual.playableStateScope()) + && expected.publicProduction() == actual.publicProduction() + && expected.controlPlaneRequestId().equals(actual.controlPlaneRequestId()) + && expected.canonicalVersionId().equals(actual.canonicalVersionId()) + && expected.expectedDescriptorRequestDigest() + .equals(actual.expectedDescriptorRequestDigest()) + && expected.expectedDescriptorResultDigest() + .equals(actual.expectedDescriptorResultDigest()) + && expected.expectedReleaseAttestationDigest() + .equals(actual.expectedReleaseAttestationDigest()); + } + private static boolean matchesLeaseGeneration( CanonicalGameplayRegionRuntimeStatus status, long regionEpoch, diff --git a/services/game-session-service/src/main/resources/db/migration/V1044.1__retained_region_bridge_abort_source.sql b/services/game-session-service/src/main/resources/db/migration/V1044.1__retained_region_bridge_abort_source.sql new file mode 100644 index 0000000000..ae7f5bd4e3 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1044.1__retained_region_bridge_abort_source.sql @@ -0,0 +1,231 @@ +-- Preserve an exact completed per-binding region bridge as abort source evidence. +-- The ACK remains unresolved cleanup input; it is not a cleanup or admission claim. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_first_new_abort_source_complete() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + affected_transition_id uuid; + initial_abort_transition boolean := false; +BEGIN + IF TG_OP = 'DELETE' THEN affected_transition_id := OLD.transition_id; + ELSE affected_transition_id := NEW.transition_id; + END IF; + IF TG_TABLE_NAME = 'game_session_canonical_binding_transition' + AND TG_OP = 'UPDATE' THEN + IF OLD.status = 'PROVISIONAL' AND NEW.status = 'ABORTED' THEN + initial_abort_transition := true; + END IF; + END IF; + IF NOT EXISTS (SELECT 1 FROM game_session_canonical_binding_transition + WHERE transition_id = affected_transition_id AND status = 'ABORTED' + AND admission_orphan_cleanup_id IS NOT NULL) THEN + RETURN NULL; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_issuer_partition_reservation reservation + ON reservation.reservation_id = transition.issuer_reservation_id + JOIN game_session_canonical_binding_account_index_obligation account_obligation + ON account_obligation.transition_id = transition.transition_id + AND account_obligation.obligation_ordinal = 0 + JOIN game_session_canonical_binding_issuer_index_obligation issuer_obligation + ON issuer_obligation.transition_id = transition.transition_id + AND issuer_obligation.binding_ref = transition.candidate_binding_ref + JOIN game_session_canonical_binding_region_bridge_obligation region_obligation + ON region_obligation.transition_id = transition.transition_id + WHERE transition.transition_id = affected_transition_id + AND transition.status = 'ABORTED' + AND transition.admission_lease_id IS NOT NULL + AND transition.admission_lease_kind = 'NEW_BINDING' + AND transition.admission_lease_evidence IS NOT NULL + AND transition.admission_lease_digest IS NOT NULL + AND transition.expected_prior_binding_ref IS NULL + AND transition.expected_prior_binding_generation IS NULL + AND transition.admission_orphan_cleanup_id IS NOT NULL + AND transition.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND transition.inventory_revision = candidate.inventory_revision + AND transition.inventory_revision = reservation.inventory_revision + AND transition.inventory_revision = account_obligation.inventory_revision + AND transition.inventory_revision = issuer_obligation.inventory_revision + AND transition.inventory_revision = region_obligation.inventory_revision + AND transition.candidate_binding_ref = candidate.binding_ref + AND transition.candidate_binding_generation = candidate.binding_generation + AND transition.candidate_account_index_fence = candidate.account_index_fence + AND transition.issuer_reservation_id = candidate.issuer_reservation_id + AND transition.tenant_id = candidate.tenant_id + AND transition.playable_state_namespace_id = candidate.playable_state_namespace_id + AND transition.character_id = candidate.character_id + AND candidate.lifecycle = 'TERMINAL_UNRESOLVED' + AND reservation.lifecycle IN ('RELEASE_PENDING', 'RELEASED') + AND reservation.transition_id = transition.transition_id + AND reservation.binding_ref = candidate.binding_ref + AND reservation.binding_generation = candidate.binding_generation + AND reservation.reservation_fence IS NOT NULL + AND reservation.account_id = candidate.account_id + AND reservation.tenant_id = candidate.tenant_id + AND reservation.playable_state_namespace_id = candidate.playable_state_namespace_id + AND reservation.character_id = candidate.character_id + AND reservation.game_instance_id = candidate.game_instance_id + AND reservation.runtime_game_instance_id = candidate.runtime_game_instance_id + AND reservation.session_id = candidate.session_id + AND reservation.region_id = candidate.region_id + AND reservation.region_epoch = candidate.region_epoch + AND reservation.issuer_id = candidate.issuer_id + AND reservation.issuer_auth_generation = candidate.issuer_auth_generation + AND reservation.issuer_index_layout_version = candidate.issuer_index_layout_version + AND reservation.issuer_index_partition_count = candidate.issuer_index_partition_count + AND reservation.issuer_index_partition_capacity = candidate.issuer_index_partition_capacity + AND account_obligation.binding_ref = candidate.binding_ref + AND account_obligation.account_id = candidate.account_id + AND account_obligation.tenant_id = candidate.tenant_id + AND account_obligation.action = 'ADD_OR_RETAIN' + AND account_obligation.binding_generation = candidate.binding_generation + AND account_obligation.expected_prior_generation IS NULL + AND account_obligation.account_index_fence = candidate.account_index_fence + AND account_obligation.execution_phase = 'BEFORE_FINAL_CAS' + AND ( + (account_obligation.status = 'REQUIRED' AND candidate.account_index_state = 'REPAIR_REQUIRED') + OR (account_obligation.status = 'ACKNOWLEDGED' + AND candidate.account_index_state = 'ACKNOWLEDGED' + AND account_obligation.projection_state = 'PRESENT_AWAITING_COVERAGE' + AND EXISTS ( + SELECT 1 FROM game_session_canonical_account_member_repair_operation repair + WHERE repair.transition_id = transition.transition_id + AND repair.obligation_ordinal = 0 + AND repair.status = 'ACKNOWLEDGED' + AND repair.binding_ref = candidate.binding_ref + AND repair.account_id = candidate.account_id + AND repair.tenant_id = candidate.tenant_id + AND repair.binding_generation = candidate.binding_generation + AND repair.account_index_fence = candidate.account_index_fence + AND repair.original_action = 'ADD_OR_RETAIN' + AND repair.original_expected_prior_generation IS NULL + AND repair.original_execution_phase = 'BEFORE_FINAL_CAS' + AND repair.original_status = 'REQUIRED' + AND repair.desired_action = 'ADD_OR_RETAIN' + AND repair.account_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND ( + NOT initial_abort_transition + OR EXISTS ( + SELECT 1 + FROM game_session_canonical_account_coverage_control control + WHERE control.account_id = repair.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = repair.account_control_epoch)) + AND repair.coverage_generation > repair.inventory_snapshot_revision + AND repair.completed_inventory_revision > repair.inventory_snapshot_revision + AND repair.completed_inventory_revision < transition.inventory_revision + AND repair.readback_state = 'PRESENT' + AND repair.readback_member = repair.member + AND repair.member = account_obligation.projection_member + AND repair.member = 'accountIndexMember/v1:' + || rtrim(translate(replace(encode(candidate.binding_ref, 'base64'), E'\n', ''), '+/', '-_'), '=') + || ':' || candidate.binding_generation::text || ':' || candidate.account_index_fence::text + AND ((repair.original_projection_state = 'REQUIRED' + AND account_obligation.projection_inventory_revision = repair.completed_inventory_revision) + OR (repair.original_projection_state = 'PRESENT_AWAITING_COVERAGE' + AND repair.original_projection_member = repair.member + AND account_obligation.projection_inventory_revision = repair.original_projection_inventory_revision)) + )) + ) + AND (SELECT count(*) + FROM game_session_canonical_binding_account_index_obligation extra_account + WHERE extra_account.transition_id = transition.transition_id) = 1 + AND issuer_obligation.reservation_id = reservation.reservation_id + AND issuer_obligation.binding_ref = candidate.binding_ref + AND issuer_obligation.binding_generation = candidate.binding_generation + AND ( + (issuer_obligation.status = 'REQUIRED' + AND issuer_obligation.local_release_operation_id IS NULL + AND reservation.lifecycle = 'RELEASE_PENDING' + AND NOT EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_binding_local_release_operation pending_release + WHERE pending_release.transition_id = transition.transition_id + AND pending_release.status <> 'PENDING_PHYSICAL_PROOF')) + OR (issuer_obligation.status = 'RELEASED' + AND issuer_obligation.local_release_operation_id IS NOT NULL + AND reservation.lifecycle = 'RELEASED' + AND EXISTS ( + SELECT 1 FROM game_session_canonical_issuer_binding_local_release_operation released + WHERE released.operation_id = issuer_obligation.local_release_operation_id + AND released.transition_id = transition.transition_id + AND released.orphan_cleanup_id = transition.admission_orphan_cleanup_id + AND released.reservation_id = reservation.reservation_id + AND released.binding_ref = candidate.binding_ref + AND released.binding_generation = candidate.binding_generation + AND released.status = 'RELEASED' + AND released.source_inventory_revision < transition.inventory_revision + AND released.completion_inventory_revision = transition.inventory_revision + AND released.physical_readback_field_set_bytes IS NOT NULL + AND released.physical_readback_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND released.released_member_value_bytes IS NOT NULL + AND released.released_member_value_digest ~ '^sha256:[0-9a-f]{64}$')) + ) + AND (SELECT count(*) + FROM game_session_canonical_binding_issuer_index_obligation extra_issuer + WHERE extra_issuer.transition_id = transition.transition_id) = 1 + AND region_obligation.binding_ref = candidate.binding_ref + AND region_obligation.binding_generation = candidate.binding_generation + AND region_obligation.account_id = candidate.account_id + AND region_obligation.tenant_id = candidate.tenant_id + AND region_obligation.game_instance_id = candidate.game_instance_id + AND region_obligation.runtime_game_instance_id = candidate.runtime_game_instance_id + AND region_obligation.session_id = candidate.session_id + AND region_obligation.region_id = candidate.region_id + AND region_obligation.region_epoch = candidate.region_epoch + AND ( + region_obligation.status = 'REQUIRED' + OR (region_obligation.status = 'ACKNOWLEDGED' + AND region_obligation.bridge_operation_id IS NOT NULL + AND region_obligation.bridge_preimage_state = 'ABSENT' + AND region_obligation.runtime_entity_id > 0 + AND region_obligation.entity_projection_generation > 0 + AND region_obligation.entity_projection_fence > 0 + AND region_obligation.entity_workload_namespace IS NOT NULL + AND region_obligation.entity_workload_namespace <> '' + AND region_obligation.entity_workload_namespace = + btrim(region_obligation.entity_workload_namespace) + AND region_obligation.entity_workload_namespace !~ '[[:cntrl:]]' + AND region_obligation.assignment_uuid IS NOT NULL + AND region_obligation.assignment_uuid <> + '00000000-0000-0000-0000-000000000000'::uuid + AND region_obligation.assignment_intent_digest ~ '^[0-9a-f]{64}$' + AND region_obligation.entity_reference_digest ~ '^[0-9a-f]{64}$' + AND region_obligation.world_source_digest ~ '^[0-9a-f]{64}$' + AND region_obligation.canonical_region_id IS NOT NULL + AND region_obligation.canonical_region_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND region_obligation.world_lifecycle_epoch > 0 + AND region_obligation.world_lifecycle_row_version >= 0 + AND region_obligation.world_capture_id IS NOT NULL + AND region_obligation.world_capture_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND region_obligation.world_graph_sha256 ~ '^[0-9a-f]{64}$' + AND region_obligation.world_preparation_input_digest ~ '^sha256:[0-9a-f]{64}$' + AND region_obligation.executor_fence > 0 + AND region_obligation.lease_token_correlation ~ '^[0-9a-f]{64}$' + AND region_obligation.redis_readback_digest ~ '^[0-9a-f]{64}$' + AND region_obligation.acknowledged_at IS NOT NULL) + ) + AND NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_gameplay_binding_inventory active + WHERE active.tenant_id = candidate.tenant_id + AND active.playable_state_namespace_id = candidate.playable_state_namespace_id + AND active.character_id = candidate.character_id + AND active.lifecycle = 'ACTIVE') + ) THEN + RAISE EXCEPTION 'First-NEW Account abort requires its exact retained candidate, reservation, and unresolved obligations' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_source_incomplete'; + END IF; + RETURN NULL; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index f0ef2dd7a8..f423fb01c3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -41,6 +41,7 @@ import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import org.jooq.DSLContext; +import org.jooq.Record; /** * Test-only wrapper for the package-private Game Session region owners. It starts from an actual @@ -67,6 +68,50 @@ public static Proof installAndBridge( CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) throws Exception { + return installAndBridgeInternal( + dsl, + redisHost, + redisPort, + worldRequest, + currentTarget, + worldRegionResolver, + entityReferenceClient, + null) + .first(); + } + + /** Runs the real first owner chain, then exercises a second candidate under its private grant. */ + public static TwoBindingProof installAndBridgeTwoCandidates( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest firstWorldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver firstWorldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient firstEntityReferenceClient, + SecondBinding secondBinding) + throws Exception { + return installAndBridgeInternal( + dsl, + redisHost, + redisPort, + firstWorldRequest, + currentTarget, + firstWorldRegionResolver, + firstEntityReferenceClient, + java.util.Objects.requireNonNull(secondBinding, "secondBinding")); + } + + private static TwoBindingProof installAndBridgeInternal( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + SecondBinding secondBinding) + throws Exception { UUID transitionId = UUID.randomUUID(); UUID sessionId = UUID.randomUUID(); var resolved = worldRegionResolver.resolve(worldRequest); @@ -129,6 +174,8 @@ public static Proof installAndBridge( "test", "test", "controlled-test-image"); + CanonicalPreseededActorRuntimeReferenceClient bridgeEntityReferenceClient = + secondBinding == null ? entityReferenceClient : secondBinding.entityReferenceClient(); var bridgeOwner = CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( dsl, @@ -136,7 +183,7 @@ public static Proof installAndBridge( scriptCatalog, stableSource, worldRegionResolver, - entityReferenceClient, + bridgeEntityReferenceClient, runtimeIdentity, Duration.ofSeconds(30), Clock.systemUTC()); @@ -160,18 +207,22 @@ public static Proof installAndBridge( || !"game-session-service".equals(status.ownerService())) { throw new IllegalStateException("Initial region SQL fence is not the expected live owner"); } + String initialMetaKey = + CanonicalGameplayRegionRedisKeys.meta( + identity.tenantId(), identity.gameInstanceId(), status.regionId()); + byte[] redisKey = + ascii( + CanonicalGameplayRegionRedisKeys.lease( + identity.tenantId(), identity.gameInstanceId(), status.regionId())); byte[] currentTickState = redis .admin() - .hget( - ascii( - CanonicalGameplayRegionRedisKeys.meta( - identity.tenantId(), identity.gameInstanceId(), status.regionId())), - ascii("current_tick_state")); + .hget(ascii(initialMetaKey), ascii("current_tick_state")); if (!Arrays.equals(currentTickState, ascii("APPLIED"))) { throw new IllegalStateException("Canonical Redis initial timeline metadata is absent"); } - return new Proof( + Proof firstProof = + new Proof( transitionId, sessionId, identity.regionId(), @@ -190,7 +241,340 @@ public static Proof installAndBridge( acknowledged.inventoryRevision(), acknowledged.acknowledgedAt(), acknowledged.equals(replayed)); + if (secondBinding == null) { + return new TwoBindingProof(firstProof, null, null, true, true, true, true, true); + } + + AccountAbortProof firstAbort = abortAfterBridge(dsl, firstProof); + Record firstTimelineBefore = + dsl.fetchOne( + "SELECT initialization_operation_id, transition_id, lifecycle_request_bytes," + + " preparation_digest, world_source_digest" + + " FROM game_session_region_timeline_preparation" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + identity.tenantId(), + identity.gameInstanceId(), + identity.regionId()); + String firstTimelineOperationId = + firstTimelineBefore.get("initialization_operation_id", UUID.class).toString(); + String firstTimelineDigest = firstTimelineBefore.get("preparation_digest", String.class); + String firstWorldSourceDigest = + firstTimelineBefore.get("world_source_digest", String.class); + byte[] firstLifecycleRequest = + firstTimelineBefore.get("lifecycle_request_bytes", byte[].class); + byte[] firstMetaOperation = + redis + .admin() + .hget(ascii(initialMetaKey), ascii("first_timeline_operation_id")); + byte[] firstMetaDigest = + redis + .admin() + .hget(ascii(initialMetaKey), ascii("first_timeline_source_digest")); + + var secondResolved = secondBinding.worldRegionResolver().resolve(secondBinding.worldRequest()); + requireExactCurrentTarget(secondBinding.worldRequest(), secondBinding.currentTarget()); + UUID secondTransitionId = UUID.randomUUID(); + UUID secondSessionId = UUID.randomUUID(); + var secondIdentity = + new CanonicalGameplayBindingIdentity( + UUID.fromString(secondBinding.worldRequest().getCanonicalAccountUuid()), + secondBinding.currentTarget().canonicalTenantId(), + secondBinding.currentTarget().playableStateNamespaceId(), + UUID.fromString(secondBinding.worldRequest().getCharacterUuid()), + secondBinding.currentTarget().playableStateScope(), + secondBinding.currentTarget().canonicalGameInstanceId(), + secondBinding.currentTarget().gameInstanceId(), + secondSessionId.toString(), + secondResolved.operationalRegionId(), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(64)); + var secondPrepared = + inventory.prepare( + new CanonicalGameplayBindingTransitionRequest( + secondTransitionId, + UUID.randomUUID(), + secondIdentity, + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE), + null, + null)); + AccountGameplayAdmissionLeaseEvidence secondLease = + controlledNewBindingLease( + secondIdentity, secondBinding.currentTarget(), secondPrepared.bindingGeneration()); + inventory.markProvisional( + inventory.readProvisionalCasEvidence(secondTransitionId), + new CanonicalGameplayAdmissionDecision( + secondTransitionId, + secondLease, + secondIdentity, + secondPrepared.bindingGeneration(), + null, + secondBinding.currentTarget())); + var secondInstallation = + bridgeOwner.installForTransition( + installation, secondTransitionId, secondBinding.worldRequest()); + var secondAcknowledgement = bridgeOwner.bridge(secondInstallation).obligation(); + var secondLostReplyRetry = bridgeOwner.bridge(secondInstallation).obligation(); + if (!secondAcknowledgement.equals(secondLostReplyRetry) + || secondAcknowledgement.status() + != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED + || secondAcknowledgement.transitionId().equals(acknowledged.transitionId()) + || secondAcknowledgement.bridgeOperationId().equals(acknowledged.bridgeOperationId()) + || !secondAcknowledgement.inventoryRevision().equals(secondLostReplyRetry.inventoryRevision())) { + throw new IllegalStateException("Second binding did not retain its independent exact ACK"); + } + var secondStatus = + new CanonicalGameplayRegionRuntimeStatusRepository(dsl) + .find(secondInstallation.source) + .orElseThrow(); + Record firstTimelineAfter = + dsl.fetchOne( + "SELECT initialization_operation_id, transition_id, lifecycle_request_bytes," + + " preparation_digest, world_source_digest" + + " FROM game_session_region_timeline_preparation" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + identity.tenantId(), + identity.gameInstanceId(), + identity.regionId()); + byte[] secondMetaOperation = + redis + .admin() + .hget(ascii(initialMetaKey), ascii("first_timeline_operation_id")); + byte[] secondMetaDigest = + redis + .admin() + .hget(ascii(initialMetaKey), ascii("first_timeline_source_digest")); + byte[] secondMetaRegionEpoch = + redis.admin().hget(ascii(initialMetaKey), ascii("region_epoch")); + byte[] secondMetaTickId = + redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_id")); + byte[] secondMetaTickState = + redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_state")); + boolean unchangedTimeline = + firstTimelineOperationId + .equals(firstTimelineAfter.get("initialization_operation_id", UUID.class).toString()) + && transitionId.equals(firstTimelineAfter.get("transition_id", UUID.class)) + && Arrays.equals( + firstLifecycleRequest, + firstTimelineAfter.get("lifecycle_request_bytes", byte[].class)) + && firstTimelineDigest.equals(firstTimelineAfter.get("preparation_digest", String.class)) + && firstWorldSourceDigest.equals( + firstTimelineAfter.get("world_source_digest", String.class)) + && Arrays.equals(firstMetaOperation, secondMetaOperation) + && Arrays.equals(firstMetaDigest, secondMetaDigest) + && Arrays.equals(secondMetaRegionEpoch, ascii("1")) + && Arrays.equals(secondMetaTickId, ascii("-1")) + && Arrays.equals(secondMetaTickState, ascii("APPLIED")) + && secondStatus.regionEpoch() == 1L + && secondStatus.lastCommittedTickId() == -1L; + if (!unchangedTimeline + || !status.leaseTokenCorrelation().equals(secondStatus.leaseTokenCorrelation()) + || redis.admin().pttl(redisKey) <= 0L + || redis.admin().pttl(ascii(initialMetaKey)) != -1L) { + throw new IllegalStateException( + "Second binding changed first timeline provenance or lost the live region grant"); + } + boolean regionLeaseStillLive = redis.admin().pttl(redisKey) > 0L; + List> sqlBeforeForeignOwner = + snapshotRegionOwnerSqlState( + dsl, identity.tenantId(), identity.gameInstanceId(), identity.regionId()); + RegionRedisState redisBeforeForeignOwner = + snapshotRegionRedisState(redis, redisKey, initialMetaKey); + var foreignBridgeOwner = + CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( + dsl, + redis.ownerClient(), + scriptCatalog, + stableSource, + secondBinding.worldRegionResolver(), + secondBinding.entityReferenceClient(), + runtimeIdentity, + Duration.ofSeconds(30), + Clock.systemUTC()); + boolean foreignOwnerInstallationRejected; + try { + foreignBridgeOwner.installForTransition( + installation, secondTransitionId, secondBinding.worldRequest()); + foreignOwnerInstallationRejected = false; + } catch (IllegalStateException expected) { + foreignOwnerInstallationRejected = + "Canonical Game Session region owner requires current exact assignment and lease evidence" + .equals(expected.getMessage()); + } + boolean foreignOwnerCapabilityRejectedWithoutStateChange = + foreignOwnerInstallationRejected + && sqlBeforeForeignOwner.equals( + snapshotRegionOwnerSqlState( + dsl, identity.tenantId(), identity.gameInstanceId(), identity.regionId())) + && redisBeforeForeignOwner.equals( + snapshotRegionRedisState(redis, redisKey, initialMetaKey)) + && redis.admin().pttl(redisKey) > 0L + && redis.admin().pttl(ascii(initialMetaKey)) == -1L; + if (!foreignOwnerCapabilityRejectedWithoutStateChange) { + throw new IllegalStateException( + "A foreign region owner accepted or changed state for another owner's installation"); + } + redis.admin().pexpire(redisKey, 0L); + List> sqlBeforeExpiredGrant = + snapshotRegionOwnerSqlState( + dsl, identity.tenantId(), identity.gameInstanceId(), identity.regionId()); + RegionRedisState redisBeforeExpiredGrant = + snapshotRegionRedisState(redis, redisKey, initialMetaKey); + boolean expiredGrantInstallationRejected; + try { + bridgeOwner.installForTransition( + secondInstallation, secondTransitionId, secondBinding.worldRequest()); + expiredGrantInstallationRejected = false; + } catch (IllegalStateException expected) { + expiredGrantInstallationRejected = true; + } + boolean expiredGrantRejectedWithoutStateChange = + expiredGrantInstallationRejected + && sqlBeforeExpiredGrant.equals( + snapshotRegionOwnerSqlState( + dsl, identity.tenantId(), identity.gameInstanceId(), identity.regionId())) + && redisBeforeExpiredGrant.equals( + snapshotRegionRedisState(redis, redisKey, initialMetaKey)) + && secondStatus.equals( + new CanonicalGameplayRegionRuntimeStatusRepository(dsl) + .find(secondInstallation.source) + .orElseThrow()); + if (!expiredGrantRejectedWithoutStateChange) { + throw new IllegalStateException( + "An expired private region grant was accepted or changed SQL/Redis state"); + } + Proof secondProof = + new Proof( + secondTransitionId, + secondSessionId, + secondIdentity.regionId(), + secondResolved.canonicalRegionInstanceId(), + secondStatus.lifecycleEpoch(), + secondStatus.lifecycleRowVersion(), + secondStatus.regionEpoch(), + secondStatus.executorFence(), + secondAcknowledgement.bridgeOperationId(), + secondAcknowledgement.runtimeEntityId(), + secondAcknowledgement.entityProjectionGeneration(), + secondAcknowledgement.entityProjectionFence(), + secondAcknowledgement.entityReferenceDigest(), + secondAcknowledgement.worldSourceDigest(), + secondAcknowledgement.redisReadbackDigest(), + secondAcknowledgement.inventoryRevision(), + secondAcknowledgement.acknowledgedAt(), + secondAcknowledgement.equals(secondLostReplyRetry)); + return new TwoBindingProof( + firstProof, + secondProof, + firstAbort, + unchangedTimeline, + Arrays.equals(firstMetaOperation, secondMetaOperation) + && Arrays.equals(firstMetaDigest, secondMetaDigest), + regionLeaseStillLive, + foreignOwnerCapabilityRejectedWithoutStateChange, + expiredGrantRejectedWithoutStateChange); + } + } + + /** + * Carries a controlled definitive Account abort through the actual repository after a real + * PostgreSQL/Redis bridge ACK, then proves exact cleanup retry/read preserves that ACK without + * promoting the candidate or claiming cleanup completion. + */ + public static AccountAbortProof abortAfterBridge(DSLContext dsl, Proof bridgeProof) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var before = inventory.readFirstNewAdmissionAbortSource(bridgeProof.transitionId()); + Record acknowledgedBefore = + dsl.fetchOne( + "SELECT status, inventory_revision, redis_readback_digest, acknowledged_at" + + " FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE transition_id = ?", + bridgeProof.transitionId()); + if (acknowledgedBefore == null + || !"ACKNOWLEDGED".equals(acknowledgedBefore.get("status", String.class)) + || !bridgeProof.acknowledgedInventoryRevision() + .equals(new BigInteger(acknowledgedBefore.get("inventory_revision").toString())) + || !bridgeProof.redisReadbackDigest() + .equals(acknowledgedBefore.get("redis_readback_digest", String.class))) { + throw new IllegalStateException("The exact region ACK is not the retained abort source"); } + String acknowledgementImageBefore = + dsl.fetchSingle( + "SELECT (to_jsonb(obligation) - 'inventory_revision')::text AS image" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " WHERE transition_id = ?", + bridgeProof.transitionId()) + .get("image", String.class); + UUID cleanupId = + UUID.nameUUIDFromBytes( + ("controlled-region-bridge-account-abort/" + bridgeProof.transitionId()) + .getBytes(StandardCharsets.UTF_8)); + var aborted = inventory.recordFirstNewAccountAbort(before, cleanupId); + var retrySource = inventory.readFirstNewAdmissionAbortSource(bridgeProof.transitionId()); + var retry = inventory.recordFirstNewAccountAbort(retrySource, cleanupId); + var retained = + inventory.readRetainedDefinitiveFirstNewAccountAbortSource(bridgeProof.transitionId()); + Record acknowledgedAfter = + dsl.fetchOne( + "SELECT status, inventory_revision, redis_readback_digest, acknowledged_at" + + " FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE transition_id = ?", + bridgeProof.transitionId()); + String acknowledgementImageAfter = + dsl.fetchSingle( + "SELECT (to_jsonb(obligation) - 'inventory_revision')::text AS image" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " WHERE transition_id = ?", + bridgeProof.transitionId()) + .get("image", String.class); + if (!aborted.equals(retry) + || !aborted.equals(retained) + || !aborted.isAccountAborted() + || !cleanupId.equals(aborted.orphanCleanupId()) + || aborted.candidate().lifecycle() + != net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED + || aborted.reservation().lifecycle() + != net.firedevops.firemud.gamesession.binding + .CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + || !"ACKNOWLEDGED".equals(acknowledgedAfter.get("status", String.class)) + || !aborted.transition().inventoryRevision() + .equals(acknowledgedAfter.get("inventory_revision", BigInteger.class)) + || !bridgeProof.redisReadbackDigest() + .equals(acknowledgedAfter.get("redis_readback_digest", String.class)) + || !bridgeProof.acknowledgedAt() + .equals( + acknowledgedAfter + .get("acknowledged_at", java.time.OffsetDateTime.class) + .toInstant()) + || !acknowledgedBefore.get("acknowledged_at", java.time.OffsetDateTime.class) + .equals(acknowledgedAfter.get("acknowledged_at", java.time.OffsetDateTime.class)) + || !acknowledgementImageBefore.equals(acknowledgementImageAfter) + || !aborted.transition().inventoryRevision() + .equals(new BigInteger(acknowledgedAfter.get("inventory_revision").toString())) + || aborted.transition().status() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.ABORTED) { + throw new IllegalStateException( + "Definitive Account abort changed region ACK evidence or claimed admission/cleanup"); + } + return new AccountAbortProof( + bridgeProof.transitionId(), + cleanupId, + before.transition().inventoryRevision(), + aborted.transition().inventoryRevision(), + acknowledgementImageBefore.equals(acknowledgementImageAfter), + aborted.candidate().lifecycle().name(), + aborted.reservation().lifecycle().name()); } private static void requireExactCurrentTarget( @@ -446,6 +830,55 @@ private static void requireEmptyCanonical( "1".repeat(64)); } + private static List> snapshotRegionOwnerSqlState( + DSLContext dsl, UUID tenantId, UUID gameInstanceId, UUID regionId) { + return List.of( + dsl.fetch( + "SELECT to_jsonb(runtime_status)::text AS image" + + " FROM game_session_region_runtime_status runtime_status" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " ORDER BY tenant_id, game_instance_id, region_id", + tenantId, + gameInstanceId, + regionId) + .getValues("image", String.class), + dsl.fetch( + "SELECT to_jsonb(preparation)::text AS image" + + " FROM game_session_region_timeline_preparation preparation" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " ORDER BY initialization_operation_id", + tenantId, + gameInstanceId, + regionId) + .getValues("image", String.class), + dsl.fetch( + "SELECT to_jsonb(obligation)::text AS image" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " ORDER BY transition_id", + tenantId, + gameInstanceId, + regionId) + .getValues("image", String.class)); + } + + private static RegionRedisState snapshotRegionRedisState( + RegionRedis redis, byte[] leaseKey, String metaKey) { + Map metadata = new LinkedHashMap<>(); + redis.admin() + .hgetall(ascii(metaKey)) + .forEach( + (field, value) -> metadata.put(asciiString(field), asciiString(value))); + return new RegionRedisState( + redis.admin().type(leaseKey), + asciiString(redis.admin().get(leaseKey)), + Map.copyOf(metadata)); + } + + private static String asciiString(byte[] value) { + return value == null ? null : new String(value, StandardCharsets.US_ASCII); + } + private static byte[] ascii(String value) { return value.getBytes(StandardCharsets.US_ASCII); } @@ -470,6 +903,34 @@ public record Proof( Instant acknowledgedAt, boolean exactLostReplyRetry) {} + public record SecondBinding( + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) {} + + public record TwoBindingProof( + Proof first, + Proof second, + AccountAbortProof firstAbort, + boolean firstTimelineUnchanged, + boolean initialMetaUnchanged, + boolean regionLeaseStillLive, + boolean foreignOwnerCapabilityRejectedWithoutStateChange, + boolean expiredGrantRejectedWithoutStateChange) {} + + private record RegionRedisState( + String leaseType, String leaseValue, Map metadata) {} + + public record AccountAbortProof( + UUID transitionId, + UUID cleanupId, + BigInteger acknowledgedRevision, + BigInteger abortRevision, + boolean exactAcknowledgementRetained, + String candidateLifecycle, + String reservationLifecycle) {} + private static final class ControlledStableIncarnationSource implements CanonicalGameplayRegionIncarnationSource { @Override diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index b2c3c0be23..36d5ff4f0f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -212,6 +212,58 @@ void sameNaturalScopeRejectsChangedWorldCaptureEvidence() { .isInstanceOf(IllegalStateException.class); } + @Test + void ownerGrantAcceptsOnlyChangedLifecycleReadCorrelationAndKeepsInitialRequestBytes() { + var initial = + repository.installOwner( + source, + 1L, + null, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:01Z")); + var laterRequest = + lifecycleRequest( + source.lifecycleRequest(), UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + source.lifecycleRequest().controlPlaneRequestId()); + var laterSource = source(source, laterRequest); + + var later = + repository.installOwner( + laterSource, + 1L, + initial, + SECOND_LEASE_CORRELATION, + "game-session-service", + "instance-b", + Instant.parse("2026-10-26T00:00:02Z")); + + assertThat(later.executorFence()).isGreaterThan(initial.executorFence()); + assertThat(later.regionEpoch()).isEqualTo(1L); + assertThat(later.lastCommittedTickId()).isEqualTo(-1L); + assertThat( + dsl.fetchSingle( + "SELECT lifecycle_request_bytes FROM game_session_region_runtime_status" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?", + TENANT_ID, + GAME_INSTANCE_ID, + OPERATIONAL_REGION_ID) + .get("lifecycle_request_bytes", byte[].class)) + .containsExactly(source.lifecycleRequest().canonicalBytes()); + assertThat(repository.find(laterSource)).contains(later); + + var changedTargetSelector = + source( + source, + lifecycleRequest( + laterRequest, + laterRequest.readRequestId(), + "different-control-plane-request")); + assertThatThrownBy(() -> repository.find(changedTargetSelector)) + .isInstanceOf(IllegalStateException.class); + } + @Test void sameRegionInDifferentGameInstancesHasDistinctPersistedOwnerTags() { var first = @@ -339,4 +391,41 @@ private static CanonicalGameplayRegionRuntimeStatusRepository.Source source( GRAPH_DIGEST, PREPARATION_DIGEST); } + + private static CanonicalGameplayRegionRuntimeStatusRepository.Source source( + CanonicalGameplayRegionRuntimeStatusRepository.Source original, + WorldCanonicalInstanceLifecycleEvidence.Request request) { + return new CanonicalGameplayRegionRuntimeStatusRepository.Source( + original.tenantId(), + original.gameInstanceId(), + original.canonicalRegionId(), + original.regionId(), + original.lifecycleEpoch(), + original.lifecycleRowVersion(), + request, + original.captureId(), + original.graphSha256(), + original.preparationInputDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + WorldCanonicalInstanceLifecycleEvidence.Request original, + UUID readRequestId, + String controlPlaneRequestId) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + original.schemaVersion(), + readRequestId, + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.canonicalGameInstanceId(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.publicProduction(), + controlPlaneRequestId, + original.canonicalVersionId(), + original.expectedDescriptorRequestDigest(), + original.expectedDescriptorResultDigest(), + original.expectedReleaseAttestationDigest()); + } } 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 88d146e544..a379d86e3d 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 @@ -3388,15 +3388,28 @@ private static void composeActualEntityWorldRegionPrerequisite( .isEqualTo(currentTarget.activeWorldEpoch()); assertThat(worldRegion.operationalRegionId()).isNotEqualTo(new UUID(0L, 0L)); - var regionProof = - CanonicalGameplayRegionOwnerCompositionFixture.installAndBridge( + var secondBinding = + controlledSecondBinding( + placementRequest, + currentTarget, + assignmentTarget, + initialLocationClient, + lifecycleClient, + runtimeReferenceClient, + lifecycleClient.read(worldRegion.lifecycleAssignment().request()), + worldRegion); + var regionProofs = + CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeTwoCandidates( gs.dsl(), REDIS.getHost(), REDIS.getMappedPort(6379), placementRequest, currentTarget, - regionResolver, - runtimeReferenceClient); + secondBinding.worldRegionResolver(), + runtimeReferenceClient, + secondBinding); + var regionProof = regionProofs.first(); + var secondRegionProof = regionProofs.second(); assertThat(regionProof.operationalRegionId()) .isEqualTo(worldRegion.operationalRegionId()); assertThat(regionProof.canonicalRegionId()) @@ -3414,6 +3427,27 @@ private static void composeActualEntityWorldRegionPrerequisite( assertThat(regionProof.acknowledgedInventoryRevision()).isPositive(); assertThat(regionProof.acknowledgedAt()).isNotNull(); assertThat(regionProof.exactLostReplyRetry()).isTrue(); + assertThat(secondRegionProof).isNotNull(); + assertThat(secondRegionProof.transitionId()).isNotEqualTo(regionProof.transitionId()); + assertThat(secondRegionProof.bridgeOperationId()) + .isNotEqualTo(regionProof.bridgeOperationId()); + assertThat(secondRegionProof.redisReadbackDigest()) + .isNotEqualTo(regionProof.redisReadbackDigest()); + assertThat(secondRegionProof.exactLostReplyRetry()).isTrue(); + assertThat(regionProofs.firstAbort().exactAcknowledgementRetained()).isTrue(); + assertThat(regionProofs.firstAbort().acknowledgedRevision()) + .isEqualTo(regionProof.acknowledgedInventoryRevision()); + assertThat(regionProofs.firstAbort().abortRevision()) + .isGreaterThan(regionProofs.firstAbort().acknowledgedRevision()); + assertThat(regionProofs.firstAbort().candidateLifecycle()) + .isEqualTo("TERMINAL_UNRESOLVED"); + assertThat(regionProofs.firstAbort().reservationLifecycle()) + .isEqualTo("RELEASE_PENDING"); + assertThat(regionProofs.firstTimelineUnchanged()).isTrue(); + assertThat(regionProofs.initialMetaUnchanged()).isTrue(); + assertThat(regionProofs.regionLeaseStillLive()).isTrue(); + assertThat(regionProofs.foreignOwnerCapabilityRejectedWithoutStateChange()).isTrue(); + assertThat(regionProofs.expiredGrantRejectedWithoutStateChange()).isTrue(); } } finally { shutdown(worldLocationServer); @@ -3454,6 +3488,166 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( .build(); } + private static CanonicalGameplayRegionOwnerCompositionFixture.SecondBinding + controlledSecondBinding( + CanonicalInitialPlayerLocationRequest firstRequest, + CanonicalPlayableTarget currentTarget, + PreseededActorAssignmentExpectedTarget assignmentTarget, + CanonicalInitialPlayerLocationClient actualInitialLocationClient, + WorldCanonicalInstanceLifecycleClient actualLifecycleClient, + CanonicalPreseededActorRuntimeReferenceClient actualEntityReferenceClient, + WorldCanonicalInstanceLifecycleEvidence firstLifecycleEvidence, + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion firstResolvedRegion) { + UUID placementOperationId = UUID.randomUUID(); + UUID assignmentId = UUID.randomUUID(); + UUID characterId = UUID.randomUUID(); + CanonicalInitialPlayerLocationRequest secondRequest = + firstRequest.toBuilder() + .setPlacementOperationUuid(placementOperationId.toString()) + .setAssignmentUuid(assignmentId.toString()) + .setCharacterUuid(characterId.toString()) + .setAssignmentIntentDigest("c".repeat(64)) + .build(); + var originalLifecycleRequest = firstLifecycleEvidence.request(); + var secondLifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + originalLifecycleRequest.schemaVersion(), + worldInitialLocationLifecycleReadId(placementOperationId), + originalLifecycleRequest.targetNamespace(), + originalLifecycleRequest.canonicalTenantId(), + originalLifecycleRequest.worldSlug(), + originalLifecycleRequest.canonicalGameInstanceId(), + originalLifecycleRequest.playableStateNamespaceId(), + originalLifecycleRequest.playableStateScope(), + originalLifecycleRequest.publicProduction(), + originalLifecycleRequest.controlPlaneRequestId(), + originalLifecycleRequest.canonicalVersionId(), + originalLifecycleRequest.expectedDescriptorRequestDigest(), + originalLifecycleRequest.expectedDescriptorResultDigest(), + originalLifecycleRequest.expectedReleaseAttestationDigest()); + var secondLifecycleEvidence = + new WorldCanonicalInstanceLifecycleEvidence( + secondLifecycleRequest, + firstLifecycleEvidence.launchBinding(), + firstLifecycleEvidence.startLocation(), + firstLifecycleEvidence.runtimeRoomInstanceId(), + firstLifecycleEvidence.lifecycleStatus(), + firstLifecycleEvidence.lifecycleEpoch(), + firstLifecycleEvidence.rowVersion(), + firstLifecycleEvidence.captureId(), + firstLifecycleEvidence.graphSha256(), + firstLifecycleEvidence.preparationInputDigest(), + firstLifecycleEvidence.operationalRegionAssignments()); + + var initialLocationClient = Mockito.mock(CanonicalInitialPlayerLocationClient.class); + var originalPlacement = firstResolvedRegion.observation().getPlacementResult(); + var secondPlacement = + originalPlacement.toBuilder() + .setPlacementOperationUuid(secondRequest.getPlacementOperationUuid()) + .setCanonicalAccountUuid(secondRequest.getCanonicalAccountUuid()) + .setCharacterUuid(secondRequest.getCharacterUuid()) + .setAssignmentUuid(secondRequest.getAssignmentUuid()) + .setAssignmentIntentDigest(secondRequest.getAssignmentIntentDigest()) + .setRequestDigest("d".repeat(64)) + .setResultDigest("e".repeat(64)) + .build(); + var secondLifecycle = + firstResolvedRegion + .observation() + .getLifecycle() + .toBuilder() + .setCanonicalRequestBytes( + com.google.protobuf.ByteString.copyFrom(secondLifecycleRequest.canonicalBytes())) + .build(); + var secondObservation = + firstResolvedRegion + .observation() + .toBuilder() + .setPlacementResult(secondPlacement) + .setLifecycle(secondLifecycle) + .build(); + Mockito.doAnswer( + invocation -> { + CanonicalInitialPlayerLocationRequest request = invocation.getArgument(0); + if (secondRequest.equals(request)) return secondObservation; + return actualInitialLocationClient.readInitialPlayerLocationRegion(request); + }) + .when(initialLocationClient) + .readInitialPlayerLocationRegion(Mockito.any(CanonicalInitialPlayerLocationRequest.class)); + var lifecycleClient = Mockito.mock(WorldCanonicalInstanceLifecycleClient.class); + Mockito.doAnswer( + invocation -> { + WorldCanonicalInstanceLifecycleEvidence.Request request = + invocation.getArgument(0); + if (secondLifecycleRequest.equals(request)) return secondLifecycleEvidence; + return actualLifecycleClient.read(request); + }) + .when(lifecycleClient) + .read(Mockito.any(WorldCanonicalInstanceLifecycleEvidence.Request.class)); + var secondWorldRegionResolver = + new CanonicalInitialPlayerLocationRegionResolver( + initialLocationClient, + new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); + + var entityReferenceClient = Mockito.mock(CanonicalPreseededActorRuntimeReferenceClient.class); + var runtimeReference = + Mockito.mock(CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference.class); + var runtimeEntityId = + Mockito.mock(CanonicalPreseededActorRuntimeReferenceClient.RuntimeEntityId.class); + when(runtimeEntityId.tenantId()).thenReturn(currentTarget.canonicalTenantId()); + when(runtimeEntityId.gameInstanceId()) + .thenReturn(currentTarget.canonicalGameInstanceId().toString()); + when(runtimeEntityId.value()).thenReturn(900_002L); + when(runtimeReference.workloadNamespace()).thenReturn(currentTarget.targetNamespace()); + when(runtimeReference.runtimeEntityId()).thenReturn(runtimeEntityId); + when(runtimeReference.projectionGeneration()).thenReturn(2L); + when(runtimeReference.projectionFence()).thenReturn(2L); + when(runtimeReference.assignmentUuid()).thenReturn(assignmentId); + when(runtimeReference.canonicalAccountUuid()) + .thenReturn(UUID.fromString(secondRequest.getCanonicalAccountUuid())); + when(runtimeReference.characterUuid()).thenReturn(characterId); + when(runtimeReference.intentDigest()).thenReturn(secondRequest.getAssignmentIntentDigest()); + when(runtimeReference.playableStateNamespaceId()) + .thenReturn(currentTarget.playableStateNamespaceId()); + when(runtimeReference.target()).thenReturn(toWire(assignmentTarget)); + when(runtimeReference.publishedOwnerProofDigest()) + .thenReturn(currentTarget.ownerProofDigest()); + when(runtimeReference.corePayload()) + .thenReturn( + net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentCorePayload + .newBuilder() + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .setDisplayName("Controlled Second Region Player") + .build()); + var secondEntityReferenceSelector = + ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(secondRequest.getAssignmentUuid()) + .setCanonicalAccountUuid(secondRequest.getCanonicalAccountUuid()) + .setExpectedTarget(secondRequest.getExpectedTarget()) + .setCharacterUuid(secondRequest.getCharacterUuid()) + .setIntentDigest(secondRequest.getAssignmentIntentDigest()) + .build(); + Mockito.doAnswer( + invocation -> { + ReadPreseededActorRuntimeReferenceRequest request = invocation.getArgument(0); + if (secondEntityReferenceSelector.equals(request)) { + return runtimeReference; + } + return actualEntityReferenceClient.read(request); + }) + .when(entityReferenceClient) + .read(Mockito.any(ReadPreseededActorRuntimeReferenceRequest.class)); + return new CanonicalGameplayRegionOwnerCompositionFixture.SecondBinding( + secondRequest, currentTarget, secondWorldRegionResolver, entityReferenceClient); + } + + private static UUID worldInitialLocationLifecycleReadId(UUID placementOperationId) { + return UUID.nameUUIDFromBytes( + ("firemud-world-initial-location-lifecycle-read/v1/" + placementOperationId) + .getBytes(StandardCharsets.US_ASCII)); + } + private static AssignPreseededActorRequest toWire(PreseededActorAssignmentRequest request) { var target = request.expectedTarget(); return AssignPreseededActorRequest.newBuilder() From 54a88a92b26dcce7e8203e6d86fb3c116ea942f1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:46:02 +1300 Subject: [PATCH 13/36] Align exact region fence comparison and canonical formatting --- ...calGameplayBindingInventoryRepository.java | 5 +- ...nicalGameplayRegionBindingBridgeOwner.java | 3 +- .../CanonicalGameplayRegionLeaseOwner.java | 11 +- ...GameplayRegionRuntimeStatusRepository.java | 14 +-- ...GameplayRegionOwnerCompositionFixture.java | 113 +++++++++--------- ...untimeStatusRepositoryIntegrationTest.java | 7 +- 6 files changed, 72 insertions(+), 81 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index f5f28bf649..004733cfb5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -737,9 +737,8 @@ private static BridgeInputs requireBridgeInputs( || !assignment.captureId().equals(ownerStatus.captureId()) || !assignment.graphSha256().equals(ownerStatus.graphSha256()) || !assignment.preparationInputDigest().equals(ownerStatus.preparationInputDigest()) - || !CanonicalGameplayRegionRuntimeStatusRepository - .sameLifecycleRequestExceptReadRequestId( - assignment.request(), ownerStatus.lifecycleRequest()) + || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( + assignment.request(), ownerStatus.lifecycleRequest()) || assignment.lifecycleEpoch() != ownerStatus.lifecycleEpoch() || assignment.lifecycleRowVersion() != ownerStatus.lifecycleRowVersion() || ownerStatus.paused() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java index ccea6e95ed..302b68b745 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java @@ -44,8 +44,7 @@ CanonicalGameplayRegionLeaseOwner.Installation installForTransition( CanonicalGameplayRegionLeaseOwner.Installation existingRegionInstallation, UUID transitionId, net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { - return regionLeaseOwner.installForTransition( - existingRegionInstallation, transitionId, request); + return regionLeaseOwner.installForTransition(existingRegionInstallation, transitionId, request); } /** Executes only an exact first-NEW bridge from a privately created region installation. */ diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 149d345312..5e37cc1989 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -171,21 +171,14 @@ Installation installForTransition( grant = redisOwner.acquire(source, expectedRegionEpoch, leaseTtl, runtimeIdentity); } else { requireReusableRegionGrant( - existingRegionInstallation, - source, - incarnation, - prior, - expectedRegionEpoch); + existingRegionInstallation, source, incarnation, prior, expectedRegionEpoch); grant = existingRegionInstallation.grant; reusingRegionGrant = true; } } if (reusingRegionGrant) { redisOwner.requireGrantScope( - grant, - existingRegionInstallation.source, - expectedRegionEpoch, - runtimeIdentity); + grant, existingRegionInstallation.source, expectedRegionEpoch, runtimeIdentity); } else { redisOwner.requireGrantScope(grant, source, expectedRegionEpoch, runtimeIdentity); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index 8046b1857a..35405cfa88 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -193,8 +193,7 @@ Optional findTimelinePreparation(Source source) { source.regionId()); if (row == null) return Optional.empty(); TimelinePreparation preparation = toTimelinePreparation(row); - if (!sameRegionSource(preparation.source, source) - || !preparation.tenantRegionTag.equals(tag)) { + if (!sameRegionSource(preparation.source, source) || !preparation.tenantRegionTag.equals(tag)) { throw unavailable(); } return Optional.of(preparation); @@ -242,7 +241,7 @@ && matchesInstalledTimelineInitialization(current, candidateSource, incarnation) && current.leaseTokenCorrelation != null && current.leaseTokenCorrelation.equals(status.leaseTokenCorrelation()) && current.executorFence != null - && status.executorFence().longValueExact() == current.executorFence + && status.executorFence().equals(current.executorFence) && current.redisMetaDigest != null && current.redisMetaDigest.equals(expectedMetaDigest) && matchesSource(status, current.source) @@ -894,11 +893,12 @@ static boolean sameLifecycleRequestExceptReadRequestId( && expected.publicProduction() == actual.publicProduction() && expected.controlPlaneRequestId().equals(actual.controlPlaneRequestId()) && expected.canonicalVersionId().equals(actual.canonicalVersionId()) - && expected.expectedDescriptorRequestDigest() + && expected + .expectedDescriptorRequestDigest() .equals(actual.expectedDescriptorRequestDigest()) - && expected.expectedDescriptorResultDigest() - .equals(actual.expectedDescriptorResultDigest()) - && expected.expectedReleaseAttestationDigest() + && expected.expectedDescriptorResultDigest().equals(actual.expectedDescriptorResultDigest()) + && expected + .expectedReleaseAttestationDigest() .equals(actual.expectedReleaseAttestationDigest()); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index f423fb01c3..26f9af42f3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -215,32 +215,30 @@ private static TwoBindingProof installAndBridgeInternal( CanonicalGameplayRegionRedisKeys.lease( identity.tenantId(), identity.gameInstanceId(), status.regionId())); byte[] currentTickState = - redis - .admin() - .hget(ascii(initialMetaKey), ascii("current_tick_state")); + redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_state")); if (!Arrays.equals(currentTickState, ascii("APPLIED"))) { throw new IllegalStateException("Canonical Redis initial timeline metadata is absent"); } Proof firstProof = new Proof( - transitionId, - sessionId, - identity.regionId(), - resolved.canonicalRegionInstanceId(), - status.lifecycleEpoch(), - status.lifecycleRowVersion(), - status.regionEpoch(), - status.executorFence(), - acknowledged.bridgeOperationId(), - acknowledged.runtimeEntityId(), - acknowledged.entityProjectionGeneration(), - acknowledged.entityProjectionFence(), - acknowledged.entityReferenceDigest(), - acknowledged.worldSourceDigest(), - acknowledged.redisReadbackDigest(), - acknowledged.inventoryRevision(), - acknowledged.acknowledgedAt(), - acknowledged.equals(replayed)); + transitionId, + sessionId, + identity.regionId(), + resolved.canonicalRegionInstanceId(), + status.lifecycleEpoch(), + status.lifecycleRowVersion(), + status.regionEpoch(), + status.executorFence(), + acknowledged.bridgeOperationId(), + acknowledged.runtimeEntityId(), + acknowledged.entityProjectionGeneration(), + acknowledged.entityProjectionFence(), + acknowledged.entityReferenceDigest(), + acknowledged.worldSourceDigest(), + acknowledged.redisReadbackDigest(), + acknowledged.inventoryRevision(), + acknowledged.acknowledgedAt(), + acknowledged.equals(replayed)); if (secondBinding == null) { return new TwoBindingProof(firstProof, null, null, true, true, true, true, true); } @@ -258,20 +256,16 @@ private static TwoBindingProof installAndBridgeInternal( String firstTimelineOperationId = firstTimelineBefore.get("initialization_operation_id", UUID.class).toString(); String firstTimelineDigest = firstTimelineBefore.get("preparation_digest", String.class); - String firstWorldSourceDigest = - firstTimelineBefore.get("world_source_digest", String.class); + String firstWorldSourceDigest = firstTimelineBefore.get("world_source_digest", String.class); byte[] firstLifecycleRequest = firstTimelineBefore.get("lifecycle_request_bytes", byte[].class); byte[] firstMetaOperation = - redis - .admin() - .hget(ascii(initialMetaKey), ascii("first_timeline_operation_id")); + redis.admin().hget(ascii(initialMetaKey), ascii("first_timeline_operation_id")); byte[] firstMetaDigest = - redis - .admin() - .hget(ascii(initialMetaKey), ascii("first_timeline_source_digest")); + redis.admin().hget(ascii(initialMetaKey), ascii("first_timeline_source_digest")); - var secondResolved = secondBinding.worldRegionResolver().resolve(secondBinding.worldRequest()); + var secondResolved = + secondBinding.worldRegionResolver().resolve(secondBinding.worldRequest()); requireExactCurrentTarget(secondBinding.worldRequest(), secondBinding.currentTarget()); UUID secondTransitionId = UUID.randomUUID(); UUID secondSessionId = UUID.randomUUID(); @@ -329,7 +323,9 @@ private static TwoBindingProof installAndBridgeInternal( != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED || secondAcknowledgement.transitionId().equals(acknowledged.transitionId()) || secondAcknowledgement.bridgeOperationId().equals(acknowledged.bridgeOperationId()) - || !secondAcknowledgement.inventoryRevision().equals(secondLostReplyRetry.inventoryRevision())) { + || !secondAcknowledgement + .inventoryRevision() + .equals(secondLostReplyRetry.inventoryRevision())) { throw new IllegalStateException("Second binding did not retain its independent exact ACK"); } var secondStatus = @@ -346,27 +342,23 @@ private static TwoBindingProof installAndBridgeInternal( identity.gameInstanceId(), identity.regionId()); byte[] secondMetaOperation = - redis - .admin() - .hget(ascii(initialMetaKey), ascii("first_timeline_operation_id")); + redis.admin().hget(ascii(initialMetaKey), ascii("first_timeline_operation_id")); byte[] secondMetaDigest = - redis - .admin() - .hget(ascii(initialMetaKey), ascii("first_timeline_source_digest")); + redis.admin().hget(ascii(initialMetaKey), ascii("first_timeline_source_digest")); byte[] secondMetaRegionEpoch = redis.admin().hget(ascii(initialMetaKey), ascii("region_epoch")); - byte[] secondMetaTickId = - redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_id")); + byte[] secondMetaTickId = redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_id")); byte[] secondMetaTickState = redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_state")); boolean unchangedTimeline = - firstTimelineOperationId - .equals(firstTimelineAfter.get("initialization_operation_id", UUID.class).toString()) + firstTimelineOperationId.equals( + firstTimelineAfter.get("initialization_operation_id", UUID.class).toString()) && transitionId.equals(firstTimelineAfter.get("transition_id", UUID.class)) && Arrays.equals( firstLifecycleRequest, firstTimelineAfter.get("lifecycle_request_bytes", byte[].class)) - && firstTimelineDigest.equals(firstTimelineAfter.get("preparation_digest", String.class)) + && firstTimelineDigest.equals( + firstTimelineAfter.get("preparation_digest", String.class)) && firstWorldSourceDigest.equals( firstTimelineAfter.get("world_source_digest", String.class)) && Arrays.equals(firstMetaOperation, secondMetaOperation) @@ -501,9 +493,11 @@ public static AccountAbortProof abortAfterBridge(DSLContext dsl, Proof bridgePro bridgeProof.transitionId()); if (acknowledgedBefore == null || !"ACKNOWLEDGED".equals(acknowledgedBefore.get("status", String.class)) - || !bridgeProof.acknowledgedInventoryRevision() + || !bridgeProof + .acknowledgedInventoryRevision() .equals(new BigInteger(acknowledgedBefore.get("inventory_revision").toString())) - || !bridgeProof.redisReadbackDigest() + || !bridgeProof + .redisReadbackDigest() .equals(acknowledgedBefore.get("redis_readback_digest", String.class))) { throw new IllegalStateException("The exact region ACK is not the retained abort source"); } @@ -541,25 +535,32 @@ public static AccountAbortProof abortAfterBridge(DSLContext dsl, Proof bridgePro || !aborted.isAccountAborted() || !cleanupId.equals(aborted.orphanCleanupId()) || aborted.candidate().lifecycle() - != net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL_UNRESOLVED + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry + .Lifecycle.TERMINAL_UNRESOLVED || aborted.reservation().lifecycle() - != net.firedevops.firemud.gamesession.binding - .CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation + .Lifecycle.RELEASE_PENDING || !"ACKNOWLEDGED".equals(acknowledgedAfter.get("status", String.class)) - || !aborted.transition().inventoryRevision() + || !aborted + .transition() + .inventoryRevision() .equals(acknowledgedAfter.get("inventory_revision", BigInteger.class)) - || !bridgeProof.redisReadbackDigest() + || !bridgeProof + .redisReadbackDigest() .equals(acknowledgedAfter.get("redis_readback_digest", String.class)) - || !bridgeProof.acknowledgedAt() + || !bridgeProof + .acknowledgedAt() .equals( acknowledgedAfter .get("acknowledged_at", java.time.OffsetDateTime.class) .toInstant()) - || !acknowledgedBefore.get("acknowledged_at", java.time.OffsetDateTime.class) + || !acknowledgedBefore + .get("acknowledged_at", java.time.OffsetDateTime.class) .equals(acknowledgedAfter.get("acknowledged_at", java.time.OffsetDateTime.class)) || !acknowledgementImageBefore.equals(acknowledgementImageAfter) - || !aborted.transition().inventoryRevision() + || !aborted + .transition() + .inventoryRevision() .equals(new BigInteger(acknowledgedAfter.get("inventory_revision").toString())) || aborted.transition().status() != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot @@ -865,10 +866,10 @@ private static List> snapshotRegionOwnerSqlState( private static RegionRedisState snapshotRegionRedisState( RegionRedis redis, byte[] leaseKey, String metaKey) { Map metadata = new LinkedHashMap<>(); - redis.admin() + redis + .admin() .hgetall(ascii(metaKey)) - .forEach( - (field, value) -> metadata.put(asciiString(field), asciiString(value))); + .forEach((field, value) -> metadata.put(asciiString(field), asciiString(value))); return new RegionRedisState( redis.admin().type(leaseKey), asciiString(redis.admin().get(leaseKey)), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index 36d5ff4f0f..9e5f4778a6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -225,7 +225,8 @@ void ownerGrantAcceptsOnlyChangedLifecycleReadCorrelationAndKeepsInitialRequestB Instant.parse("2026-10-26T00:00:01Z")); var laterRequest = lifecycleRequest( - source.lifecycleRequest(), UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + source.lifecycleRequest(), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), source.lifecycleRequest().controlPlaneRequestId()); var laterSource = source(source, laterRequest); @@ -257,9 +258,7 @@ void ownerGrantAcceptsOnlyChangedLifecycleReadCorrelationAndKeepsInitialRequestB source( source, lifecycleRequest( - laterRequest, - laterRequest.readRequestId(), - "different-control-plane-request")); + laterRequest, laterRequest.readRequestId(), "different-control-plane-request")); assertThatThrownBy(() -> repository.find(changedTargetSelector)) .isInstanceOf(IllegalStateException.class); } From 8013feaea6310687d763dbd624379ecd70488c6f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:05:24 +1300 Subject: [PATCH 14/36] Qualify retained region abort and shared-region binding proofs --- ...GameplayRegionOwnerCompositionFixture.java | 154 +++++++++++++----- ...ationOwnerCompositionCrossServiceTest.java | 18 +- 2 files changed, 120 insertions(+), 52 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index 26f9af42f3..1167635e73 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.repository; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.lettuce.core.AclSetuserArgs; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; @@ -13,6 +14,7 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -20,11 +22,13 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; @@ -253,8 +257,12 @@ private static TwoBindingProof installAndBridgeInternal( identity.tenantId(), identity.gameInstanceId(), identity.regionId()); + Objects.requireNonNull(firstTimelineBefore, "first timeline source row"); String firstTimelineOperationId = - firstTimelineBefore.get("initialization_operation_id", UUID.class).toString(); + Objects.requireNonNull( + firstTimelineBefore.get("initialization_operation_id", UUID.class), + "first initialization operation") + .toString(); String firstTimelineDigest = firstTimelineBefore.get("preparation_digest", String.class); String firstWorldSourceDigest = firstTimelineBefore.get("world_source_digest", String.class); byte[] firstLifecycleRequest = @@ -350,9 +358,13 @@ private static TwoBindingProof installAndBridgeInternal( byte[] secondMetaTickId = redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_id")); byte[] secondMetaTickState = redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_state")); + Objects.requireNonNull(firstTimelineAfter, "retained timeline source row"); boolean unchangedTimeline = firstTimelineOperationId.equals( - firstTimelineAfter.get("initialization_operation_id", UUID.class).toString()) + Objects.requireNonNull( + firstTimelineAfter.get("initialization_operation_id", UUID.class), + "retained initialization operation") + .toString()) && transitionId.equals(firstTimelineAfter.get("transition_id", UUID.class)) && Arrays.equals( firstLifecycleRequest, @@ -477,6 +489,29 @@ private static TwoBindingProof installAndBridgeInternal( } } + private static boolean sameAbortSource( + CanonicalGameplayAdmissionAbortSource expected, + CanonicalGameplayAdmissionAbortSource actual) { + var left = expected.originalDecision(); + var right = actual.originalDecision(); + // Independently loaded decisions are verified carriers, not value records. + return expected.transition().equals(actual.transition()) + && expected.candidate().equals(actual.candidate()) + && expected.reservation().equals(actual.reservation()) + && Objects.equals(expected.orphanCleanupId(), actual.orphanCleanupId()) + && left.bindingDecisionId().equals(right.bindingDecisionId()) + && left.leaseEvidenceJson().equals(right.leaseEvidenceJson()) + && left.leaseSha256().equals(right.leaseSha256()) + && left.requestId().equals(right.requestId()) + && left.leaseId().equals(right.leaseId()) + && left.leaseFence().equals(right.leaseFence()) + && left.candidate().equals(right.candidate()) + && left.bindingGeneration().equals(right.bindingGeneration()) + && Objects.equals(left.expectedOldBindingGeneration(), right.expectedOldBindingGeneration()) + && Objects.equals(left.resumeEpisodeId(), right.resumeEpisodeId()) + && left.targetEvidence().equals(right.targetEvidence()); + } + /** * Carries a controlled definitive Account abort through the actual repository after a real * PostgreSQL/Redis bridge ACK, then proves exact cleanup retry/read preserves that ACK without @@ -495,7 +530,11 @@ public static AccountAbortProof abortAfterBridge(DSLContext dsl, Proof bridgePro || !"ACKNOWLEDGED".equals(acknowledgedBefore.get("status", String.class)) || !bridgeProof .acknowledgedInventoryRevision() - .equals(new BigInteger(acknowledgedBefore.get("inventory_revision").toString())) + .equals( + new BigInteger( + Objects.requireNonNull( + acknowledgedBefore.get("inventory_revision"), "original ACK revision") + .toString())) || !bridgeProof .redisReadbackDigest() .equals(acknowledgedBefore.get("redis_readback_digest", String.class))) { @@ -523,6 +562,7 @@ public static AccountAbortProof abortAfterBridge(DSLContext dsl, Proof bridgePro + " FROM game_session_canonical_binding_region_bridge_obligation" + " WHERE transition_id = ?", bridgeProof.transitionId()); + Objects.requireNonNull(acknowledgedAfter, "retained region ACK row"); String acknowledgementImageAfter = dsl.fetchSingle( "SELECT (to_jsonb(obligation) - 'inventory_revision')::text AS image" @@ -530,43 +570,76 @@ public static AccountAbortProof abortAfterBridge(DSLContext dsl, Proof bridgePro + " WHERE transition_id = ?", bridgeProof.transitionId()) .get("image", String.class); - if (!aborted.equals(retry) - || !aborted.equals(retained) - || !aborted.isAccountAborted() - || !cleanupId.equals(aborted.orphanCleanupId()) - || aborted.candidate().lifecycle() - != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry - .Lifecycle.TERMINAL_UNRESOLVED - || aborted.reservation().lifecycle() - != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation - .Lifecycle.RELEASE_PENDING - || !"ACKNOWLEDGED".equals(acknowledgedAfter.get("status", String.class)) - || !aborted - .transition() - .inventoryRevision() - .equals(acknowledgedAfter.get("inventory_revision", BigInteger.class)) - || !bridgeProof - .redisReadbackDigest() - .equals(acknowledgedAfter.get("redis_readback_digest", String.class)) - || !bridgeProof - .acknowledgedAt() - .equals( - acknowledgedAfter - .get("acknowledged_at", java.time.OffsetDateTime.class) - .toInstant()) - || !acknowledgedBefore - .get("acknowledged_at", java.time.OffsetDateTime.class) - .equals(acknowledgedAfter.get("acknowledged_at", java.time.OffsetDateTime.class)) - || !acknowledgementImageBefore.equals(acknowledgementImageAfter) - || !aborted - .transition() - .inventoryRevision() - .equals(new BigInteger(acknowledgedAfter.get("inventory_revision").toString())) - || aborted.transition().status() - != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot - .Status.ABORTED) { + List abortFailures = new ArrayList<>(); + if (!sameAbortSource(aborted, retry)) { + abortFailures.add("abort retry changed the retained terminal result"); + } + if (!sameAbortSource(aborted, retained)) { + abortFailures.add("retained abort read changed the terminal result"); + } + if (!aborted.isAccountAborted()) { + abortFailures.add("the original Account abort is not retained"); + } + if (!cleanupId.equals(aborted.orphanCleanupId())) { + abortFailures.add("the abort changed its exact orphan cleanup identity"); + } + if (aborted.candidate().lifecycle() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry + .Lifecycle.TERMINAL_UNRESOLVED) { + abortFailures.add("the aborted candidate is not TERMINAL_UNRESOLVED"); + } + if (aborted.reservation().lifecycle() + != net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation.Lifecycle + .RELEASE_PENDING) { + abortFailures.add("the aborted reservation is not RELEASE_PENDING"); + } + if (!"ACKNOWLEDGED".equals(acknowledgedAfter.get("status", String.class))) { + abortFailures.add("the retained region ACK status changed"); + } + if (!aborted + .transition() + .inventoryRevision() + .equals(acknowledgedAfter.get("inventory_revision", BigInteger.class))) { + abortFailures.add("the retained region ACK revision differs from the aborted transition"); + } + if (!bridgeProof + .redisReadbackDigest() + .equals(acknowledgedAfter.get("redis_readback_digest", String.class))) { + abortFailures.add("the retained region ACK Redis readback digest changed"); + } + Instant persistedAcknowledgedAt = bridgeProof.acknowledgedAt().truncatedTo(ChronoUnit.MICROS); + if (!persistedAcknowledgedAt.equals( + acknowledgedAfter.get("acknowledged_at", java.time.OffsetDateTime.class).toInstant())) { + abortFailures.add( + "the retained region ACK timestamp changed after SQL precision normalization"); + } + if (!acknowledgedBefore + .get("acknowledged_at", java.time.OffsetDateTime.class) + .equals(acknowledgedAfter.get("acknowledged_at", java.time.OffsetDateTime.class))) { + abortFailures.add("the region ACK timestamp changed across the Account abort"); + } + if (!acknowledgementImageBefore.equals(acknowledgementImageAfter)) { + abortFailures.add("the retained region ACK row image changed"); + } + if (!aborted + .transition() + .inventoryRevision() + .equals( + new BigInteger( + Objects.requireNonNull( + acknowledgedAfter.get("inventory_revision"), "retained ACK revision") + .toString()))) { + abortFailures.add( + "the retained region ACK revision changed in its SQL numeric representation"); + } + if (aborted.transition().status() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.ABORTED) { + abortFailures.add("the aborted transition does not remain ABORTED"); + } + if (!abortFailures.isEmpty()) { throw new IllegalStateException( - "Definitive Account abort changed region ACK evidence or claimed admission/cleanup"); + "Definitive Account abort composition failed: " + String.join("; ", abortFailures)); } return new AccountAbortProof( bridgeProof.transitionId(), @@ -904,6 +977,9 @@ public record Proof( Instant acknowledgedAt, boolean exactLostReplyRetry) {} + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The generated Protocol Buffers request is immutable") public record SecondBinding( CanonicalInitialPlayerLocationRequest worldRequest, CanonicalPlayableTarget currentTarget, 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 fb898b2479..c06dcb905e 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 @@ -3493,17 +3493,12 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( .setResultDigest("e".repeat(64)) .build(); var secondLifecycle = - firstResolvedRegion - .observation() - .getLifecycle() - .toBuilder() + firstResolvedRegion.observation().getLifecycle().toBuilder() .setCanonicalRequestBytes( com.google.protobuf.ByteString.copyFrom(secondLifecycleRequest.canonicalBytes())) .build(); var secondObservation = - firstResolvedRegion - .observation() - .toBuilder() + firstResolvedRegion.observation().toBuilder() .setPlacementResult(secondPlacement) .setLifecycle(secondLifecycle) .build(); @@ -3518,8 +3513,7 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( var lifecycleClient = Mockito.mock(WorldCanonicalInstanceLifecycleClient.class); Mockito.doAnswer( invocation -> { - WorldCanonicalInstanceLifecycleEvidence.Request request = - invocation.getArgument(0); + WorldCanonicalInstanceLifecycleEvidence.Request request = invocation.getArgument(0); if (secondLifecycleRequest.equals(request)) return secondLifecycleEvidence; return actualLifecycleClient.read(request); }) @@ -3527,8 +3521,7 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( .read(Mockito.any(WorldCanonicalInstanceLifecycleEvidence.Request.class)); var secondWorldRegionResolver = new CanonicalInitialPlayerLocationRegionResolver( - initialLocationClient, - new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); + initialLocationClient, new CanonicalRegionBootstrapAssignmentResolver(lifecycleClient)); var entityReferenceClient = Mockito.mock(CanonicalPreseededActorRuntimeReferenceClient.class); var runtimeReference = @@ -3551,8 +3544,7 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( when(runtimeReference.playableStateNamespaceId()) .thenReturn(currentTarget.playableStateNamespaceId()); when(runtimeReference.target()).thenReturn(toWire(assignmentTarget)); - when(runtimeReference.publishedOwnerProofDigest()) - .thenReturn(currentTarget.ownerProofDigest()); + when(runtimeReference.publishedOwnerProofDigest()).thenReturn(currentTarget.ownerProofDigest()); when(runtimeReference.corePayload()) .thenReturn( net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentCorePayload From 98747cea8169fcec1f68aca114a2d8ffa713b23c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:00:44 +1300 Subject: [PATCH 15/36] Keep provisional region inventory reads limited to required evidence --- ...calGameplayBindingInventoryRepository.java | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 004733cfb5..23a8588439 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -2149,7 +2149,7 @@ private static CanonicalGameplayBindingProvisionalCasEvidence loadProvisionalCas + (forUpdate ? " FOR UPDATE" : ""), transitionId); CanonicalGameplayBindingRegionBridgeObligation regionObligation = - regionObligationRow == null ? null : toRegionObligation(regionObligationRow); + regionObligationRow == null ? null : toProvisionalRegionObligation(regionObligationRow); requireExactProvisionalRows(evidence, accountObligations, issuerObligation, regionObligation); if (!accountObligations.isEmpty() && accountObligations.getFirst().status() @@ -4501,6 +4501,32 @@ private static CanonicalGameplayBindingIssuerIndexObligation toIssuerObligation( row.get("local_release_operation_id", UUID.class)); } + /** Inventory preparation consumes the required obligation's identity, not bridge proof. */ + private static CanonicalGameplayBindingRegionBridgeObligation toProvisionalRegionObligation( + Record row) { + var status = + CanonicalGameplayBindingRegionBridgeObligation.Status.valueOf( + row.get("status", String.class)); + if (status == CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { + // An ACK is never represented by the required-only projection: retain every closed + // Entity/World/Redis proof check in its actual acknowledgement decoder. + return toRegionObligation(row); + } + return new CanonicalGameplayBindingRegionBridgeObligation( + row.get("transition_id", UUID.class), + CanonicalGameplayBindingRef.fromExactBytes(row.get("binding_ref", byte[].class)), + readBigInteger(row, "binding_generation"), + row.get("account_id", UUID.class), + row.get("tenant_id", UUID.class), + row.get("game_instance_id", UUID.class), + row.get("runtime_game_instance_id", Long.class), + row.get("session_id", String.class), + row.get("region_id", UUID.class), + readBigInteger(row, "region_epoch"), + status, + readBigInteger(row, "inventory_revision")); + } + private static CanonicalGameplayBindingRegionBridgeObligation toRegionObligation(Record row) { UUID tenantId = row.get("tenant_id", UUID.class); UUID gameInstanceId = row.get("game_instance_id", UUID.class); From 7f6b2f079b16dfff5de4c98c15c2c524b65b3b27 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:10:12 +1300 Subject: [PATCH 16/36] fix: preserve issuer cohorts across region bridge schema growth --- .../CanonicalGameplayIssuerCohortSql.java | 13 +++++++- ...rtitionBuildRepositoryIntegrationTest.java | 27 ++++++++++++++++ ...GameplayRegionOwnerCompositionFixture.java | 32 +++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java index b50e51f411..ff7eae1fc0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java @@ -41,7 +41,18 @@ final class CanonicalGameplayIssuerCohortSql { + " WHERE o.inventory_revision <= ?" + " UNION ALL SELECT 'REGION_OBLIGATION' AS source_kind," + " g.transition_id::text AS source_key, g.inventory_revision AS source_revision," - + " to_jsonb(g)::text AS source_row_json" + // V1042's untouched bridge extension is absence-equivalent to the old row shape. + // Its CHECK makes every extension field NULL until a real bridge operation exists. + // Once materialized, capture the entire bridge source, including all readback evidence. + + " CASE WHEN to_jsonb(g)->'bridge_operation_id' = 'null'::jsonb" + + " THEN (to_jsonb(g) - ARRAY['bridge_operation_id', 'bridge_preimage_state'," + + " 'runtime_entity_id', 'entity_projection_generation', 'entity_projection_fence'," + + " 'entity_workload_namespace', 'assignment_uuid', 'assignment_intent_digest'," + + " 'entity_reference_digest', 'world_source_digest', 'canonical_region_id'," + + " 'world_lifecycle_epoch', 'world_lifecycle_row_version', 'world_capture_id'," + + " 'world_graph_sha256', 'world_preparation_input_digest', 'executor_fence'," + + " 'lease_token_correlation', 'redis_readback_digest', 'acknowledged_at'])::text" + + " ELSE to_jsonb(g)::text END AS source_row_json" + " FROM game_session_canonical_binding_region_bridge_obligation g" + " WHERE g.inventory_revision <= ?" + ") captured_cohort ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; 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 693de911f6..ee22452f7b 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 @@ -2241,6 +2241,29 @@ private static DriverManagerDataSource dataSource(String schema) { return dataSource; } + private static String retainedPreBridgeRegionImage(DSLContext dsl) { + // This populated V1030 fixture retains its original columns and physical xmin. A later + // nullable schema extension changes to_jsonb's field set without changing those values. + String originalFields = + "ARRAY['transition_id', 'binding_ref', 'account_id', 'tenant_id', 'game_instance_id'," + + " 'runtime_game_instance_id', 'session_id', 'binding_generation', 'region_id'," + + " 'region_epoch', 'status', 'inventory_revision']"; + Long unexpectedMaterializedFields = + dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_binding_region_bridge_obligation g" + + " WHERE jsonb_strip_nulls(to_jsonb(g) - " + + originalFields + + ") <> '{}'::jsonb") + .get(0, Long.class); + if (unexpectedMaterializedFields == null || unexpectedMaterializedFields != 0L) { + throw new IllegalStateException("Historical fixture gained materialized bridge evidence"); + } + return "to_jsonb(retained_row) - ARRAY(SELECT key FROM jsonb_each(to_jsonb(retained_row))" + + " WHERE NOT (key = ANY(" + + originalFields + + ")))"; + } + private static List rowImages(DSLContext dsl, String tableName) { String image = "to_jsonb(retained_row)"; if (tableName.equals("game_session_canonical_binding_transition")) { @@ -2253,6 +2276,8 @@ private static List rowImages(DSLContext dsl, String tableName) { image = "CASE WHEN to_jsonb(retained_row)->'local_release_operation_id' = 'null'::jsonb" + " THEN to_jsonb(retained_row) - 'local_release_operation_id' ELSE to_jsonb(retained_row) END"; + } else if (tableName.equals("game_session_canonical_binding_region_bridge_obligation")) { + image = retainedPreBridgeRegionImage(dsl); } return dsl.fetch( "SELECT (" @@ -2275,6 +2300,8 @@ private static List rowImagesWithXmin(DSLContext dsl, String tableName) image = "CASE WHEN to_jsonb(retained_row)->'local_release_operation_id' = 'null'::jsonb" + " THEN to_jsonb(retained_row) - 'local_release_operation_id' ELSE to_jsonb(retained_row) END"; + } else if (tableName.equals("game_session_canonical_binding_region_bridge_obligation")) { + image = retainedPreBridgeRegionImage(dsl); } return dsl.fetch( "SELECT xmin::text || ':' || (" diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index 1167635e73..769a81bb58 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -201,6 +201,7 @@ private static TwoBindingProof installAndBridgeInternal( != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { throw new IllegalStateException("Exact first-NEW region bridge retry changed its SQL ACK"); } + requireMaterializedBridgeCaptured(dsl, transitionId); var status = new CanonicalGameplayRegionRuntimeStatusRepository(dsl) .find(installation.source) @@ -326,6 +327,7 @@ private static TwoBindingProof installAndBridgeInternal( installation, secondTransitionId, secondBinding.worldRequest()); var secondAcknowledgement = bridgeOwner.bridge(secondInstallation).obligation(); var secondLostReplyRetry = bridgeOwner.bridge(secondInstallation).obligation(); + requireMaterializedBridgeCaptured(dsl, secondTransitionId); if (!secondAcknowledgement.equals(secondLostReplyRetry) || secondAcknowledgement.status() != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED @@ -517,6 +519,36 @@ private static boolean sameAbortSource( * PostgreSQL/Redis bridge ACK, then proves exact cleanup retry/read preserves that ACK without * promoting the candidate or claiming cleanup completion. */ + private static void requireMaterializedBridgeCaptured(DSLContext dsl, UUID transitionId) { + String exactRow = + dsl.fetchSingle( + "SELECT to_jsonb(g)::text FROM game_session_canonical_binding_region_bridge_obligation g" + + " WHERE transition_id = ? AND bridge_operation_id IS NOT NULL", + transitionId) + .get(0, String.class); + java.math.BigDecimal revision = + dsl.fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1") + .get(0, java.math.BigDecimal.class); + var captured = + dsl + .fetch( + CanonicalGameplayIssuerCohortSql.cohortSql(), + CanonicalGameplayIssuerCohortSql.cohortBindings( + GameSessionAccountDelegationProfile.ISSUER, revision)) + .stream() + .filter( + row -> + "REGION_OBLIGATION".equals(row.get("source_kind", String.class)) + && transitionId.toString().equals(row.get("source_key", String.class))) + .toList(); + if (captured.size() != 1 + || !Objects.equals(exactRow, captured.getFirst().get("source_row_json", String.class))) { + throw new IllegalStateException("Issuer cohort omitted materialized region bridge evidence"); + } + } + public static AccountAbortProof abortAfterBridge(DSLContext dsl, Proof bridgeProof) { var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); var before = inventory.readFirstNewAdmissionAbortSource(bridgeProof.transitionId()); From 4190654b0faa1e162082e07fc576c80a8084da4c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:58:25 +1300 Subject: [PATCH 17/36] fix: preserve acknowledged region evidence through member repair --- .../runtime-and-data.md | 2 + .../game-session-service/operations.md | 2 + .../game-session-service/runtime-and-data.md | 4 +- .../gameplay-rules-entities-and-effects.md | 1 + .../world-runtime-and-movement.md | 2 +- ...calGameplayBindingInventoryRepository.java | 2 +- ...nBindingBridgeRedisScriptContribution.java | 4 +- ...layRegionLeaseRedisScriptContribution.java | 4 +- ...meplayRegionLeaseOwnerIntegrationTest.java | 288 +++++++++++++- ...GameplayRegionOwnerCompositionFixture.java | 365 +++++++++++++++++- ...nicalInitialPlayerLocationServiceTest.java | 125 +++++- 11 files changed, 785 insertions(+), 14 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 1d39ee759b..734ea5854d 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -387,6 +387,8 @@ 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. Runtime replacement allocates a new projection generation and runtime ID while retaining and fencing the previous association; reconnect alone does not replace the projection. 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 rejects update, delete, and truncate until the exact replacement-owner chain exists. 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. diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index 0f3a76ddcb..a2a13a1aa4 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -42,6 +42,8 @@ Before deploying the new Game Session admission validation, Automation must alre - Prometheus scrapes metrics from `/actuator/prometheus`. - Target state: logs, traces, and control-plane reads expose the active exact `{scriptPatchVersion, scriptPinEpoch}` execution fence so operators can identify the hotfix revision and selection epoch during incident triage without adding either raw value as ordinary high-cardinality metric labels. Current coverage is summarized in [Implementation Status](#implementation-status). +For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata is inconclusive loss. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. No same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). + ## Scaling and Region Rebalancing - Region-to-instance mapping is flexible and driven by a scheduler or consistent-hashing layer that assigns `` values to Game Session instances. 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 64fdc8b9e0..e5cd7fc445 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -213,7 +213,7 @@ The target transition's durable identity spans the target session record and cha Game Session acts as the authoritative tick executor for each `` region scope it owns: -- It participates in region leadership using the Redis lease key `tick-executor-lease:{tenantRegionTag}` described in [Tick System: Region Authority and Tick Executor](../../system-architecture-ticks.md#region-authority-and-tick-executor). +- Region timeline, epoch, executor-fence, lease acquisition, revalidation, and handoff semantics are owned by [Tick System: Region Authority and Tick Executor](../../system-architecture-ticks.md#region-authority-and-tick-executor). Game Session uses the Redis lease key `tick-executor-lease:{tenantRegionTag}`; the physical complete-scope `tenantRegionTag` projection is owned by [Redis: Canonical Region Key Projection](../../system-architecture-redis.md#canonical-region-key-projection). - While it holds the lease for a region, it is the only instance allowed to consume commands from that region’s queues and timers, drive `tick:{tenantRegionTag}:pending`, and issue tick-scoped gRPC calls on behalf of that region’s commands. - **Target state:** on crash or deliberate handoff, another instance acquires the lease and resumes tick processing from durable PostgreSQL commands, tick batches, effects, and participant guards, using surviving Redis queues, timers, retries, `pending`, or AOF state only as reconciled coordination hints after that durable baseline is established. Redis state never supplies recovery authority or the sole source of replayable work; the successor preserves the epoch-scoped `(regionEpoch, tickId)` timeline and EffectId/effect-guard rules from the tick-system design. - Tick execution correctness must not depend on process-local executor memory surviving restart. Lease acquisition, staged tick state, retry metadata, and resumable session bindings are all externalized specifically so another Game Session instance can continue work from shared state. @@ -233,6 +233,8 @@ Tick coordination is region-scoped, not session-scoped. Tick queues, locks, time Session shutdown therefore cleans up session keys but does not implicitly delete region-level tick coordination keys. +Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. Once that permission is consumed, missing Redis metadata is ambiguous loss; the same-scope retry fails closed and cannot obtain a fresh create permission or rewrite the same-epoch baseline. No same-scope automated or operator repair is implemented, so this is a scope-local liveness limit. The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). + ## Reconnection and Disconnect Handling Game Session restores player sessions after disconnects and enforces single-session control as outlined in the [Reconnection Strategy](../../system-architecture-reconnection.md). For Telnet clients, it also consumes best-effort, at-least-once `NotifyDisconnect` events emitted by the TCP Proxy Service over an internal gRPC link and treats them as idempotent hints keyed by `` rather than a guaranteed source of truth. 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..c52efd2660 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. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index f7f0f30d3e..a5c2e65a0e 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -14,7 +14,7 @@ The selected local region prerequisite now composes the actual #2973 committed W The next receiving checkpoint at `63bfad5b657d6fafc2880345355074e68b3945e2` receives #2973 `bea4f4dd555a6536e5d09a7a04b54e3a8f5bc6a6` and still contains the same 83 owned paths. Eighty-one owned postimages are unchanged; the two shared files receive the qualified retained-abort validation correction and settlement-read fixture wire bound. R714 exits successfully with 73 executed passing cases and 19 skipped Game Session native cases; the skip cause is unproven and that run alone is not full qualification. R715 then freshly executes and passes all 19 skipped cases, with no failures, errors or skips. Across R714/R715, all 92 selected methods have passing execution on unchanged production postimages, including the actual Human-to-region owner composition. Enabled affected static analysis, formatting and documentation checks pass. All 14 observed R714 and seven R715 containers are independently absent. The same controlled-source, unregistered-runtime and final-player-CAS limits remain; current public CI is still required. -Final receiving checkpoint `cc90e783280a99aa6c247e32377fd7cf283be9c4` receives published #2973 `8e15d7af318808a5cab6c460da22db917f66dbb2` and #3310 `8cf137b8fb31be2728978e1397ffce7012bf313e`. Its 83-path comparison preserves all 82 owned source postimages from the qualified boundary; only this shared tracker receives parent proof attribution. R720 freshly passes the actual Human-to-region composed owner case and all seven runtime-fence cases, with zero failures, errors or skips and enabled affected static analysis, formatting and documentation checks. All eight R720 observed containers are independently absent. This is current-parent receiving proof supplementing the separately scoped 92-method qualification above. Controlled authority, registration, tick execution, final player CAS, production custody/PKI and activation limits remain unchanged. +Historical subsequent receiving checkpoint `cc90e783280a99aa6c247e32377fd7cf283be9c4` receives published #2973 `8e15d7af318808a5cab6c460da22db917f66dbb2` and #3310 `8cf137b8fb31be2728978e1397ffce7012bf313e`. Its 83-path comparison preserves all 82 owned source postimages from the qualified boundary; only this shared tracker receives parent proof attribution. R720 freshly passes the actual Human-to-region composed owner case and all seven runtime-fence cases, with zero failures, errors or skips and enabled affected static analysis, formatting and documentation checks. All eight R720 observed containers are independently absent. This is current-parent receiving proof supplementing the separately scoped 92-method qualification above. Controlled authority, registration, tick execution, final player CAS, production custody/PKI and activation limits remain unchanged. The first region-PR CI repair preserves the intentional V1011/V1017 Entity roster-retention migration fixtures. They now seed explicitly historical assignment receipts, actors and snapshots without calling the fresh V1022 projection allocator before upgrade; current-schema assignments still use the production owner. No applied migration or production compatibility/backfill path changes. R722 executes 584 Entity methods: 454 unit and 65 native cases pass, while 46 retention setup cases expose a placeholder error in the new fixture and 19 other native cases fail PostgreSQL connection setup. R723 corrects only the placeholder and freshly passes all 65 affected native cases with zero failures, errors or skips. All 584 distinct methods therefore have passing execution across the two runs; the failed full-check aggregate stays retained. Enabled affected static analysis and formatting pass. This is current-parent fixture and regression proof; replacement public CI is still required. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 23a8588439..7c1cd2cd1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -3680,7 +3680,7 @@ private static void persistMemberRepairAcknowledgement( "UPDATE " + REGION_OBLIGATION + " SET inventory_revision = ? WHERE transition_id = ? AND binding_ref = ?" - + " AND status = 'REQUIRED' AND inventory_revision = ?", + + " AND status IN ('REQUIRED', 'ACKNOWLEDGED') AND inventory_revision = ?", decimal(nextRevision), operation.transitionId(), operation.bindingRef().bytes(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java index 03d3be3686..8e6efb9e71 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionBindingBridgeRedisScriptContribution.java @@ -46,7 +46,9 @@ private RedisScriptDescriptor readDescriptor() { } return descriptor; } catch (IOException | RuntimeException failure) { - throw unavailable(); + IllegalStateException unavailable = unavailable(); + unavailable.initCause(failure); + throw unavailable; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java index 5ba434a32e..b15fa5baae 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRegionLeaseRedisScriptContribution.java @@ -55,7 +55,9 @@ private RedisScriptDescriptor read(String path, String id) { } return descriptor; } catch (IOException | RuntimeException failure) { - throw unavailable(); + IllegalStateException unavailable = unavailable(); + unavailable.initCause(failure); + throw unavailable; } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 6733a16df9..104efd1f6b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -6,6 +6,10 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; import io.lettuce.core.AclSetuserArgs; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; @@ -24,24 +28,39 @@ import java.time.ZoneOffset; import java.util.List; import java.util.UUID; +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.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.testing.AuthoringFixtures; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +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.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.client.CanonicalInitialPlayerLocationClient; +import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; import net.firedevops.firemud.gamesession.service.CanonicalRegionBootstrapAssignmentResolver; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; @@ -53,7 +72,9 @@ import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.testcontainers.containers.GenericContainer; @@ -76,6 +97,13 @@ class CanonicalGameplayRegionLeaseOwnerIntegrationTest { private static final UUID OPERATIONAL_REGION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final Instant NOW = Instant.parse("2026-10-26T00:00:00Z"); + private static final String ENTITY_CLIENT_PEER = + "spiffe://firemud/ns/firemud/sa/game-session-service"; + private static final String ENTITY_SERVER_PEER = + "spiffe://firemud/ns/firemud/sa/entity-management-service"; + + @TempDir static Path pkiDirectory; + private static LoopbackMtlsTestPki.Pki pki; @Container private static final PostgreSQLContainer POSTGRES = @@ -85,6 +113,16 @@ class CanonicalGameplayRegionLeaseOwnerIntegrationTest { private static final GenericContainer REDIS = new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(REDIS_PORT); + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + pkiDirectory, + "Region member order test CA", + new LoopbackMtlsTestPki.IdentitySpec("client", ENTITY_CLIENT_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec("entity-server", ENTITY_SERVER_PEER, true)); + } + @Test void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); @@ -442,6 +480,105 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws } } + @Test + void accountMemberAcknowledgementAfterRegionBridgePreservesOriginalBridgeEvidence() + throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try { + // The shared test Redis container may have state from the sibling owner test. + try (RedisFixture redis = RedisFixture.open()) { + redis.admin().flushdb(); + } + // This local candidate-launch source is created through the real Game Session owners; + // its upstream publication inputs remain controlled test evidence. + var runtimeTarget = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + testSchema.dataSource(), UUID.randomUUID(), "firemud"); + WorldFixture world = WorldFixture.open(runtimeTarget); + CanonicalPlayableTarget currentTarget = runtimeTarget.playableTarget(); + // World and Entity responses are controlled fixtures; region and Account owners are actual. + try (var entitySource = EntityReferenceFixture.open()) { + CanonicalGameplayRegionOwnerCompositionFixture.MemberRepairProof proof = + CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeThenRepairAccountMember( + testSchema.dsl(), + REDIS.getHost(), + REDIS.getMappedPort(REDIS_PORT), + world.request(), + currentTarget, + world.resolver(), + entitySource.client()); + + assertThat(proof.regionBridge().exactLostReplyRetry()).isTrue(); + assertThat(proof.memberAcknowledgement().schemaVersion()).isEqualTo(2); + assertThat(proof.memberAcknowledgement().transitionId()) + .isEqualTo(proof.regionBridge().transitionId()); + assertThat(proof.memberAcknowledgement().readback().member()) + .isEqualTo(proof.memberAcknowledgement().operation().member()); + assertThat(proof.memberAcknowledgedInventoryRevision()) + .isEqualTo(proof.regionAcknowledgedInventoryRevision().add(BigInteger.ONE)); + assertThat(proof.sharedRevisionPropagated()).isTrue(); + assertThat(proof.regionAcknowledgementEvidenceUnchanged()).isTrue(); + assertThat(proof.physicalBridgeEvidenceUnchanged()).isTrue(); + assertThat(proof.accountMemberAddedExactly()).isTrue(); + assertThat(proof.accountControlStatePreserved()).isTrue(); + assertThat(proof.exactMemberRetryPreservedState()).isTrue(); + } + } finally { + dropSchema(testSchema.schema()); + } + } + + private static Server entityReferenceServer() throws Exception { + var service = + new CanonicalPreseededActorAssignmentServiceGrpc + .CanonicalPreseededActorAssignmentServiceImplBase() { + @Override + public void readPreseededActorRuntimeReference( + ReadPreseededActorRuntimeReferenceRequest request, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null || !ENTITY_CLIENT_PEER.equals(peer.uri())) { + observer.onError(io.grpc.Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + observer.onNext(entityResponse(request)); + observer.onCompleted(); + } + }; + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(pki.identity("entity-server")), + pki.trustManagerFactory(), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + factory.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + return factory.createServer().start(); + } + + private static ReadPreseededActorRuntimeReferenceResponse entityResponse( + ReadPreseededActorRuntimeReferenceRequest request) { + return ReadPreseededActorRuntimeReferenceResponse.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(request.getAssignmentUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setCharacterUuid(request.getCharacterUuid()) + .setIntentDigest(request.getIntentDigest()) + .setExpectedTarget(request.getExpectedTarget()) + .setPublishedOwnerProofDigest("f".repeat(64)) + .setRuntimeEntityId(91L) + .setProjectionGeneration(11L) + .setProjectionFence(12L) + .setCorePayload( + PreseededActorAssignmentCorePayload.newBuilder() + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .setDisplayName("Fixture Player")) + .build(); + } + private static DriverManagerDataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(POSTGRES.getDriverClassName()); @@ -451,6 +588,38 @@ private static DriverManagerDataSource dataSource() { return dataSource; } + private static TestSchema newTestSchema() { + String schema = "gs_region_member_order_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(POSTGRES.getDriverClassName()); + String separator = POSTGRES.getJdbcUrl().contains("?") ? "&" : "?"; + dataSource.setUrl(POSTGRES.getJdbcUrl() + separator + "currentSchema=" + schema); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations( + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + .load() + .migrate(); + return new TestSchema(schema, dataSource, DSL.using(dataSource, SQLDialect.POSTGRES)); + } + + private static void dropSchema(String schema) { + try (var connection = + java.sql.DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException( + "Failed to dispose reverse-order region/member schema", failure); + } + } + /** Controlled current-incarnation fixture; it does not attest production Redis custody. */ private static CanonicalGameplayRegionIncarnationSource.StableEvidence stableIncarnation( CanonicalGameplayRegionIncarnationSource.RegionScope scope, String storageGeneration) { @@ -665,6 +834,41 @@ private static CanonicalInitialPlayerLocationRequest initialLocationRequest( .build(); } + private static CanonicalInitialPlayerLocationRequest initialLocationRequest( + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target) { + var expectedTarget = + PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid(target.canonicalTenantId().toString()) + .setRealmUuid(target.realmId().toString()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceId(target.gameInstanceUuid().toString()) + .setCatalogRevision(target.catalogRevision()) + .setCanonicalVersionUuid(target.canonicalVersionId().toString()) + .setFrozenPolicyDigest("a".repeat(64)) + .setPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .setPublishedReleaseBundleRef(target.publishedReleaseBundleRef()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + return CanonicalInitialPlayerLocationRequest.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(UUID.randomUUID().toString()) + .setExpectedTarget(expectedTarget) + .setCanonicalAccountUuid(ACCOUNT_ID.toString()) + .setCharacterUuid(CHARACTER_ID.toString()) + .setAssignmentUuid(UUID.randomUUID().toString()) + .setAssignmentIntentDigest("b".repeat(64)) + .setInitialAdmissionHoldUuid(target.holdId().toString()) + .setInitialAdmissionHoldFence(target.holdFence().toString()) + .setInitialAdmissionRequestId(target.initialAdmissionRequestId()) + .setInitialAdmissionRequestDigest(target.initialAdmissionRequestDigest()) + .setActiveLifecycleEpoch(target.activeWorldEpoch()) + .setTerminalProofDigest(target.ownerProofDigest()) + .setCommittedPointerVersion(target.pointerVersion()) + .setAuditEventId(target.auditEventId()) + .build(); + } + private static CanonicalInitialPlayerLocationRegionResponse regionResponse( CanonicalInitialPlayerLocationRequest request, WorldCanonicalInstanceLifecycleEvidence evidence) { @@ -739,9 +943,15 @@ private static final class WorldFixture { private final CanonicalInitialPlayerLocationRegionResolver resolver; private WorldFixture(WorldCanonicalInstanceLifecycleEvidence original) { + this(original, initialLocationRequest(original.request())); + } + + private WorldFixture( + WorldCanonicalInstanceLifecycleEvidence original, + CanonicalInitialPlayerLocationRequest request) { this.original = original; this.current = new AtomicReference<>(original); - this.request = initialLocationRequest(original.request()); + this.request = request; this.initialClient = mock(CanonicalInitialPlayerLocationClient.class); this.lifecycleClient = mock(WorldCanonicalInstanceLifecycleClient.class); when(initialClient.readInitialPlayerLocationRegion(request)) @@ -764,6 +974,36 @@ static WorldFixture open() throws Exception { return new WorldFixture(AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L)); } + static WorldFixture open(CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target) { + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.randomUUID(), + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.gameInstanceUuid(), + target.playableStateNamespaceId(), + target.playableStateScope(), + true, + target.controlPlaneRequestId(), + target.canonicalVersionId(), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + var evidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(evidence.request()).thenReturn(lifecycleRequest); + when(evidence.lifecycleStatus()).thenReturn("ACTIVE"); + when(evidence.lifecycleEpoch()).thenReturn(target.activeWorldEpoch()); + when(evidence.rowVersion()).thenReturn(1L); + when(evidence.captureId()).thenReturn(UUID.randomUUID()); + when(evidence.graphSha256()).thenReturn("d".repeat(64)); + when(evidence.preparationInputDigest()).thenReturn("sha256:" + "e".repeat(64)); + when(evidence.operationalRegionAssignments()) + .thenReturn(java.util.Map.of(CANONICAL_REGION_ID, OPERATIONAL_REGION_ID)); + return new WorldFixture(evidence, initialLocationRequest(target)); + } + CanonicalInitialPlayerLocationRegionResolver resolver() { return resolver; } @@ -798,6 +1038,50 @@ void resetReads() { } } + private static final class EntityReferenceFixture implements AutoCloseable { + private final Server server; + private final CanonicalPreseededActorRuntimeReferenceClient client; + + private EntityReferenceFixture( + Server server, CanonicalPreseededActorRuntimeReferenceClient client) { + this.server = server; + this.client = client; + } + + static EntityReferenceFixture open() throws Exception { + Server server = entityReferenceServer(); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("localhost:" + server.getPort()); + var client = + new CanonicalPreseededActorRuntimeReferenceClient( + endpoints, + pki.clientProperties(pkiDirectory, pki.identity("client")), + new GrpcChannelFactory(), + "firemud"); + try { + client.init(); + return new EntityReferenceFixture(server, client); + } catch (Exception failure) { + client.close(); + server.shutdownNow(); + throw failure; + } + } + + CanonicalPreseededActorRuntimeReferenceClient client() { + return client; + } + + @Override + public void close() throws Exception { + client.close(); + server.shutdownNow(); + if (!server.awaitTermination(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled Entity reference server did not terminate"); + } + } + } + private static final class RedisFixture implements AutoCloseable { private final RedisClient administrator; private final RedisClient ownerClient; @@ -882,4 +1166,6 @@ public void close() { administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); } } + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index 769a81bb58..baeb518b7c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -23,11 +23,13 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; @@ -40,6 +42,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; @@ -84,6 +87,287 @@ public static Proof installAndBridge( .first(); } + /** + * Runs the physical region bridge first, then the actual Account-member repair owner and retry. + */ + public static MemberRepairProof installAndBridgeThenRepairAccountMember( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) + throws Exception { + Proof regionBridge = + installAndBridge( + dsl, + redisHost, + redisPort, + worldRequest, + currentTarget, + worldRegionResolver, + entityReferenceClient); + return repairAccountMemberAfterRegionBridge(dsl, redisHost, redisPort, regionBridge); + } + + private static MemberRepairProof repairAccountMemberAfterRegionBridge( + DSLContext dsl, String redisHost, int redisPort, Proof regionBridge) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + try (var redis = RegionRedis.openForMemberRepair(redisHost, redisPort)) { + var catalog = + RedisScriptCatalog.fromContributions( + List.of( + new CanonicalGameplayRegionLeaseRedisScriptContribution(), + new CanonicalGameplayRegionBindingBridgeRedisScriptContribution(), + new CanonicalGameplayAccountMemberRepairRedisScriptContribution())); + Record bridgeBefore = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE transition_id = ?", + regionBridge.transitionId()), + "persisted region bridge acknowledgement"); + BigInteger bridgeRevision = + new BigInteger(Objects.requireNonNull(bridgeBefore.get("inventory_revision")).toString()); + String bridgeEvidenceBefore = + dsl.fetchSingle( + "SELECT (to_jsonb(obligation) - 'inventory_revision')::text AS image" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " WHERE transition_id = ?", + regionBridge.transitionId()) + .get("image", String.class); + boolean originalAcknowledgementMatchesBridgeProof = + "ACKNOWLEDGED".equals(bridgeBefore.get("status", String.class)) + && regionBridge + .bridgeOperationId() + .equals(bridgeBefore.get("bridge_operation_id", UUID.class)) + && regionBridge + .executorFence() + .equals( + new BigInteger( + Objects.requireNonNull( + bridgeBefore.get("executor_fence"), + "persisted region executor fence") + .toString())) + && regionBridge + .redisReadbackDigest() + .equals(bridgeBefore.get("redis_readback_digest", String.class)) + && bridgeRevision.equals(regionBridge.acknowledgedInventoryRevision()) + && regionBridge + .acknowledgedAt() + .truncatedTo(ChronoUnit.MICROS) + .equals( + bridgeBefore + .get("acknowledged_at", java.time.OffsetDateTime.class) + .toInstant()); + RegionBridgeRedisState regionRedisBefore = + snapshotRegionBridgeRedisState(redis, bridgeBefore, regionBridge.runtimeEntityId()); + Set accountMembersBefore = + snapshotAccountMembers(redis, bridgeBefore.get("account_id", UUID.class)); + String accountControlImageBefore = + accountControlImage(dsl, bridgeBefore.get("account_id", UUID.class)); + var inventoryBefore = inventory.readSnapshot(); + var accountRepairOwner = + new CanonicalGameplayAccountMemberRepairOwner(dsl, redis.ownerClient(), catalog); + + CanonicalGameplayAccountMemberAcknowledgement acknowledgement = + accountRepairOwner.repair(regionBridge.transitionId()); + var inventoryAfterAcknowledgement = inventory.readSnapshot(); + BigInteger expectedRevision = bridgeRevision.add(BigInteger.ONE); + Record bridgeAfter = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE transition_id = ?", + regionBridge.transitionId()), + "region bridge acknowledgement after member repair"); + String bridgeEvidenceAfter = + dsl.fetchSingle( + "SELECT (to_jsonb(obligation) - 'inventory_revision')::text AS image" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " WHERE transition_id = ?", + regionBridge.transitionId()) + .get("image", String.class); + RegionBridgeRedisState regionRedisAfterAcknowledgement = + snapshotRegionBridgeRedisState(redis, bridgeAfter, regionBridge.runtimeEntityId()); + Set accountMembersAfter = snapshotAccountMembers(redis, acknowledgement.accountId()); + String accountControlImageAfterAcknowledgement = + accountControlImage(dsl, acknowledgement.accountId()); + Set expectedAccountMembers = new java.util.TreeSet<>(accountMembersBefore); + expectedAccountMembers.add(acknowledgement.member()); + boolean sharedRevisionPropagated = + inventoryAfterAcknowledgement.inventoryRevision().equals(expectedRevision) + && inventoryAfterAcknowledgement.bindings().size() == 1 + && "PROVISIONAL" + .equals(inventoryAfterAcknowledgement.bindings().getFirst().lifecycle().name()) + && "ACKNOWLEDGED" + .equals( + inventoryAfterAcknowledgement + .bindings() + .getFirst() + .accountIndexState() + .name()) + && "REPAIR_REQUIRED" + .equals( + inventoryAfterAcknowledgement.bindings().getFirst().issuerIndexState().name()) + && inventoryAfterAcknowledgement + .bindings() + .getFirst() + .inventoryRevision() + .equals(expectedRevision) + && inventoryAfterAcknowledgement.transitions().size() == 1 + && "PROVISIONAL" + .equals(inventoryAfterAcknowledgement.transitions().getFirst().status().name()) + && inventoryAfterAcknowledgement + .transitions() + .getFirst() + .inventoryRevision() + .equals(expectedRevision) + && inventoryAfterAcknowledgement.reservations().size() == 1 + && inventoryAfterAcknowledgement + .reservations() + .getFirst() + .inventoryRevision() + .equals(expectedRevision) + && inventoryAfterAcknowledgement.accountIndexObligations().size() == 1 + && "ACKNOWLEDGED" + .equals( + inventoryAfterAcknowledgement + .accountIndexObligations() + .getFirst() + .status() + .name()) + && inventoryAfterAcknowledgement + .accountIndexObligations() + .getFirst() + .inventoryRevision() + .equals(expectedRevision) + && inventoryAfterAcknowledgement.issuerIndexObligations().size() == 1 + && "REQUIRED" + .equals( + inventoryAfterAcknowledgement + .issuerIndexObligations() + .getFirst() + .status() + .name()) + && inventoryAfterAcknowledgement + .issuerIndexObligations() + .getFirst() + .inventoryRevision() + .equals(expectedRevision) + && inventoryAfterAcknowledgement.regionBridgeObligations().size() == 1 + && "ACKNOWLEDGED" + .equals( + inventoryAfterAcknowledgement + .regionBridgeObligations() + .getFirst() + .status() + .name()) + && inventoryAfterAcknowledgement + .regionBridgeObligations() + .getFirst() + .inventoryRevision() + .equals(expectedRevision) + && "RESERVED" + .equals( + inventoryAfterAcknowledgement.reservations().getFirst().lifecycle().name()) + && new BigInteger( + Objects.requireNonNull( + bridgeAfter.get("inventory_revision"), + "region acknowledgement inventory revision after member repair") + .toString()) + .equals(expectedRevision); + boolean bridgeAcknowledgementEvidenceUnchanged = + originalAcknowledgementMatchesBridgeProof + && bridgeEvidenceBefore.equals(bridgeEvidenceAfter) + && "ACKNOWLEDGED".equals(bridgeAfter.get("status", String.class)); + boolean physicalBridgeEvidenceUnchanged = + regionRedisBefore.equals(regionRedisAfterAcknowledgement) + && regionRedisBefore.leaseValue() != null + && regionRedisBefore.metadata().size() == 5 + && regionRedisBefore.sessionBindingValue().size() == 2; + boolean accountMemberAddedExactly = expectedAccountMembers.equals(accountMembersAfter); + boolean accountControlStatePreserved = + accountControlImageBefore.equals(accountControlImageAfterAcknowledgement); + String memberRepairOperationImageAfterAcknowledgement = + dsl.fetchSingle( + "SELECT to_jsonb(operation)::text AS image" + + " FROM game_session_canonical_account_member_repair_operation operation" + + " WHERE operation_id = ?", + acknowledgement.operationId()) + .get("image", String.class); + String accountCoverageControlImageAfterAcknowledgement = + dsl.fetchSingle( + "SELECT to_jsonb(control)::text AS image" + + " FROM game_session_canonical_account_coverage_control control" + + " WHERE account_id = ?", + acknowledgement.accountId()) + .get("image", String.class); + + CanonicalGameplayAccountMemberAcknowledgement retry = + accountRepairOwner.repair(regionBridge.transitionId()); + var inventoryAfterRetry = inventory.readSnapshot(); + Record bridgeAfterRetry = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE transition_id = ?", + regionBridge.transitionId()), + "region bridge acknowledgement after exact member retry"); + String bridgeEvidenceAfterRetry = + dsl.fetchSingle( + "SELECT (to_jsonb(obligation) - 'inventory_revision')::text AS image" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " WHERE transition_id = ?", + regionBridge.transitionId()) + .get("image", String.class); + String memberRepairOperationImageAfterRetry = + dsl.fetchSingle( + "SELECT to_jsonb(operation)::text AS image" + + " FROM game_session_canonical_account_member_repair_operation operation" + + " WHERE operation_id = ?", + acknowledgement.operationId()) + .get("image", String.class); + String accountCoverageControlImageAfterRetry = + accountControlImage(dsl, acknowledgement.accountId()); + boolean exactMemberRetryPreservedState = + acknowledgement.equals(retry) + && inventoryAfterAcknowledgement.equals(inventoryAfterRetry) + && bridgeEvidenceAfter.equals(bridgeEvidenceAfterRetry) + && memberRepairOperationImageAfterAcknowledgement.equals( + memberRepairOperationImageAfterRetry) + && accountCoverageControlImageAfterAcknowledgement.equals( + accountCoverageControlImageAfterRetry) + && regionRedisAfterAcknowledgement.equals( + snapshotRegionBridgeRedisState( + redis, bridgeAfterRetry, regionBridge.runtimeEntityId())) + && accountMembersAfter.equals( + snapshotAccountMembers(redis, acknowledgement.accountId())); + if (!sharedRevisionPropagated + || !bridgeAcknowledgementEvidenceUnchanged + || !physicalBridgeEvidenceUnchanged + || !accountMemberAddedExactly + || !accountControlStatePreserved + || !exactMemberRetryPreservedState + || inventoryBefore.inventoryRevision().compareTo(bridgeRevision) != 0) { + throw new IllegalStateException( + "Reverse-order region and Account-member acknowledgements did not preserve exact evidence"); + } + return new MemberRepairProof( + regionBridge, + acknowledgement, + bridgeRevision, + expectedRevision, + sharedRevisionPropagated, + bridgeAcknowledgementEvidenceUnchanged, + physicalBridgeEvidenceUnchanged, + accountMemberAddedExactly, + accountControlStatePreserved, + exactMemberRetryPreservedState); + } + } + /** Runs the real first owner chain, then exercises a second candidate under its private grant. */ public static TwoBindingProof installAndBridgeTwoCandidates( DSLContext dsl, @@ -981,6 +1265,52 @@ private static RegionRedisState snapshotRegionRedisState( Map.copyOf(metadata)); } + private static RegionBridgeRedisState snapshotRegionBridgeRedisState( + RegionRedis redis, Record bridgeRow, long runtimeEntityId) { + UUID tenantId = bridgeRow.get("tenant_id", UUID.class); + UUID gameInstanceId = bridgeRow.get("game_instance_id", UUID.class); + UUID regionId = bridgeRow.get("region_id", UUID.class); + String metaKey = CanonicalGameplayRegionRedisKeys.meta(tenantId, gameInstanceId, regionId); + Map metadata = new LinkedHashMap<>(); + redis + .admin() + .hgetall(ascii(metaKey)) + .forEach((field, value) -> metadata.put(asciiString(field), asciiString(value))); + Map sessionBinding = new LinkedHashMap<>(); + redis + .admin() + .hgetall( + ascii( + CanonicalGameplayRegionRedisKeys.sessionBinding( + tenantId, gameInstanceId, regionId, runtimeEntityId))) + .forEach((field, value) -> sessionBinding.put(asciiString(field), asciiString(value))); + return new RegionBridgeRedisState( + asciiString( + redis + .admin() + .get( + ascii( + CanonicalGameplayRegionRedisKeys.lease( + tenantId, gameInstanceId, regionId)))), + Map.copyOf(metadata), + Map.copyOf(sessionBinding)); + } + + private static Set snapshotAccountMembers(RegionRedis redis, UUID accountId) { + return redis.admin().smembers(ascii("session:game:index:account:" + accountId)).stream() + .map(CanonicalGameplayRegionOwnerCompositionFixture::asciiString) + .collect(java.util.stream.Collectors.toCollection(java.util.TreeSet::new)); + } + + private static String accountControlImage(DSLContext dsl, UUID accountId) { + return dsl.fetchSingle( + "SELECT to_jsonb(control)::text AS image" + + " FROM game_session_canonical_account_coverage_control control" + + " WHERE account_id = ?", + accountId) + .get("image", String.class); + } + private static String asciiString(byte[] value) { return value == null ? null : new String(value, StandardCharsets.US_ASCII); } @@ -1031,6 +1361,21 @@ public record TwoBindingProof( private record RegionRedisState( String leaseType, String leaseValue, Map metadata) {} + private record RegionBridgeRedisState( + String leaseValue, Map metadata, Map sessionBindingValue) {} + + public record MemberRepairProof( + Proof regionBridge, + CanonicalGameplayAccountMemberAcknowledgement memberAcknowledgement, + BigInteger regionAcknowledgedInventoryRevision, + BigInteger memberAcknowledgedInventoryRevision, + boolean sharedRevisionPropagated, + boolean regionAcknowledgementEvidenceUnchanged, + boolean physicalBridgeEvidenceUnchanged, + boolean accountMemberAddedExactly, + boolean accountControlStatePreserved, + boolean exactMemberRetryPreservedState) {} + public record AccountAbortProof( UUID transitionId, UUID cleanupId, @@ -1066,13 +1411,20 @@ private RegionRedis( } static RegionRedis open(String host, int port) { + return open(host, port, false); + } + + static RegionRedis openForMemberRepair(String host, int port) { + return open(host, port, true); + } + + private static RegionRedis open(String host, int port, boolean allowAccountMemberRepair) { var baseUri = RedisURI.Builder.redis(host, port).withTimeout(Duration.ofSeconds(5)).build(); RedisClient administrator = RedisClient.create(baseUri); StatefulRedisConnection adminConnection = administrator.connect(ByteArrayCodec.INSTANCE); RedisCommands admin = adminConnection.sync(); - admin.aclSetuser( - REDIS_PRINCIPAL, + AclSetuserArgs permissions = new AclSetuserArgs() .reset() .on() @@ -1092,7 +1444,14 @@ static RegionRedis open(String host, int port) { .addCommand(CommandType.PTTL) .addCommand(CommandType.GET) .addCommand(CommandType.SET) - .addCommand(CommandType.PEXPIRE)); + .addCommand(CommandType.PEXPIRE); + if (allowAccountMemberRepair) { + permissions + .keyPattern("session:game:index:account:*") + .addCommand(CommandType.SADD) + .addCommand(CommandType.SISMEMBER); + } + admin.aclSetuser(REDIS_PRINCIPAL, permissions); RedisURI ownerUri = RedisURI.Builder.redis(host, port) .withTimeout(Duration.ofSeconds(5)) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java index 06d11b00b1..aa62f4ce45 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java @@ -191,21 +191,129 @@ void regionReadRequiresRetainedAppliedPlacementAndFreshExactEntityReceipt() { } @Test - void mismatchedEntityReceiptStopsBeforeHoldOrPlacementWrite() { + void regionReadWithAbsentPlacementReturnsEmptyWithoutReadingRegion() { var selection = CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request()); var location = emptyLocation(selection); var holds = mock(WorldCanonicalInitialAdmissionHoldRepository.class); var gameSession = mock(GameSessionCanonicalInitialAdmissionOwnerClient.class); + var entityReads = new AtomicInteger(); + var service = + service( + selection, + location, + holds, + gameSession, + ignored -> { + entityReads.incrementAndGet(); + throw new AssertionError("Absent placement must not read the Entity receipt"); + }); + + assertThat(service.readRegion(selection)).isEmpty(); + assertThat(entityReads.get()).isZero(); + verify(location, never()).readInitialPlayerLocationRegion(any(RequestSelector.class)); + verify(location, never()).store(any()); + verifyNoInteractions(holds, gameSession); + } + + @Test + void regionReadWithRetainedConflictFailsBeforeReadingRegion() { + var selection = CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request()); + var conflict = + new Result( + Outcome.CONFLICT, + "CHARACTER_ALREADY_PLACED", + null, + null, + new byte[] {1}, + "sha256:" + "a".repeat(64), + new byte[] {2}, + "sha256:" + "b".repeat(64), + true); + var location = mock(WorldCanonicalInitialPlayerLocationRepository.class); + when(location.readByOperationId( + eq(selection.placementOperationId()), any(RequestSelector.class))) + .thenReturn(Optional.of(conflict)); + var holds = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var gameSession = mock(GameSessionCanonicalInitialAdmissionOwnerClient.class); + var entityReads = new AtomicInteger(); + var service = + service( + selection, + location, + holds, + gameSession, + ignored -> { + entityReads.incrementAndGet(); + return entityReceipt(selection); + }); + + assertThatThrownBy(() -> service.readRegion(selection)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(entityReads.get()).isZero(); + verify(location, never()).readInitialPlayerLocationRegion(any(RequestSelector.class)); + verify(location, never()).store(any()); + verifyNoInteractions(holds, gameSession); + } + + @Test + void mismatchedEntityReceiptStopsRegionReadBeforePlacementMutation() { + var selection = CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request()); + var placement = + new Result( + Outcome.APPLIED, + null, + new RoomTemplateRef(TENANT, VERSION, uuid("abababab-abab-4bab-8bab-abababababab")), + 9182L, + new byte[] {1}, + "sha256:" + "a".repeat(64), + new byte[] {2}, + "sha256:" + "b".repeat(64), + true); + var location = mock(WorldCanonicalInitialPlayerLocationRepository.class); + when(location.readByOperationId( + eq(selection.placementOperationId()), any(RequestSelector.class))) + .thenReturn(Optional.of(placement)); + var holds = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var gameSession = mock(GameSessionCanonicalInitialAdmissionOwnerClient.class); + var entityReads = new AtomicInteger(); var service = service( selection, location, holds, gameSession, - ignored -> - entityReceipt(selection).toBuilder() - .setCharacterUuid(uuid("66666666-6666-4666-8666-666666666666").toString()) - .build()); + ignored -> { + entityReads.incrementAndGet(); + return mismatchedEntityReceipt(selection); + }); + + assertThatThrownBy(() -> service.readRegion(selection)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(entityReads.get()).isEqualTo(1); + verify(location, never()).readInitialPlayerLocationRegion(any(RequestSelector.class)); + verify(location, never()).store(any()); + verifyNoInteractions(holds, gameSession); + } + + @Test + void mismatchedEntityReceiptStopsBeforeHoldOrPlacementWrite() { + var selection = CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request()); + var location = emptyLocation(selection); + var holds = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var gameSession = mock(GameSessionCanonicalInitialAdmissionOwnerClient.class); + var service = + service( + selection, location, holds, gameSession, ignored -> mismatchedEntityReceipt(selection)); assertThatThrownBy(() -> service.place(selection)) .isInstanceOf(StatusRuntimeException.class) @@ -479,6 +587,13 @@ private static ReadPreseededActorAssignmentReceiptResponse entityReceipt( .build(); } + private static ReadPreseededActorAssignmentReceiptResponse mismatchedEntityReceipt( + CanonicalInitialPlayerLocationGrpcCodec.Selection selection) { + return entityReceipt(selection).toBuilder() + .setCharacterUuid(uuid("66666666-6666-4666-8666-666666666666").toString()) + .build(); + } + private static CanonicalInitialPlayerLocationRequest request() { return CanonicalInitialPlayerLocationRequest.newBuilder() .setSchemaVersion(1) From 3ad391286ff5609c2ecc37c089ab4d5e8b7ebe30 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:24:36 +1300 Subject: [PATCH 18/36] fix: retain region acknowledgement across grant replacement --- ...calGameplayBindingInventoryRepository.java | 58 ++++-- ...meplayRegionLeaseOwnerIntegrationTest.java | 96 ++++++++- ...GameplayRegionOwnerCompositionFixture.java | 187 ++++++++++++++++++ ...ationOwnerCompositionCrossServiceTest.java | 3 + 4 files changed, 319 insertions(+), 25 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 7c1cd2cd1e..80277d083b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -338,14 +338,13 @@ CanonicalGameplayBindingRegionBridgeObligation prepareRegionBridge( && Objects.equals( existing.leaseTokenCorrelation(), ownerStatus.leaseTokenCorrelation()); if (sameGrant) return existing; + if (existing.status() + == CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { + throw conflict( + "A completed region bridge acknowledgement cannot be rewritten for a new grant"); + } return rewritePreparedBridgeForCurrentGrant( - transaction, - currentRevision, - currentEvidence, - regionRow, - existing, - inputs, - ownerStatus); + transaction, currentRevision, currentEvidence, existing, inputs, ownerStatus); } if (preimage.state() != CanonicalGameplayRegionLeaseRedisOwner.PreimageState.ABSENT) { throw conflict("First region bridge operation requires a proven absent Redis preimage"); @@ -470,7 +469,6 @@ private CanonicalGameplayBindingRegionBridgeObligation rewritePreparedBridgeForC DSLContext transaction, BigInteger currentRevision, CanonicalGameplayBindingProvisionalCasEvidence evidence, - Record regionRow, CanonicalGameplayBindingRegionBridgeObligation existing, BridgeInputs inputs, CanonicalGameplayRegionRuntimeStatus ownerStatus) { @@ -484,7 +482,7 @@ private CanonicalGameplayBindingRegionBridgeObligation rewritePreparedBridgeForC + " SET status = 'REQUIRED', executor_fence = ?, lease_token_correlation = ?," + " redis_readback_digest = NULL, acknowledged_at = NULL, inventory_revision = ?" + " WHERE transition_id = ? AND bridge_operation_id = ?" - + " AND inventory_revision = ?", + + " AND status = 'REQUIRED' AND inventory_revision = ?", decimal(ownerStatus.executorFence()), ownerStatus.leaseTokenCorrelation(), decimal(nextRevision), @@ -493,15 +491,23 @@ private CanonicalGameplayBindingRegionBridgeObligation rewritePreparedBridgeForC decimal(oldRevision)), "Prepared region bridge changed before current-grant revalidation"); bumpInventoryClock(transaction, currentRevision, nextRevision); - return toRegionObligation( - Objects.requireNonNull( - transaction.fetchOne( - "SELECT * FROM " - + REGION_OBLIGATION - + " WHERE transition_id = ? AND bridge_operation_id = ?", - evidence.transition().transitionId(), - existing.bridgeOperationId()), - "prepared region bridge row must survive current-grant readback")); + Record row = + transaction.fetchOne( + "SELECT * FROM " + + REGION_OBLIGATION + + " WHERE transition_id = ? AND bridge_operation_id = ?", + evidence.transition().transitionId(), + existing.bridgeOperationId()); + CanonicalGameplayBindingRegionBridgeObligation rewritten = + row == null ? null : toRegionObligation(row); + if (rewritten == null + || rewritten.status() != CanonicalGameplayBindingRegionBridgeObligation.Status.REQUIRED + || !matchesPreparedOperationForGrant( + rewritten, inputs, existing.bridgeOperationId(), ownerStatus) + || !rewritten.inventoryRevision().equals(nextRevision)) { + throw conflict("Prepared region bridge did not survive exact current-grant readback"); + } + return rewritten; } private CanonicalGameplayBindingRegionBridgeObligation writePreparedBridge( @@ -563,12 +569,26 @@ private CanonicalGameplayBindingRegionBridgeObligation writePreparedBridge( evidence.transition().transitionId()); CanonicalGameplayBindingRegionBridgeObligation result = row == null ? null : toRegionObligation(row); - if (result == null || !matchesPreparedOperation(result, inputs)) { + if (result == null + || result.status() != CanonicalGameplayBindingRegionBridgeObligation.Status.REQUIRED + || !matchesPreparedOperationForGrant(result, inputs, operationId, ownerStatus) + || !result.inventoryRevision().equals(nextRevision)) { throw conflict("Region bridge operation did not survive durable SQL readback"); } return result; } + private static boolean matchesPreparedOperationForGrant( + CanonicalGameplayBindingRegionBridgeObligation obligation, + BridgeInputs inputs, + UUID expectedOperationId, + CanonicalGameplayRegionRuntimeStatus ownerStatus) { + return expectedOperationId.equals(obligation.bridgeOperationId()) + && matchesPreparedOperation(obligation, inputs) + && Objects.equals(obligation.executorFence(), ownerStatus.executorFence()) + && Objects.equals(obligation.leaseTokenCorrelation(), ownerStatus.leaseTokenCorrelation()); + } + private static void writeRevisionRows( DSLContext transaction, CanonicalGameplayBindingProvisionalCasEvidence evidence, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 104efd1f6b..5e57d664ad 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -22,6 +22,8 @@ import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -31,6 +33,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import javax.sql.DataSource; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -75,6 +78,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DelegatingDataSource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.testcontainers.containers.GenericContainer; @@ -126,7 +130,7 @@ static void certificates() throws Exception { @Test void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws Exception { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); - DriverManagerDataSource dataSource = dataSource(); + ControlledConnectionFailureDataSource dataSource = dataSource(); Flyway.configure() .dataSource(dataSource) .locations( @@ -464,7 +468,8 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(redis.admin().pexpire(redisKey, 0L)).isTrue(); world.resetReads(); - world.setAfterRead(2, POSTGRES::stop); + var ownerStatusBeforeSqlOutage = statusRepository.find(qualifiedSource).orElseThrow(); + world.setAfterRead(2, dataSource::failConnections); var sixthOwner = owner( bindingInventory, @@ -473,8 +478,13 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws world, "instance-f", incarnationSource); - assertThatThrownBy(() -> sixthOwner.installForTransition(TRANSITION_ID, world.request())) - .isInstanceOf(RuntimeException.class); + Throwable sqlOutageFailure = + catchThrowable(() -> sixthOwner.installForTransition(TRANSITION_ID, world.request())); + dataSource.restoreConnections(); + assertThat(sqlOutageFailure) + .isInstanceOf(RuntimeException.class) + .hasRootCauseInstanceOf(SQLException.class); + assertThat(statusRepository.find(qualifiedSource)).contains(ownerStatusBeforeSqlOutage); assertThat(redis.admin().type(redisKey)).isEqualTo("string"); assertThat(redis.admin().pttl(redisKey)).isPositive(); } @@ -529,6 +539,48 @@ void accountMemberAcknowledgementAfterRegionBridgePreservesOriginalBridgeEvidenc } } + @Test + void acknowledgedRegionBridgeSurvivesExpiredGrantReplacement() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try { + try (RedisFixture redis = RedisFixture.open()) { + redis.admin().flushdb(); + } + // This local candidate-launch source is created through the real Game Session owners; + // its upstream publication inputs remain controlled test evidence. + var runtimeTarget = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + testSchema.dataSource(), UUID.randomUUID(), "firemud"); + WorldFixture world = WorldFixture.open(runtimeTarget); + try (var entitySource = EntityReferenceFixture.open()) { + CanonicalGameplayRegionOwnerCompositionFixture.ChangedGrantProof proof = + CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeThenChangedGrantRefuses( + testSchema.dsl(), + REDIS.getHost(), + REDIS.getMappedPort(REDIS_PORT), + world.request(), + runtimeTarget.playableTarget(), + world.resolver(), + entitySource.client()); + + assertThat(proof.acknowledgedBridge().exactLostReplyRetry()).isTrue(); + assertThat(proof.replacementGrantInstalled()).isTrue(); + assertThat(proof.replacementExecutorFence()) + .isGreaterThan(proof.acknowledgedBridge().executorFence()); + assertThat(proof.bridgeRefused()).isTrue(); + assertThat(proof.refusalMessage()) + .isEqualTo( + "A completed region bridge acknowledgement cannot be rewritten for a new grant"); + assertThat(proof.acknowledgementRowPreserved()).isTrue(); + assertThat(proof.inventoryStatePreserved()).isTrue(); + assertThat(proof.physicalBridgeStatePreserved()).isTrue(); + } + } finally { + dropSchema(testSchema.schema()); + } + } + private static Server entityReferenceServer() throws Exception { var service = new CanonicalPreseededActorAssignmentServiceGrpc @@ -579,13 +631,45 @@ private static ReadPreseededActorRuntimeReferenceResponse entityResponse( .build(); } - private static DriverManagerDataSource dataSource() { + private static ControlledConnectionFailureDataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(POSTGRES.getDriverClassName()); dataSource.setUrl(POSTGRES.getJdbcUrl()); dataSource.setUsername(POSTGRES.getUsername()); dataSource.setPassword(POSTGRES.getPassword()); - return dataSource; + return new ControlledConnectionFailureDataSource(dataSource); + } + + private static final class ControlledConnectionFailureDataSource extends DelegatingDataSource { + private volatile boolean connectionsUnavailable; + + private ControlledConnectionFailureDataSource(DataSource target) { + super(target); + } + + void failConnections() { + connectionsUnavailable = true; + } + + void restoreConnections() { + connectionsUnavailable = false; + } + + @Override + public Connection getConnection() throws SQLException { + if (connectionsUnavailable) { + throw new SQLException("Controlled test-owned PostgreSQL connection failure"); + } + return super.getConnection(); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + if (connectionsUnavailable) { + throw new SQLException("Controlled test-owned PostgreSQL connection failure"); + } + return super.getConnection(username, password); + } } private static TestSchema newTestSchema() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index baeb518b7c..d43bd377dd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -25,6 +25,7 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.runtime.RuntimeIdentity; @@ -42,6 +43,7 @@ import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; @@ -87,6 +89,30 @@ public static Proof installAndBridge( .first(); } + /** Reacquires a real region grant after the bridge ACK and proves that the ACK remains closed. */ + public static ChangedGrantProof installAndBridgeThenChangedGrantRefuses( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) + throws Exception { + var capture = new AtomicReference(); + installAndBridgeInternal( + dsl, + redisHost, + redisPort, + worldRequest, + currentTarget, + worldRegionResolver, + entityReferenceClient, + null, + capture); + return Objects.requireNonNull(capture.get(), "changed-grant bridge proof"); + } + /** * Runs the physical region bridge first, then the actual Account-member repair owner and retry. */ @@ -400,6 +426,29 @@ private static TwoBindingProof installAndBridgeInternal( CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, SecondBinding secondBinding) throws Exception { + return installAndBridgeInternal( + dsl, + redisHost, + redisPort, + worldRequest, + currentTarget, + worldRegionResolver, + entityReferenceClient, + secondBinding, + null); + } + + private static TwoBindingProof installAndBridgeInternal( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + SecondBinding secondBinding, + AtomicReference changedGrantProofCapture) + throws Exception { UUID transitionId = UUID.randomUUID(); UUID sessionId = UUID.randomUUID(); var resolved = worldRegionResolver.resolve(worldRequest); @@ -529,6 +578,20 @@ private static TwoBindingProof installAndBridgeInternal( acknowledged.acknowledgedAt(), acknowledged.equals(replayed)); if (secondBinding == null) { + if (changedGrantProofCapture != null) { + changedGrantProofCapture.set( + reacquireGrantAfterAcknowledgement( + dsl, + redis, + scriptCatalog, + stableSource, + worldRegionResolver, + bridgeEntityReferenceClient, + worldRequest, + firstProof, + installation, + status)); + } return new TwoBindingProof(firstProof, null, null, true, true, true, true, true); } @@ -775,6 +838,120 @@ private static TwoBindingProof installAndBridgeInternal( } } + private static ChangedGrantProof reacquireGrantAfterAcknowledgement( + DSLContext dsl, + RegionRedis redis, + RedisScriptCatalog scriptCatalog, + ControlledStableIncarnationSource stableSource, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + CanonicalInitialPlayerLocationRequest worldRequest, + Proof acknowledged, + CanonicalGameplayRegionLeaseOwner.Installation originalInstallation, + CanonicalGameplayRegionRuntimeStatus originalStatus) { + String acknowledgedRowBeforeGrant = regionBridgeRowImage(dsl, acknowledged.transitionId()); + byte[] leaseKey = + ascii( + CanonicalGameplayRegionRedisKeys.lease( + originalInstallation.source.tenantId(), + originalInstallation.source.gameInstanceId(), + originalInstallation.source.regionId())); + if (!redis.admin().pexpire(leaseKey, 0L)) { + throw new IllegalStateException("The acknowledged bridge grant could not be expired"); + } + + RuntimeIdentity replacementIdentity = + new RuntimeIdentity( + "game-session-service", + "region-owner-composition-replacement", + "localhost", + Instant.now(), + "test", + "test", + "controlled-test-image"); + var replacementOwner = + CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( + dsl, + redis.ownerClient(), + scriptCatalog, + stableSource, + worldRegionResolver, + entityReferenceClient, + replacementIdentity, + Duration.ofSeconds(30), + Clock.systemUTC()); + var replacementInstallation = + replacementOwner.installForTransition(acknowledged.transitionId(), worldRequest); + CanonicalGameplayRegionRuntimeStatus replacementStatus = + new CanonicalGameplayRegionRuntimeStatusRepository(dsl) + .find(originalInstallation.source) + .orElseThrow(); + + String acknowledgedRowBeforeRefusal = regionBridgeRowImage(dsl, acknowledged.transitionId()); + Record acknowledgedRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE transition_id = ?", + acknowledged.transitionId()), + "acknowledged bridge row after grant replacement"); + RegionBridgeRedisState physicalBridgeBeforeRefusal = + snapshotRegionBridgeRedisState(redis, acknowledgedRow, acknowledged.runtimeEntityId()); + var inventoryBeforeRefusal = + new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot(); + + boolean bridgeRefused; + String refusalMessage; + try { + replacementOwner.bridge(replacementInstallation); + bridgeRefused = false; + refusalMessage = null; + } catch (CanonicalGameplayBindingInventoryConflictException expected) { + bridgeRefused = true; + refusalMessage = expected.getMessage(); + } + + String acknowledgedRowAfterRefusal = regionBridgeRowImage(dsl, acknowledged.transitionId()); + var acknowledgedRowAfter = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE transition_id = ?", + acknowledged.transitionId()), + "acknowledged bridge row after changed-grant bridge refusal"); + RegionBridgeRedisState physicalBridgeAfterRefusal = + snapshotRegionBridgeRedisState(redis, acknowledgedRowAfter, acknowledged.runtimeEntityId()); + var inventoryAfterRefusal = new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot(); + boolean replacementGrantInstalled = + replacementStatus.executorFence().compareTo(acknowledged.executorFence()) > 0 + && !originalStatus + .leaseTokenCorrelation() + .equals(replacementStatus.leaseTokenCorrelation()) + && "region-owner-composition-replacement".equals(replacementStatus.ownerInstanceId()); + return new ChangedGrantProof( + acknowledged, + replacementStatus.executorFence(), + replacementGrantInstalled, + bridgeRefused, + refusalMessage, + acknowledgedRowBeforeGrant.equals(acknowledgedRowBeforeRefusal) + && acknowledgedRowBeforeRefusal.equals(acknowledgedRowAfterRefusal), + inventoryBeforeRefusal.equals(inventoryAfterRefusal), + physicalBridgeBeforeRefusal.equals(physicalBridgeAfterRefusal)); + } + + private static String regionBridgeRowImage(DSLContext dsl, UUID transitionId) { + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(obligation)::text AS image" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " WHERE transition_id = ?", + transitionId), + "persisted region bridge obligation image"); + return Objects.requireNonNull(row.get("image", String.class), "region bridge row image"); + } + private static boolean sameAbortSource( CanonicalGameplayAdmissionAbortSource expected, CanonicalGameplayAdmissionAbortSource actual) { @@ -1376,6 +1553,16 @@ public record MemberRepairProof( boolean accountControlStatePreserved, boolean exactMemberRetryPreservedState) {} + public record ChangedGrantProof( + Proof acknowledgedBridge, + BigInteger replacementExecutorFence, + boolean replacementGrantInstalled, + boolean bridgeRefused, + String refusalMessage, + boolean acknowledgementRowPreserved, + boolean inventoryStatePreserved, + boolean physicalBridgeStatePreserved) {} + public record AccountAbortProof( UUID transitionId, UUID cleanupId, 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 c06dcb905e..c19815eb58 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 @@ -3188,6 +3188,7 @@ private static void composeActualEntityWorldRegionPrerequisite( try { assigned = CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub(assignmentChannel) + .withDeadlineAfter(10, TimeUnit.SECONDS) .assignPreseededActor(wireRequest); } catch (StatusRuntimeException failure) { throw new AssertionError( @@ -3202,6 +3203,7 @@ private static void composeActualEntityWorldRegionPrerequisite( .isEqualTo(assignmentRequest.mutationIntentDigest()); var assignmentRetry = CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub(assignmentChannel) + .withDeadlineAfter(10, TimeUnit.SECONDS) .assignPreseededActor(wireRequest); assertThat(assignmentRetry.toByteArray()).containsExactly(assigned.toByteArray()); var runtimeReferenceSelector = @@ -3220,6 +3222,7 @@ private static void composeActualEntityWorldRegionPrerequisite( () -> CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub( worldPeerChannel) + .withDeadlineAfter(10, TimeUnit.SECONDS) .readPreseededActorRuntimeReference(runtimeReferenceSelector)) .isInstanceOf(StatusRuntimeException.class) .satisfies( From e877aef57d7f528c108b093a51f2ff9ce87700ca Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:12:26 +1300 Subject: [PATCH 19/36] Fix region metadata refusals and Human runtime completion fence --- .../game-session-service/runtime-and-data.md | 2 + .../player-access-and-session.md | 2 + ...egion_executor_and_human_runtime_fence.sql | 496 ++++++++++++++++++ .../lua/game-session-region-lease-read.lua | 1 + .../lua/game-session-region-lease-renew.lua | 1 + ...-session-region-session-binding-bridge.lua | 1 + ...ame-session-region-timeline-initialize.lua | 1 + .../game-session-region-lease-read.json | 2 +- .../game-session-region-lease-renew.json | 2 +- ...session-region-session-binding-bridge.json | 2 +- ...me-session-region-timeline-initialize.json | 2 +- ...ayDecisionRuntimeFenceIntegrationTest.java | 153 +++++- ...indingBridgeRedisOwnerIntegrationTest.java | 24 +- ...meplayRegionLeaseOwnerIntegrationTest.java | 42 ++ ...yRegionLeaseRedisOwnerIntegrationTest.java | 36 ++ ...tionRepositoryPostgresIntegrationTest.java | 186 +++++++ ...onicalInitialPlayerLocationClientTest.java | 14 +- 17 files changed, 956 insertions(+), 11 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1044.2__region_executor_and_human_runtime_fence.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 e5cd7fc445..ee9f6047e8 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -71,6 +71,8 @@ The sections below define the target-state runtime contract. Current implementat The protected reservation retains the complete Account protection and original owner association on the Game Session attempt. A separate immutable runtime-completion record binds that protection to the exact launch, captured `STARTING` row version, and completed `RUNNING` row version; this completion changes no admission pointer or terminal. The existing initial-admission owner later writes the pointer, matching append-only audit, and immutable protected attempt/intent terminal together, while the Account-purpose read exposes the retained exact terminal for settlement. A protected `NO_PRIOR_POINTER` abort preserves a pointer independently created after its reservation; it terminalizes only its own retained attempt and intent, while positive commit keeps the original absence checks. Legacy unprotected rows remain readable but are not adopted as protected attempts. These local storage owners remain unregistered; the [API contract](./api-contracts.md#initial-admission-bind) owns the cross-owner behavior and the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) records proof and remaining limits. +The completed `RUNNING` row version is immutable provenance and a lower bound for later lease-bound decisions. An ordinary owner save may advance the current row version; each decision still requires the actual current `RUNNING` state, a version no earlier than completion, and every original launch, target, protection and terminal binding. A stopped runtime or changed source does not acquire authority through a later version number. + ### Persisted actor admission boundary Game Session does not persist or allocate the primary actor. It resolves the realm target, asks Entity Management for the valid roster/policy result, and keeps `CHARS` as discovery before `PLAY`. A normal binding requires one persisted `characterId`; controller uniqueness is `{tenantId, playableStateNamespaceId, characterId}`, with `accountId` owner evidence and `playableStateScope`, `gameInstanceId`, and region/epoch as routing/fence evidence. See [Entity Runtime and Data](../entity-management-service/runtime-and-data.md) for allocation, policy, descriptor/template, and fork-copy rules. 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 e1861d0bb6..389690a4dd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -466,6 +466,8 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The ## Validation and Proof +The region-owner CLI correction gate passed 40 freshly executed tests across the World client and five native PostgreSQL/Redis suites. It verifies exact positive BIGINT executor-fence migration, refusal of fractional/overflow/nonfinite retained fences, a real healthy Human runtime repository save retaining its immutable completion as a lower bound, and stale refusal without writes for incomplete timeline metadata across lease read/renew, timeline initialize/verify and binding bridge. Malformed, ambient-transaction and closed-client guards cover all three World RPCs. Fresh jOOQ generation, migration-frontier validation, affected Checkstyle/SpotBugs, formatting and documentation checks also passed. This is focused manually composed proof; production registration, custody, activation and genuine external World authority remain outside this qualification. + 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/services/game-session-service/src/main/resources/db/migration/V1044.2__region_executor_and_human_runtime_fence.sql b/services/game-session-service/src/main/resources/db/migration/V1044.2__region_executor_and_human_runtime_fence.sql new file mode 100644 index 0000000000..7b2805f9c5 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1044.2__region_executor_and_human_runtime_fence.sql @@ -0,0 +1,496 @@ +-- Region executor fences are issued by the BIGINT sequence and retain that exact domain. +-- Refuse invalid retained NUMERIC values before PostgreSQL's rounding cast can change them. +-- [jooq ignore start] +DO $$ +BEGIN + LOCK TABLE game_session_canonical_binding_region_bridge_obligation IN ACCESS EXCLUSIVE MODE; + IF EXISTS ( + SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation + WHERE executor_fence IS NOT NULL + AND (executor_fence::text IN ('NaN', 'Infinity', '-Infinity') + OR executor_fence < 1 + OR executor_fence > 9223372036854775807 + OR executor_fence <> trunc(executor_fence)) + ) THEN + RAISE EXCEPTION 'Retained region executor fence must be an exact positive BIGINT' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_region_executor_fence_exact_bigint_required'; + END IF; +END; +$$; +-- [jooq ignore stop] + +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + ALTER COLUMN executor_fence SET DATA TYPE bigint; + +-- A healthy RUNNING runtime may advance through ordinary repository saves after its immutable +-- Human completion. Preserve that completion as a lower bound and every exact source guard. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_running_runtime_for_lease_bound_binding_decision() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime_row game_instances%ROWTYPE; + approved_first_new_abort boolean := false; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from an existing PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + RETURN NEW; + END IF; + + -- Definitive Account abort is a permanent source, including after cleanup retries. + -- Inventory advancement may retain the source, but may never rewrite its decision. + IF OLD.status = 'ABORTED' AND OLD.admission_orphan_cleanup_id IS NOT NULL THEN + IF (to_jsonb(NEW) - 'inventory_revision') + IS DISTINCT FROM (to_jsonb(OLD) - 'inventory_revision') + OR NEW.inventory_revision < OLD.inventory_revision THEN + RAISE EXCEPTION 'Definitive first-NEW Account abort source is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_terminal_source_immutable'; + END IF; + RETURN NEW; + END IF; + + IF OLD.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND OLD.admission_lease_id IS NOT NULL THEN + IF OLD.status = 'PROVISIONAL' + AND NEW.status = 'ABORTED' + AND OLD.admission_lease_kind = 'NEW_BINDING' + AND OLD.expected_prior_binding_ref IS NULL + AND OLD.expected_prior_binding_generation IS NULL + AND OLD.admission_orphan_cleanup_id IS NULL + AND NEW.admission_orphan_cleanup_id IS NOT NULL + AND NEW.admission_orphan_cleanup_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND NEW.inventory_revision > OLD.inventory_revision THEN + approved_first_new_abort := true; + ELSIF NEW.status NOT IN ('PROVISIONAL', 'AMBIGUOUS') + OR (OLD.status = 'AMBIGUOUS' AND NEW.status <> 'AMBIGUOUS') THEN + RAISE EXCEPTION 'A lease-bound runtime fence cannot be released without definitive first-NEW Account abort evidence' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_terminal_owner_required'; + END IF; + + IF approved_first_new_abort + AND ROW( + NEW.transition_id, NEW.tenant_id, NEW.playable_state_namespace_id, + NEW.character_id, NEW.expected_prior_binding_ref, + NEW.expected_prior_binding_generation, NEW.candidate_binding_ref, + NEW.candidate_binding_generation, NEW.candidate_account_index_fence, + NEW.issuer_reservation_id, NEW.created_at, + NEW.account_coverage_state, NEW.account_coverage_operation_id, + NEW.account_coverage_lifecycle, NEW.account_coverage_operation_fence, + NEW.account_admission_fence_kind, NEW.account_admission_fence, + NEW.historical_account_admission_fence_kind, + NEW.historical_account_admission_fence, NEW.resolved_scope_kind, + NEW.resolved_scope_account_id, NEW.account_coverage_fence, + NEW.account_coverage_generation, NEW.account_inventory_snapshot_revision + ) IS DISTINCT FROM ROW( + OLD.transition_id, OLD.tenant_id, OLD.playable_state_namespace_id, + OLD.character_id, OLD.expected_prior_binding_ref, + OLD.expected_prior_binding_generation, OLD.candidate_binding_ref, + OLD.candidate_binding_generation, OLD.candidate_account_index_fence, + OLD.issuer_reservation_id, OLD.created_at, + OLD.account_coverage_state, OLD.account_coverage_operation_id, + OLD.account_coverage_lifecycle, OLD.account_coverage_operation_fence, + OLD.account_admission_fence_kind, OLD.account_admission_fence, + OLD.historical_account_admission_fence_kind, + OLD.historical_account_admission_fence, OLD.resolved_scope_kind, + OLD.resolved_scope_account_id, OLD.account_coverage_fence, + OLD.account_coverage_generation, OLD.account_inventory_snapshot_revision + ) THEN + RAISE EXCEPTION 'First-NEW abort cannot change its transition, Account-control, or inventory source' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_first_new_abort_transition_source_immutable'; + END IF; + + IF NOT approved_first_new_abort + AND NEW.admission_orphan_cleanup_id IS DISTINCT FROM OLD.admission_orphan_cleanup_id THEN + RAISE EXCEPTION 'A lease-bound cleanup identity requires the exact first-NEW Account abort transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_abort_cleanup_identity'; + END IF; + + IF ROW( + NEW.admission_request_id, + NEW.admission_lease_id, + NEW.admission_lease_fence, + NEW.admission_lease_kind, + NEW.admission_lease_digest, + NEW.admission_lease_evidence, + NEW.admission_resume_episode_id, + NEW.admission_expected_old_binding_generation, + NEW.admission_lease_expires_at, + NEW.admission_target_namespace, + NEW.admission_target_tenant_slug, + NEW.admission_target_tenant_id, + NEW.admission_target_world_slug, + NEW.admission_target_world_display_name, + NEW.admission_target_realm_id, + NEW.admission_target_realm_slug, + NEW.admission_target_realm_display_name, + NEW.admission_target_game_session_tenant_id, + NEW.admission_target_game_instance_id, + NEW.admission_target_playable_state_namespace_id, + NEW.admission_target_playable_state_scope, + NEW.admission_target_canonical_game_instance_id, + NEW.admission_target_canonical_version_id, + NEW.admission_target_runtime_version_id, + NEW.admission_target_catalog_revision, + NEW.admission_target_pointer_version, + NEW.admission_target_pointer_snapshot_digest, + NEW.admission_target_active_world_epoch, + NEW.admission_target_initial_admission_request_id, + NEW.admission_target_initial_admission_request_digest, + NEW.admission_target_origin_kind, + NEW.admission_target_expected_prior_pointer_version, + NEW.admission_target_hold_id, + NEW.admission_target_hold_fence, + NEW.admission_target_hold_binding_digest, + NEW.admission_target_audit_event_id, + NEW.admission_target_owner_proof_digest, + NEW.admission_target_owner_proof_outcome, + NEW.admission_target_positive_durable_abort, + NEW.admission_target_terminal_at, + NEW.admission_target_character_creation_policy + ) IS DISTINCT FROM ROW( + OLD.admission_request_id, + OLD.admission_lease_id, + OLD.admission_lease_fence, + OLD.admission_lease_kind, + OLD.admission_lease_digest, + OLD.admission_lease_evidence, + OLD.admission_resume_episode_id, + OLD.admission_expected_old_binding_generation, + OLD.admission_lease_expires_at, + OLD.admission_target_namespace, + OLD.admission_target_tenant_slug, + OLD.admission_target_tenant_id, + OLD.admission_target_world_slug, + OLD.admission_target_world_display_name, + OLD.admission_target_realm_id, + OLD.admission_target_realm_slug, + OLD.admission_target_realm_display_name, + OLD.admission_target_game_session_tenant_id, + OLD.admission_target_game_instance_id, + OLD.admission_target_playable_state_namespace_id, + OLD.admission_target_playable_state_scope, + OLD.admission_target_canonical_game_instance_id, + OLD.admission_target_canonical_version_id, + OLD.admission_target_runtime_version_id, + OLD.admission_target_catalog_revision, + OLD.admission_target_pointer_version, + OLD.admission_target_pointer_snapshot_digest, + OLD.admission_target_active_world_epoch, + OLD.admission_target_initial_admission_request_id, + OLD.admission_target_initial_admission_request_digest, + OLD.admission_target_origin_kind, + OLD.admission_target_expected_prior_pointer_version, + OLD.admission_target_hold_id, + OLD.admission_target_hold_fence, + OLD.admission_target_hold_binding_digest, + OLD.admission_target_audit_event_id, + OLD.admission_target_owner_proof_digest, + OLD.admission_target_owner_proof_outcome, + OLD.admission_target_positive_durable_abort, + OLD.admission_target_terminal_at, + OLD.admission_target_character_creation_policy + ) THEN + RAISE EXCEPTION 'A lease-bound runtime fence decision is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_decision_immutable'; + END IF; + ELSIF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + IF OLD.status <> 'PREPARED' + OR OLD.admission_lease_id IS NOT NULL + OR OLD.admission_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from the exact PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + ELSE + RETURN NEW; + END IF; + + -- This SELECT is in the same transaction as markProvisional's transition UPDATE. Its row + -- lock serializes the decision with stop/replacement/deletion and is retained through commit. + SELECT runtime.* + INTO runtime_row + FROM game_instances runtime + JOIN game_session_canonical_instance_launch launch + ON launch.game_session_tenant_id = runtime.tenant_id + AND launch.game_instance_id = runtime.id + AND launch.game_instance_uuid = runtime.game_instance_uuid + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = NEW.candidate_binding_ref + AND candidate.tenant_id = launch.canonical_tenant_id + AND candidate.runtime_game_instance_id = runtime.id + AND candidate.game_instance_id = runtime.game_instance_uuid + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = launch.target_namespace + AND catalog.canonical_tenant_id = launch.canonical_tenant_id + AND catalog.realm_id = launch.canonical_realm_id + AND catalog.world_slug = launch.world_slug + AND catalog.playable_state_namespace_id = launch.playable_state_namespace_id + AND catalog.catalog_revision = NEW.admission_target_catalog_revision + WHERE runtime.tenant_id = NEW.admission_target_game_session_tenant_id + AND runtime.id = NEW.admission_target_game_instance_id + AND runtime.status = 'RUNNING' + AND runtime.game_instance_uuid = NEW.admission_target_canonical_game_instance_id + AND runtime.version_id = NEW.admission_target_runtime_version_id + AND runtime.game_template_id = launch.game_template_id + AND runtime.launch_descriptor_id = launch.launch_descriptor_id + AND runtime.release_bundle_id = launch.release_bundle_id + AND runtime.generation_config_revision = launch.generation_config_revision + AND runtime.version_state_epoch = launch.version_state_epoch + AND ( + ( + -- Preserve the original run-owned source exactly for its owner route. + runtime.run_owned_start_active_epoch = NEW.admission_target_active_world_epoch + AND runtime.run_owned_start_request_id = launch.control_plane_request_id + AND runtime.run_owned_start_published_release_bundle_ref = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef' + ) + OR ( + -- Human STARTING -> RUNNING rows retain their own immutable positive receipt and + -- original StartSession identity. The request/digest/release columns bind that + -- source identity; run-owned lifecycle epochs remain absent. + NEW.admission_target_owner_proof_outcome = 'COMMITTED' + AND NEW.admission_target_positive_durable_abort IS FALSE + AND runtime.run_owned_start_preparing_epoch IS NULL + AND runtime.run_owned_start_active_epoch IS NULL + AND EXISTS ( + SELECT 1 + FROM game_session_canonical_human_runtime_completion completion + JOIN game_session_canonical_initial_admission_attempt attempt + ON attempt.target_namespace = completion.target_namespace + AND attempt.initial_admission_request_id = completion.initial_admission_request_id + AND attempt.request_digest = completion.request_digest + AND attempt.canonical_tenant_id = completion.canonical_tenant_id + AND attempt.world_slug = completion.world_slug + AND attempt.realm_id = completion.realm_id + AND attempt.playable_state_namespace_id = completion.playable_state_namespace_id + AND attempt.playable_state_scope = completion.playable_state_scope + AND attempt.canonical_game_instance_id = completion.canonical_game_instance_id + AND attempt.canonical_version_id = completion.canonical_version_id + AND attempt.game_session_tenant_id = completion.game_session_tenant_id + AND attempt.game_instance_id = completion.game_instance_id + AND attempt.expected_catalog_revision = completion.expected_catalog_revision + AND attempt.origin_kind = completion.origin_kind + AND attempt.expected_prior_pointer_version IS NOT DISTINCT FROM + completion.expected_prior_pointer_version + AND attempt.active_lifecycle_epoch = completion.active_lifecycle_epoch + AND attempt.hold_id = completion.hold_id + AND attempt.hold_fence = completion.hold_fence + AND attempt.hold_binding_digest = completion.hold_binding_digest + AND attempt.status = 'COMMITTED' + AND attempt.pointer_id IS NOT NULL + AND attempt.pointer_version = NEW.admission_target_pointer_version + AND attempt.audit_event_id = NEW.admission_target_audit_event_id + AND attempt.commit_proof_digest = NEW.admission_target_owner_proof_digest + AND attempt.terminal_at = NEW.admission_target_terminal_at + JOIN game_session_start_session_operator_attempt original + ON original.target_namespace = completion.target_namespace + AND original.owner_attempt_id = completion.original_owner_attempt_id + AND original.owner_mutation_id = completion.original_owner_mutation_id + AND original.owner_fence = completion.original_owner_fence + AND original.canonical_tenant_id = completion.canonical_tenant_id + AND original.control_plane_request_id = launch.control_plane_request_id + AND original.post_authorization_execution_tuple = + completion.original_start_session_tuple + AND original.account_redemption_projection = + completion.account_redemption_projection + AND runtime.run_owned_start_request_id = original.control_plane_request_id + AND runtime.run_owned_start_request_digest = original.mutation_digest + AND runtime.run_owned_start_published_release_bundle_ref = + launch.complete_launch_binding_evidence -> 'descriptor' + ->> 'publishedReleaseBundleRef' + JOIN gameplay_admission_pointer pointer + ON pointer.id = attempt.pointer_id + AND pointer.representation_version = 3 + AND pointer.target_namespace = attempt.target_namespace + AND pointer.canonical_tenant_id = attempt.canonical_tenant_id + AND pointer.realm_id = attempt.realm_id + AND pointer.world_slug = attempt.world_slug + AND pointer.playable_state_namespace_id = attempt.playable_state_namespace_id + AND pointer.state_scope = attempt.playable_state_scope + AND pointer.canonical_game_instance_id = attempt.canonical_game_instance_id + AND pointer.canonical_version_id = attempt.canonical_version_id + AND pointer.runtime_version_id = attempt.runtime_version_id + AND pointer.tenant_id = attempt.game_session_tenant_id + AND pointer.game_instance_id = attempt.game_instance_id + AND pointer.pointer_version = attempt.pointer_version + AND pointer.catalog_revision = attempt.expected_catalog_revision + AND pointer.initial_admission_request_id = attempt.initial_admission_request_id + AND pointer.initial_admission_request_digest = attempt.request_digest + AND pointer.initial_admission_origin_kind = attempt.origin_kind + AND pointer.initial_admission_prior_pointer_version IS NOT DISTINCT FROM + attempt.expected_prior_pointer_version + AND pointer.initial_admission_active_epoch = attempt.active_lifecycle_epoch + AND pointer.initial_admission_hold_id = attempt.hold_id + AND pointer.initial_admission_hold_fence = attempt.hold_fence + AND pointer.initial_admission_hold_binding_digest = attempt.hold_binding_digest + AND pointer.admission_state = 'OPEN' + JOIN gameplay_admission_pointer_event event + ON event.id = attempt.audit_event_id + AND event.representation_version = 3 + AND event.target_namespace = attempt.target_namespace + AND event.canonical_tenant_id = attempt.canonical_tenant_id + AND event.realm_id = attempt.realm_id + AND event.world_slug = attempt.world_slug + AND event.playable_state_namespace_id = attempt.playable_state_namespace_id + AND event.state_scope = attempt.playable_state_scope + AND event.canonical_game_instance_id = attempt.canonical_game_instance_id + AND event.canonical_version_id = attempt.canonical_version_id + AND event.runtime_version_id = attempt.runtime_version_id + AND event.tenant_id = attempt.game_session_tenant_id + AND event.game_instance_id = attempt.game_instance_id + AND event.pointer_version = attempt.pointer_version + AND event.catalog_revision = attempt.expected_catalog_revision + AND event.initial_admission_request_id = attempt.initial_admission_request_id + AND event.control_plane_request_id = attempt.initial_admission_request_id + AND event.initial_admission_request_digest = attempt.request_digest + AND event.initial_admission_origin_kind = attempt.origin_kind + AND event.initial_admission_prior_pointer_version IS NOT DISTINCT FROM + attempt.expected_prior_pointer_version + AND event.initial_admission_active_epoch = attempt.active_lifecycle_epoch + AND event.initial_admission_hold_id = attempt.hold_id + AND event.initial_admission_hold_fence = attempt.hold_fence + AND event.initial_admission_hold_binding_digest = attempt.hold_binding_digest + AND event.admission_state = 'OPEN' + AND event.prepared_version_upgrade_id IS NULL + WHERE completion.target_namespace = NEW.admission_target_namespace + AND completion.initial_admission_request_id = + NEW.admission_target_initial_admission_request_id + AND completion.request_digest = + NEW.admission_target_initial_admission_request_digest + AND completion.canonical_tenant_id = NEW.admission_target_tenant_id + AND completion.world_slug = NEW.admission_target_world_slug + AND completion.realm_id = NEW.admission_target_realm_id + AND completion.playable_state_namespace_id = + NEW.admission_target_playable_state_namespace_id + AND completion.playable_state_scope = NEW.admission_target_playable_state_scope + AND completion.canonical_game_instance_id = + NEW.admission_target_canonical_game_instance_id + AND completion.canonical_version_id = NEW.admission_target_canonical_version_id + AND completion.active_lifecycle_epoch = NEW.admission_target_active_world_epoch + AND completion.expected_catalog_revision = NEW.admission_target_catalog_revision + AND completion.origin_kind = NEW.admission_target_origin_kind + AND completion.expected_prior_pointer_version IS NOT DISTINCT FROM + NEW.admission_target_expected_prior_pointer_version + AND completion.hold_id = NEW.admission_target_hold_id + AND completion.hold_fence = NEW.admission_target_hold_fence + AND completion.hold_binding_digest = NEW.admission_target_hold_binding_digest + AND completion.game_session_tenant_id = runtime.tenant_id + AND completion.game_instance_id = runtime.id + AND completion.game_session_tenant_id = NEW.admission_target_game_session_tenant_id + AND completion.game_instance_id = NEW.admission_target_game_instance_id + AND completion.control_plane_request_id = launch.control_plane_request_id + AND completion.captured_starting_row_version = launch.captured_starting_row_version + AND completion.completed_running_row_version <= runtime.row_version + AND completion.launch_descriptor_id = launch.launch_descriptor_id + AND completion.descriptor_request_digest = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' + AND completion.descriptor_result_digest = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' + AND completion.release_attestation_digest = + launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' + AND completion.world_lifecycle_state = 'ACTIVE' + AND pointer.target_namespace = NEW.admission_target_namespace + AND pointer.canonical_tenant_id = NEW.admission_target_tenant_id + AND pointer.realm_id = NEW.admission_target_realm_id + AND pointer.world_slug = NEW.admission_target_world_slug + AND pointer.world_display_name = catalog.source_world_display_name + AND pointer.realm_slug = NEW.admission_target_realm_slug + AND pointer.realm_display_name = catalog.realm_display_name + AND pointer.playable_state_namespace_id = + NEW.admission_target_playable_state_namespace_id + AND pointer.state_scope = NEW.admission_target_playable_state_scope + AND pointer.canonical_game_instance_id = + NEW.admission_target_canonical_game_instance_id + AND pointer.canonical_version_id = NEW.admission_target_canonical_version_id + AND pointer.runtime_version_id = NEW.admission_target_runtime_version_id + AND pointer.tenant_id = NEW.admission_target_game_session_tenant_id + AND pointer.game_instance_id = NEW.admission_target_game_instance_id + AND pointer.pointer_version = NEW.admission_target_pointer_version + AND pointer.catalog_revision = NEW.admission_target_catalog_revision + AND pointer.initial_admission_request_id = + NEW.admission_target_initial_admission_request_id + AND pointer.initial_admission_request_digest = + NEW.admission_target_initial_admission_request_digest + AND pointer.initial_admission_origin_kind = NEW.admission_target_origin_kind + AND pointer.initial_admission_prior_pointer_version IS NOT DISTINCT FROM + NEW.admission_target_expected_prior_pointer_version + AND pointer.initial_admission_active_epoch = NEW.admission_target_active_world_epoch + AND pointer.initial_admission_hold_id = NEW.admission_target_hold_id + AND pointer.initial_admission_hold_fence = NEW.admission_target_hold_fence + AND pointer.initial_admission_hold_binding_digest = + NEW.admission_target_hold_binding_digest + AND pointer.admission_state = 'OPEN' + AND pointer.visible = catalog.visible + AND pointer.public_production_realm = catalog.public_production + AND pointer.character_creation_policy = + NEW.admission_target_character_creation_policy + AND pointer.requires_character_selection IS NULL + AND pointer.last_updated_by = 'game-session-canonical-initial-admission' + AND pointer.last_update_reason = 'World-held initial admission' + ) + ) + ) + AND launch.target_namespace = NEW.admission_target_namespace + AND launch.canonical_tenant_id = NEW.admission_target_tenant_id + AND launch.canonical_realm_id = NEW.admission_target_realm_id + AND catalog.tenant_slug = NEW.admission_target_tenant_slug + AND catalog.world_slug = NEW.admission_target_world_slug + AND catalog.source_world_display_name = NEW.admission_target_world_display_name + AND catalog.realm_slug = NEW.admission_target_realm_slug + AND catalog.realm_display_name = NEW.admission_target_realm_display_name + AND launch.playable_state_namespace_id = NEW.admission_target_playable_state_namespace_id + AND launch.playable_state_scope = NEW.admission_target_playable_state_scope + AND launch.version_id = NEW.admission_target_runtime_version_id + AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.admission_target_canonical_version_id::text + AND catalog.visible + AND catalog.public_production + AND catalog.state_scope = 'SHARED' + AND launch.public_production + AND launch.playable_state_scope = 'SHARED' + AND launch.captured_starting_row_version <= runtime.row_version + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'targetNamespace' + = launch.target_namespace + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'controlPlaneRequestId' + = launch.control_plane_request_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'canonicalTenantId' + = launch.canonical_tenant_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'worldSlug' + = launch.world_slug + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'gameTemplateId' + = launch.game_template_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'launchDescriptorId' + = launch.launch_descriptor_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionId' + = launch.version_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'releaseBundleId' + = launch.release_bundle_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'generationConfigRevision' + = launch.generation_config_revision + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionStateEpoch' + = launch.version_state_epoch::text + FOR UPDATE OF runtime; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Lease-bound binding decision requires the exact current RUNNING launch row and candidate identity' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_exact_running_launch_required'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua index d78fdc7db9..4283d1b15d 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-read.lua @@ -34,6 +34,7 @@ local function validMeta() local tickId = redis.call('HGET', metaKey, 'current_tick_id') local state = redis.call('HGET', metaKey, 'current_tick_state') local terminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') + if not tickId then return false end if tickId == '-1' then return state == 'APPLIED' and not terminalAt end if not nonnegativeInt64(tickId) then return false end if state == 'STAGED' or state == 'RESOLVING' then return not terminalAt end diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua index 6b3daa8c1a..49f1609adb 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-renew.lua @@ -35,6 +35,7 @@ local function validMeta() local tickId = redis.call('HGET', metaKey, 'current_tick_id') local state = redis.call('HGET', metaKey, 'current_tick_state') local terminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') + if not tickId then return false end if tickId == '-1' then return state == 'APPLIED' and not terminalAt end if not nonnegativeInt64(tickId) then return false end if state == 'STAGED' or state == 'RESOLVING' then return not terminalAt end diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-session-binding-bridge.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-session-binding-bridge.lua index c232134c8f..4cab4477f6 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-session-binding-bridge.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-session-binding-bridge.lua @@ -65,6 +65,7 @@ if metaType ~= 'hash' local currentTickId = redis.call('HGET', metaKey, 'current_tick_id') local currentTickState = redis.call('HGET', metaKey, 'current_tick_state') local currentTickTerminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') +if not currentTickId then return 0 end if currentTickId == '-1' then if currentTickState ~= 'APPLIED' or currentTickTerminalAt then return 0 end elseif not nonnegativeInt64(currentTickId) then diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua index 2b09a01ef0..f489e49d7b 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-timeline-initialize.lua @@ -41,6 +41,7 @@ local function validTimelineMeta() local tickId = redis.call('HGET', metaKey, 'current_tick_id') local state = redis.call('HGET', metaKey, 'current_tick_state') local terminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') + if not tickId then return false end if tickId == '-1' then return state == 'APPLIED' and not terminalAt end if not nonnegativeInt64(tickId) then return false end if state == 'STAGED' or state == 'RESOLVING' then return not terminalAt end diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json index 30a6e0f0b5..70f2505e2a 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-read.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.region-lease-read.v1", "resourcePath": "redis/lua/game-session-region-lease-read.lua", - "sha256": "694631a5d389e6cf75cf108e2f81ee537e1b50e43fa40db8efe4249080c86ef0", + "sha256": "ef62557b212e9f19298f8066e6f4b499f2f7bebf09a05d9f79cfaa314add266e", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json index a1a306ce63..fd6591b131 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-renew.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.region-lease-renew.v1", "resourcePath": "redis/lua/game-session-region-lease-renew.lua", - "sha256": "b3bbab855f90f4431d2f358b92780907f0b7f67cb3bd673b49973f8b16276c19", + "sha256": "0e7cfd77259c1158e3b32d2b7e0eea1b863a532bada03fd77c7970486f3f2412", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-session-binding-bridge.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-session-binding-bridge.json index 5bcb861167..dc75e1e093 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-session-binding-bridge.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-session-binding-bridge.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.region-session-binding-bridge.v1", "resourcePath": "redis/lua/game-session-region-session-binding-bridge.lua", - "sha256": "29c1832217644dd22f79f84dc749d3b93ce2da440e60b95efe9a988dd2337009", + "sha256": "b65358cd964d6147eeba69cc401d2b2caa1a307fa0720490c8f56959ec91fb1a", "owner": "game-session-service", "principal": "gamesession_coord_app", "role": "COORDINATION", diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json index 9d2ba49029..c8134bc924 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-timeline-initialize.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.region-timeline-initialize.v1", "resourcePath": "redis/lua/game-session-region-timeline-initialize.lua", - "sha256": "93204b35a25e88883633d6a2e33ddc622d21ac69c82c6c7843251ced56138c3b", + "sha256": "2a403cd54d2033aff3d12403c0fd01821429bda39fcd8b164d3e8bdc98523325", "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/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java index 78851664f6..08cb96a863 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java @@ -24,7 +24,7 @@ /** PostgreSQL proof for V34.2 canonical gameplay integrity and runtime fence behavior. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") -class CanonicalGameplayDecisionRuntimeFenceIntegrationTest { +public class CanonicalGameplayDecisionRuntimeFenceIntegrationTest { private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); private static final String RAW_SHA256 = "a".repeat(64); @@ -445,6 +445,137 @@ void launchPreparationMustReferenceTheFullImmutableCatalogIdentity() { } } + @Test + void regionExecutorFenceForwardMigrationPreservesIssuedAndNullRequiredSources() { + String schema = "gs_executor_forward_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrateToRegionFencePredecessor(schema, dataSource); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var target = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); + long issuedFence = + dsl.fetchSingle("SELECT nextval('game_session_region_executor_fence_seq') AS fence") + .get("fence", Long.class); + assertThat(issuedFence).isPositive(); + seedRequiredRegionSource(dsl, target, Long.toString(issuedFence)); + seedRequiredRegionSource(dsl, target, null); + seedRequiredRegionSource(dsl, target, Long.toString(Long.MAX_VALUE)); + var before = requiredRegionSourceImages(dsl); + + migrate(schema, dataSource); + + assertThat(requiredRegionSourceImages(dsl)).isEqualTo(before); + assertThat(regionExecutorFenceType(dsl, schema)).isEqualTo("bigint"); + assertThat( + dsl.fetchSingle( + "SELECT count(*) AS count FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE status = 'ACKNOWLEDGED'") + .get("count", Long.class)) + .isZero(); + } finally { + dropSchema(schema); + } + } + + @Test + void regionExecutorFenceForwardMigrationRefusesFractionalOverflowAndNonfiniteRetainedSources() { + for (String invalid : java.util.List.of("1.5", "9223372036854775808", "NaN", "Infinity")) { + String schema = "gs_executor_refuse_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrateToRegionFencePredecessor(schema, dataSource); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var target = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); + seedRequiredRegionSource(dsl, target, invalid); + var before = requiredRegionSourceImages(dsl); + + assertThatThrownBy(() -> migrate(schema, dataSource)) + .as("retained executor fence %s", invalid) + .hasStackTraceContaining( + "Retained region executor fence must be an exact positive BIGINT"); + + assertThat(requiredRegionSourceImages(dsl)).isEqualTo(before); + assertThat(regionExecutorFenceType(dsl, schema)).isEqualTo("numeric"); + } finally { + dropSchema(schema); + } + } + } + + private static void migrateToRegionFencePredecessor( + String schema, DriverManagerDataSource dataSource) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target("1044.1") + .load() + .migrate(); + } + + private static java.util.List requiredRegionSourceImages(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(obligation)::text AS image" + + " FROM game_session_canonical_binding_region_bridge_obligation obligation" + + " ORDER BY transition_id") + .getValues("image", String.class); + } + + private static String regionExecutorFenceType(DSLContext dsl, String schema) { + return dsl.fetchSingle( + "SELECT data_type FROM information_schema.columns WHERE table_schema = ?" + + " AND table_name = 'game_session_canonical_binding_region_bridge_obligation'" + + " AND column_name = 'executor_fence'", + schema) + .get("data_type", String.class); + } + + /** + * Controlled REQUIRED staging rows prove retained storage only; none asserts bridge ACK + * authority. + */ + private static void seedRequiredRegionSource( + DSLContext dsl, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, + String fence) { + byte[] candidateRef = seedCandidateAndPreparedTransition(dsl, target, CandidateMismatch.NONE); + dsl.execute( + "INSERT INTO game_session_canonical_binding_region_bridge_obligation" + + " (transition_id, binding_ref, binding_generation, account_id, tenant_id," + + " game_instance_id, runtime_game_instance_id, session_id, region_id, region_epoch," + + " status, inventory_revision) SELECT transition_id, binding_ref, binding_generation," + + " account_id, tenant_id, game_instance_id, runtime_game_instance_id, session_id," + + " region_id, region_epoch, 'REQUIRED', inventory_revision" + + " FROM game_session_canonical_gameplay_binding_inventory WHERE binding_ref = ?", + candidateRef); + if (fence != null) { + dsl.execute( + "UPDATE game_session_canonical_binding_region_bridge_obligation SET" + + " bridge_operation_id = ?, bridge_preimage_state = 'ABSENT', runtime_entity_id = 1," + + " entity_projection_generation = 1, entity_projection_fence = 1," + + " entity_workload_namespace = 'controlled-storage-input', assignment_uuid = ?," + + " assignment_intent_digest = ?, entity_reference_digest = ?, world_source_digest = ?," + + " canonical_region_id = ?, world_lifecycle_epoch = 2, world_lifecycle_row_version = 0," + + " world_capture_id = ?, world_graph_sha256 = ?, world_preparation_input_digest = ?," + + " executor_fence = cast(? as numeric), lease_token_correlation = ?" + + " WHERE binding_ref = ?", + UUID.randomUUID(), + UUID.randomUUID(), + RAW_SHA256, + RAW_SHA256, + RAW_SHA256, + UUID.randomUUID(), + UUID.randomUUID(), + RAW_SHA256, + "sha256:" + RAW_SHA256, + fence, + RAW_SHA256, + candidateRef); + } + } + private static void migrate(String schema, DriverManagerDataSource dataSource) { Flyway.configure() .dataSource(dataSource) @@ -528,7 +659,17 @@ private static byte[] seedCandidateAndPreparedTransition( DSLContext dsl, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, CandidateMismatch mismatch) { - CanonicalPlayableTarget playableTarget = target.playableTarget(); + return seedCandidateAndPreparedTransition(dsl, target.playableTarget(), mismatch); + } + + public static byte[] seedCandidateAndPreparedTransition( + DSLContext dsl, CanonicalPlayableTarget target) { + return seedCandidateAndPreparedTransition(dsl, target, CandidateMismatch.NONE); + } + + private static byte[] seedCandidateAndPreparedTransition( + DSLContext dsl, CanonicalPlayableTarget target, CandidateMismatch mismatch) { + CanonicalPlayableTarget playableTarget = target; UUID candidateTenant = mismatch == CandidateMismatch.TENANT ? UUID.randomUUID() : target.canonicalTenantId(); long candidateRuntimeId = @@ -538,7 +679,7 @@ private static byte[] seedCandidateAndPreparedTransition( UUID candidateGameInstanceUuid = mismatch == CandidateMismatch.CANONICAL_GAME_INSTANCE_UUID ? UUID.randomUUID() - : target.gameInstanceUuid(); + : target.canonicalGameInstanceId(); UUID transitionId = UUID.randomUUID(); UUID accountId = UUID.randomUUID(); UUID characterId = UUID.randomUUID(); @@ -593,7 +734,11 @@ private static void markProvisional( DSLContext dsl, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget, byte[] candidateRef) { - CanonicalPlayableTarget target = runtimeTarget.playableTarget(); + markProvisional(dsl, runtimeTarget.playableTarget(), candidateRef); + } + + public static void markProvisional( + DSLContext dsl, CanonicalPlayableTarget target, byte[] candidateRef) { dsl.execute( "UPDATE game_session_canonical_binding_transition SET" + " status = 'PROVISIONAL', admission_request_id = ?, admission_lease_id = ?," diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java index 267f8f1697..bc22192ba2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java @@ -193,6 +193,8 @@ void wrongOrMissingMetaAndExpiredLeaseFailWithoutCreatingBinding() throws Except CanonicalGameplayRegionRedisKeys.sessionBinding( TENANT_ID, GAME_INSTANCE_ID, REGION_ID, actor.runtimeEntityId().value()); String meta = CanonicalGameplayRegionRedisKeys.meta(TENANT_ID, GAME_INSTANCE_ID, REGION_ID); + byte[] leaseKey = ascii(grant.key()); + byte[] leaseValue = redis.admin().get(leaseKey); redis.admin().del(ascii(meta)); assertThatThrownBy( @@ -206,6 +208,26 @@ void wrongOrMissingMetaAndExpiredLeaseFailWithoutCreatingBinding() throws Except .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); + seedMeta(redis.admin(), source, "1"); + assertThat(redis.admin().hdel(ascii(meta), ascii("current_tick_id"))).isEqualTo(1L); + assertThatThrownBy( + () -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Game Session region lease is unavailable") + .satisfies(failure -> assertThat(failure.getCause()).isNull()); + assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); + assertThat(redis.admin().hget(ascii(meta), ascii("current_tick_id"))).isNull(); + assertThat(redis.admin().hget(ascii(meta), ascii("region_epoch"))) + .containsExactly(ascii("1")); + assertThat(redis.admin().get(leaseKey)).containsExactly(leaseValue); + + seedMeta(redis.admin(), source, "1"); redis.admin().hset(ascii(meta), ascii("region_epoch"), ascii("2")); assertThatThrownBy( () -> @@ -218,7 +240,7 @@ void wrongOrMissingMetaAndExpiredLeaseFailWithoutCreatingBinding() throws Except .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); - redis.admin().hset(ascii(meta), ascii("region_epoch"), ascii("1")); + seedMeta(redis.admin(), source, "1"); redis.admin().pexpire(ascii(grant.key()), 0L); assertThatThrownBy( () -> diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 5e57d664ad..fd56868842 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -287,6 +287,48 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws .containsExactly(ascii(initialTimelineOperationId.toString())); assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("first_timeline_source_digest"))) .containsExactly(ascii(initialTimelineSourceDigest)); + + var preparation = statusRepository.findTimelinePreparation(qualifiedSource).orElseThrow(); + byte[] initialLeaseValue = redis.admin().get(redisKey); + assertThat(redis.admin().hdel(ascii(initialMetaKey), ascii("current_tick_id"))).isEqualTo(1L); + assertThatThrownBy( + () -> + redisOwner.initializeOrResumeTimeline( + preparation, + null, + Duration.ofSeconds(30), + new RuntimeIdentity( + "game-session-service", + "instance-a", + "localhost", + NOW, + "controlled-test", + "controlled-sha", + "controlled-image"))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Game Session region lease is unavailable") + .satisfies(failure -> assertThat(failure.getCause()).isNull()); + assertThatThrownBy( + () -> redisOwner.verifyInitializedTimeline(firstInstallation.grant, preparation)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Game Session region lease is unavailable") + .satisfies(failure -> assertThat(failure.getCause()).isNull()); + assertThat(redis.admin().hlen(ascii(initialMetaKey))).isEqualTo(4L); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_id"))).isNull(); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("region_epoch"))) + .containsExactly(ascii("1")); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("current_tick_state"))) + .containsExactly(ascii("APPLIED")); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("first_timeline_operation_id"))) + .containsExactly(ascii(initialTimelineOperationId.toString())); + assertThat(redis.admin().hget(ascii(initialMetaKey), ascii("first_timeline_source_digest"))) + .containsExactly(ascii(initialTimelineSourceDigest)); + assertThat(redis.admin().get(redisKey)).containsExactly(initialLeaseValue); + assertThat(redis.admin().pttl(redisKey)).isPositive(); + + redis.admin().hset(ascii(initialMetaKey), ascii("current_tick_id"), ascii("-1")); + redisOwner.verifyInitializedTimeline(firstInstallation.grant, preparation); + var currentIncarnation = incarnationSource.readCurrent( CanonicalGameplayRegionIncarnationSource.RegionScope.from(qualifiedSource)); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java index 7e59d85b5f..28addb8c4a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java @@ -127,6 +127,42 @@ void acceptsTickZeroAndRejectsExpiringTimelineMetadata() { } } + @Test + void missingCurrentTickIdMakesLeaseReadAndRenewStaleWithoutChangingLeaseOrMeta() { + try (RedisFixture redis = RedisFixture.open()) { + var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + var source = source(GAME_INSTANCE_ID_A); + seedMeta(redis.admin(), source); + var grant = owner.acquire(source, 7L, Duration.ofSeconds(30), identity("missing-tick-id")); + byte[] leaseKey = ascii(grant.key()); + byte[] metaKey = + ascii( + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())); + byte[] leaseValue = redis.admin().get(leaseKey); + assertThat(redis.admin().hdel(metaKey, ascii("current_tick_id"))).isEqualTo(1L); + long ttlBeforeRejectedRenewal = redis.admin().pttl(leaseKey); + + assertThatThrownBy(() -> owner.requireCurrent(grant)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Game Session region lease is unavailable") + .satisfies(failure -> assertThat(failure.getCause()).isNull()); + assertThatThrownBy(() -> owner.renew(grant, Duration.ofMinutes(2))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Game Session region lease is unavailable") + .satisfies(failure -> assertThat(failure.getCause()).isNull()); + + assertThat(redis.admin().hget(metaKey, ascii("current_tick_id"))).isNull(); + assertThat(redis.admin().hget(metaKey, ascii("region_epoch"))).containsExactly(ascii("7")); + assertThat(redis.admin().hget(metaKey, ascii("current_tick_state"))) + .containsExactly(ascii("APPLIED")); + assertThat(redis.admin().get(leaseKey)).containsExactly(leaseValue); + assertThat(redis.admin().pttl(leaseKey)) + .isPositive() + .isLessThanOrEqualTo(ttlBeforeRejectedRenewal); + } + } + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); private static final UUID GAME_INSTANCE_ID_A = UUID.fromString("22222222-2222-4222-8222-222222222222"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java index 44a621ccdc..8df2d2ceb4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java @@ -29,9 +29,12 @@ import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.repository.AccountInitialAdmissionProtectionBindingRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayDecisionRuntimeFenceIntegrationTest; import net.firedevops.firemud.gamesession.repository.CanonicalHumanRuntimeCompletionRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; @@ -698,6 +701,189 @@ void upgradedStartingHistoryCompletesWithoutBackfillOrPointerEffects() throws Ex } } + @Test + void healthyHumanRunningRepositorySaveRetainsCompletionForLaterLeaseBoundDecision() + throws Exception { + var harness = + CanonicalInitialAdmissionIntentRepositoryIntegrationTest.harness(postgres, "1044.1"); + try { + var prepared = prepareStarting(harness, "human-runtime-save-forward", 1701); + commitControlledHumanAdmission(harness, prepared); + var target = humanPlayableTarget(harness, prepared, false); + String originalCompletion = completionImage(harness); + var repository = new GameInstanceRepository(harness.dsl()); + var before = repository.findById(target.gameInstanceId()).orElseThrow(); + assertThat(before.getStatus()).isEqualTo("RUNNING"); + var saved = harness.transactions().execute(status -> repository.save(before)); + assertThat(saved).isNotNull(); + assertThat(saved.getStatus()).isEqualTo("RUNNING"); + assertThat(saved.getRowVersion()).isEqualTo(before.getRowVersion() + 1L); + assertThat(completionImage(harness)).isEqualTo(originalCompletion); + byte[] candidate = + CanonicalGameplayDecisionRuntimeFenceIntegrationTest.seedCandidateAndPreparedTransition( + harness.dsl(), target); + + // V1044 required equality with the immutable completion and refused this real owner save. + assertThatThrownBy( + () -> + CanonicalGameplayDecisionRuntimeFenceIntegrationTest.markProvisional( + harness.dsl(), target, candidate)) + .hasMessageContaining("exact current RUNNING launch row and candidate identity"); + harness.migrateLatest(); + + CanonicalGameplayDecisionRuntimeFenceIntegrationTest.markProvisional( + harness.dsl(), target, candidate); + + assertThat( + harness + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE candidate_binding_ref = ?", + candidate) + .get("status", String.class)) + .isEqualTo("PROVISIONAL"); + assertThat(completionImage(harness)).isEqualTo(originalCompletion); + assertThatThrownBy( + () -> + harness + .dsl() + .execute( + "UPDATE game_session_canonical_human_runtime_completion" + + " SET completed_running_row_version = completed_running_row_version + 1")) + .hasMessageContaining("Canonical Human runtime completion evidence is immutable"); + assertThat(completionImage(harness)).isEqualTo(originalCompletion); + } finally { + harness.close(); + } + } + + @Test + void humanCompletionStillRefusesStoppedMismatchedAndEarlierRuntimeDecisions() throws Exception { + for (String mismatch : List.of("STOPPED", "TARGET", "EARLIER_ROW_VERSION")) { + var harness = CanonicalInitialAdmissionIntentRepositoryIntegrationTest.harness(postgres); + try { + var prepared = prepareStarting(harness, "human-runtime-refusal", 1801); + commitControlledHumanAdmission(harness, prepared); + var target = humanPlayableTarget(harness, prepared, mismatch.equals("TARGET")); + String originalCompletion = completionImage(harness); + var repository = new GameInstanceRepository(harness.dsl()); + var running = repository.findById(target.gameInstanceId()).orElseThrow(); + harness.transactions().executeWithoutResult(status -> repository.save(running)); + if (mismatch.equals("STOPPED")) { + var stopping = repository.findById(target.gameInstanceId()).orElseThrow(); + stopping.setStatus("STOPPED"); + harness.transactions().executeWithoutResult(status -> repository.save(stopping)); + } else if (mismatch.equals("EARLIER_ROW_VERSION")) { + // Controlled corruption of only the row-version consequence proves the lower bound; + // it is not an owner mutation or substitute runtime-completion authority. + harness + .dsl() + .execute( + "UPDATE game_instances SET row_version = (SELECT completed_running_row_version - 1" + + " FROM game_session_canonical_human_runtime_completion) WHERE id = ?", + target.gameInstanceId()); + } + byte[] candidate = + CanonicalGameplayDecisionRuntimeFenceIntegrationTest.seedCandidateAndPreparedTransition( + harness.dsl(), target); + + assertThatThrownBy( + () -> + CanonicalGameplayDecisionRuntimeFenceIntegrationTest.markProvisional( + harness.dsl(), target, candidate)) + .as("Human runtime source mismatch %s", mismatch) + .hasMessageContaining("exact current RUNNING launch row and candidate identity"); + + assertThat( + harness + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE candidate_binding_ref = ?", + candidate) + .get("status", String.class)) + .isEqualTo("PREPARED"); + assertThat(completionImage(harness)).isEqualTo(originalCompletion); + } finally { + harness.close(); + } + } + } + + /** Actual GS owners consume controlled Account protection and World verifier output. */ + private static void commitControlledHumanAdmission( + CanonicalInitialAdmissionIntentRepositoryIntegrationTest.Harness harness, Prepared prepared) { + var result = + coordinator( + harness, + admissionRepository(harness), + ignored -> prepared.protection(), + ignored -> prepared.worldProof()) + .bind(prepared.request(), prepared.protection().request()); + assertThat(result.outcome()).isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + } + + private static String completionImage( + CanonicalInitialAdmissionIntentRepositoryIntegrationTest.Harness harness) { + return harness + .dsl() + .fetchSingle( + "SELECT to_jsonb(completion)::text AS image" + + " FROM game_session_canonical_human_runtime_completion completion") + .get("image", String.class); + } + + private static CanonicalPlayableTarget humanPlayableTarget( + CanonicalInitialAdmissionIntentRepositoryIntegrationTest.Harness harness, + Prepared prepared, + boolean mismatchedRuntimeVersion) { + var catalog = prepared.target().catalog(); + var snapshot = + admissionRepository(harness) + .readCurrentOpenSnapshotForRealm( + catalog.targetNamespace(), catalog.tenantId(), catalog.realmId()); + var proof = snapshot.ownerProof(); + long versionId = + new GameInstanceRepository(harness.dsl()) + .findById(prepared.target().gameInstanceId()) + .orElseThrow() + .getVersionId(); + return new CanonicalPlayableTarget( + catalog.targetNamespace(), + catalog.tenantSlug(), + catalog.tenantId(), + catalog.worldSlug(), + catalog.sourceIntakeReceipt().source().worldDisplayName(), + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + prepared.target().gameSessionTenantId(), + prepared.target().gameInstanceId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + proof.canonicalGameInstanceId(), + proof.canonicalVersionId(), + mismatchedRuntimeVersion ? versionId + 1 : versionId, + catalog.catalogRevision(), + proof.committedPointerVersion(), + snapshot.admissionPointerSnapshotDigest(), + proof.activeLifecycleEpoch(), + proof.initialAdmissionRequestId(), + proof.requestDigest(), + proof.originKind(), + proof.expectedPriorPointerVersion(), + proof.holdId(), + proof.holdFence(), + proof.holdBindingDigest(), + proof.auditEventId(), + proof.proofDigest(), + proof.outcome(), + proof.positiveDurableAbort(), + proof.terminalAt(), + catalog.characterCreationPolicy()); + } + private static Prepared prepareStarting( CanonicalInitialAdmissionIntentRepositoryIntegrationTest.Harness harness, String requestId, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java index 2c7996e2ac..7a89d32c64 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java @@ -213,7 +213,7 @@ void rejectsRegionResultWithSubstitutedActorRoomKeyOrMalformedPlacementDigest() } @Test - void rejectsOpenMalformedOrUnsupportedRequestsBeforeEitherRpc() throws Exception { + void rejectsOpenMalformedOrUnsupportedRequestsBeforeEveryRpc() throws Exception { var request = request(); var stub = mockStub(); var client = clientWithStub(stub); @@ -300,9 +300,12 @@ void rejectsOpenMalformedOrUnsupportedRequestsBeforeEitherRpc() throws Exception .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> client.readInitialPlayerLocation(candidate)) .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(candidate)) + .isInstanceOf(IllegalArgumentException.class); } verify(stub, never()).placeInitialPlayer(any()); verify(stub, never()).readInitialPlayerLocation(any()); + verify(stub, never()).readInitialPlayerLocationRegion(any()); } @Test @@ -385,7 +388,7 @@ void rejectsMismatchedIdentityScopeAssignmentAndMalformedResponses() throws Exce } @Test - void refusesAmbientSqlDuringInitializationAndBothRpcsAndRejectsUseAfterClose() throws Exception { + void refusesAmbientSqlDuringInitializationAndEveryRpcAndRejectsUseAfterClose() throws Exception { var request = request(); var initClient = newClient(); TransactionSynchronizationManager.initSynchronization(); @@ -411,16 +414,23 @@ void refusesAmbientSqlDuringInitializationAndBothRpcsAndRejectsUseAfterClose() t .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> client.readInitialPlayerLocation(request)) .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class); } finally { TransactionSynchronizationManager.clear(); } } verify(stub, never()).placeInitialPlayer(any()); verify(stub, never()).readInitialPlayerLocation(any()); + verify(stub, never()).readInitialPlayerLocationRegion(any()); client.close(); assertThatThrownBy(() -> client.placeInitialPlayer(request)) .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.readInitialPlayerLocation(request)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.readInitialPlayerLocationRegion(request)) + .isInstanceOf(IllegalStateException.class); } @Test From 8286e033d7709eda8b7f25d8c1db14b0543dccbd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:37:23 +1300 Subject: [PATCH 20/36] Fix fresh region grant reuse and deterministic World read refusals --- ...anonicalGameplayRegionLeaseRedisOwner.java | 7 +- .../lua/game-session-region-lease-acquire.lua | 1 + .../game-session-region-lease-acquire.json | 2 +- ...meplayRegionLeaseOwnerIntegrationTest.java | 96 +++++++++++++++++- ...yRegionLeaseRedisOwnerIntegrationTest.java | 9 +- ...GameplayRegionOwnerCompositionFixture.java | 49 ++++++++-- ...nonicalInitialPlayerLocationGrpcCodec.java | 11 +-- ...nicalInitialPlayerLocationGrpcService.java | 24 +++-- ...CanonicalInitialPlayerLocationService.java | 11 +-- ...tialPlayerLocationGrpcServiceMtlsTest.java | 97 +++++++++++++++++++ ...calInitialPlayerLocationGrpcCodecTest.java | 8 ++ 11 files changed, 277 insertions(+), 38 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index c28867a7fa..7d4961c64e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -106,6 +106,7 @@ LeaseGrant acquire( grant, ttlMillis, true); + if (outcome == 0L) throw unavailable(); if (outcome != 1L && outcome != 2L) { throw unavailable(new IllegalStateException("Region lease acquire outcome was " + outcome)); } @@ -179,7 +180,8 @@ void verifyInitializedTimeline( LeaseGrant grant, CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation) { requireNoAmbientTransaction(); - if (!grant.source.equals(preparation.source()) + if (!CanonicalGameplayRegionRuntimeStatusRepository.sameRegionSource( + grant.source, preparation.source()) || grant.regionEpoch != preparation.regionEpoch()) { throw unavailable(); } @@ -425,7 +427,8 @@ private static void requireGrantBackedStatus( || !status.regionId().equals(grant.source.regionId()) || status.lifecycleEpoch() != grant.source.lifecycleEpoch() || status.lifecycleRowVersion() != grant.source.lifecycleRowVersion() - || !status.lifecycleRequest().equals(grant.source.lifecycleRequest()) + || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( + status.lifecycleRequest(), grant.source.lifecycleRequest()) || !status.captureId().equals(grant.source.captureId()) || !status.graphSha256().equals(grant.source.graphSha256()) || !status.preparationInputDigest().equals(grant.source.preparationInputDigest()) diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua index 3c6851ac9b..f2dac7a3c5 100644 --- a/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-region-lease-acquire.lua @@ -35,6 +35,7 @@ local function validMeta() local tickId = redis.call('HGET', metaKey, 'current_tick_id') local state = redis.call('HGET', metaKey, 'current_tick_state') local terminalAt = redis.call('HGET', metaKey, 'current_tick_terminal_at_ms') + if not tickId then return false end if tickId == '-1' then return state == 'APPLIED' and not terminalAt end diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json index 34def97cdd..c00ea1e224 100644 --- a/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-region-lease-acquire.json @@ -1,7 +1,7 @@ { "scriptId": "game-session.region-lease-acquire.v1", "resourcePath": "redis/lua/game-session-region-lease-acquire.lua", - "sha256": "f13d30294753b98b715b9652749d6e25285a847f98d57677c3b193d1cc7aee93", + "sha256": "eca9c386644d6cb518db2849e2c4dcf8b19dd0fcd2ac53dd7ebe7a7152e543d8", "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/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index fd56868842..54649194da 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -623,7 +623,88 @@ void acknowledgedRegionBridgeSurvivesExpiredGrantReplacement() throws Exception } } - private static Server entityReferenceServer() throws Exception { + @Test + void laterPlacementAcquiresFreshGrantWithoutChangingInitialTimeline() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema schema = newTestSchema(); + try { + try (RedisFixture redis = RedisFixture.open()) { + redis.admin().flushdb(); + } + var target = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + schema.dataSource(), UUID.randomUUID(), "firemud"); + var first = WorldFixture.open(target); + var original = first.original.request(); + var secondRequest = + first.request().toBuilder() + .setPlacementOperationUuid(UUID.randomUUID().toString()) + .setCharacterUuid(UUID.randomUUID().toString()) + .setAssignmentUuid(UUID.randomUUID().toString()) + .build(); + var secondLifecycle = + new WorldCanonicalInstanceLifecycleEvidence.Request( + original.schemaVersion(), + UUID.nameUUIDFromBytes( + ("firemud-world-initial-location-lifecycle-read/v1/" + + secondRequest.getPlacementOperationUuid()) + .getBytes(StandardCharsets.US_ASCII)), + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.canonicalGameInstanceId(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.publicProduction(), + original.controlPlaneRequestId(), + original.canonicalVersionId(), + original.expectedDescriptorRequestDigest(), + original.expectedDescriptorResultDigest(), + original.expectedReleaseAttestationDigest()); + var secondEvidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(secondEvidence.request()).thenReturn(secondLifecycle); + when(secondEvidence.lifecycleStatus()) + .thenAnswer(ignored -> first.original.lifecycleStatus()); + when(secondEvidence.lifecycleEpoch()).thenAnswer(ignored -> first.original.lifecycleEpoch()); + when(secondEvidence.rowVersion()).thenAnswer(ignored -> first.original.rowVersion()); + when(secondEvidence.captureId()).thenAnswer(ignored -> first.original.captureId()); + when(secondEvidence.graphSha256()).thenAnswer(ignored -> first.original.graphSha256()); + when(secondEvidence.preparationInputDigest()) + .thenAnswer(ignored -> first.original.preparationInputDigest()); + when(secondEvidence.operationalRegionAssignments()) + .thenAnswer(ignored -> first.original.operationalRegionAssignments()); + var second = new WorldFixture(secondEvidence, secondRequest); + assertThat(secondLifecycle.readRequestId()).isNotEqualTo(original.readRequestId()); + try (var entity = EntityReferenceFixture.open(secondRequest.getCharacterUuid())) { + var result = + CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeTwoCandidates( + schema.dsl(), + REDIS.getHost(), + REDIS.getMappedPort(REDIS_PORT), + first.request(), + target.playableTarget(), + first.resolver(), + entity.client(), + new CanonicalGameplayRegionOwnerCompositionFixture.SecondBinding( + second.request(), + target.playableTarget(), + second.resolver(), + entity.client(), + true)); + assertThat(result.firstTimelineUnchanged()).isTrue(); + assertThat(result.initialMetaUnchanged()).isTrue(); + assertThat(result.first().exactLostReplyRetry()).isTrue(); + assertThat(result.second().exactLostReplyRetry()).isTrue(); + assertThat(result.second().executorFence()).isGreaterThan(result.first().executorFence()); + assertThat(result.foreignOwnerCapabilityRejectedWithoutStateChange()).isTrue(); + assertThat(result.expiredGrantRejectedWithoutStateChange()).isTrue(); + } + } finally { + dropSchema(schema.schema()); + } + } + + private static Server entityReferenceServer(String secondCharacterId) throws Exception { var service = new CanonicalPreseededActorAssignmentServiceGrpc .CanonicalPreseededActorAssignmentServiceImplBase() { @@ -636,7 +717,12 @@ public void readPreseededActorRuntimeReference( observer.onError(io.grpc.Status.PERMISSION_DENIED.asRuntimeException()); return; } - observer.onNext(entityResponse(request)); + // Controlled source maps distinct actors to distinct scoped runtime projections. + observer.onNext( + entityResponse(request).toBuilder() + .setRuntimeEntityId( + request.getCharacterUuid().equals(secondCharacterId) ? 92L : 91L) + .build()); observer.onCompleted(); } }; @@ -1175,7 +1261,11 @@ private EntityReferenceFixture( } static EntityReferenceFixture open() throws Exception { - Server server = entityReferenceServer(); + return open(null); + } + + static EntityReferenceFixture open(String secondCharacterId) throws Exception { + Server server = entityReferenceServer(secondCharacterId); ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); endpoints.setEntityManagementService("localhost:" + server.getPort()); var client = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java index 28addb8c4a..e00b83e6dc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java @@ -128,7 +128,7 @@ void acceptsTickZeroAndRejectsExpiringTimelineMetadata() { } @Test - void missingCurrentTickIdMakesLeaseReadAndRenewStaleWithoutChangingLeaseOrMeta() { + void missingCurrentTickIdMakesLeaseAcquireReadAndRenewStaleWithoutChangingLeaseOrMeta() { try (RedisFixture redis = RedisFixture.open()) { var owner = new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); var source = source(GAME_INSTANCE_ID_A); @@ -143,6 +143,13 @@ void missingCurrentTickIdMakesLeaseReadAndRenewStaleWithoutChangingLeaseOrMeta() assertThat(redis.admin().hdel(metaKey, ascii("current_tick_id"))).isEqualTo(1L); long ttlBeforeRejectedRenewal = redis.admin().pttl(leaseKey); + assertThatThrownBy( + () -> + owner.acquire( + source, 7L, Duration.ofMinutes(2), identity("after-missing-tick-id"))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Game Session region lease is unavailable") + .satisfies(failure -> assertThat(failure.getCause()).isNull()); assertThatThrownBy(() -> owner.requireCurrent(grant)) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical Game Session region lease is unavailable") diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index d43bd377dd..7fecf6124f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -669,11 +669,32 @@ private static TwoBindingProof installAndBridgeInternal( secondPrepared.bindingGeneration(), null, secondBinding.currentTarget())); - var secondInstallation = - bridgeOwner.installForTransition( - installation, secondTransitionId, secondBinding.worldRequest()); - var secondAcknowledgement = bridgeOwner.bridge(secondInstallation).obligation(); - var secondLostReplyRetry = bridgeOwner.bridge(secondInstallation).obligation(); + CanonicalGameplayRegionLeaseOwner.Installation secondInstallation; + CanonicalGameplayRegionBindingBridgeOwner secondBridgeOwner = bridgeOwner; + if (secondBinding.freshGrant()) { + // The first private handle is deliberately not reused. Expire only this test-owned lease. + redis.admin().pexpire(redisKey, 0L); + secondBridgeOwner = + CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( + dsl, + redis.ownerClient(), + scriptCatalog, + stableSource, + secondBinding.worldRegionResolver(), + secondBinding.entityReferenceClient(), + runtimeIdentity, + Duration.ofSeconds(30), + Clock.systemUTC()); + secondInstallation = + secondBridgeOwner.installForTransition( + secondTransitionId, secondBinding.worldRequest()); + } else { + secondInstallation = + bridgeOwner.installForTransition( + installation, secondTransitionId, secondBinding.worldRequest()); + } + var secondAcknowledgement = secondBridgeOwner.bridge(secondInstallation).obligation(); + var secondLostReplyRetry = secondBridgeOwner.bridge(secondInstallation).obligation(); requireMaterializedBridgeCaptured(dsl, secondTransitionId); if (!secondAcknowledgement.equals(secondLostReplyRetry) || secondAcknowledgement.status() @@ -730,7 +751,10 @@ private static TwoBindingProof installAndBridgeInternal( && secondStatus.regionEpoch() == 1L && secondStatus.lastCommittedTickId() == -1L; if (!unchangedTimeline - || !status.leaseTokenCorrelation().equals(secondStatus.leaseTokenCorrelation()) + || (secondBinding.freshGrant() + ? status.leaseTokenCorrelation().equals(secondStatus.leaseTokenCorrelation()) + || secondStatus.executorFence().compareTo(status.executorFence()) <= 0 + : !status.leaseTokenCorrelation().equals(secondStatus.leaseTokenCorrelation())) || redis.admin().pttl(redisKey) <= 0L || redis.admin().pttl(ascii(initialMetaKey)) != -1L) { throw new IllegalStateException( @@ -784,7 +808,7 @@ private static TwoBindingProof installAndBridgeInternal( snapshotRegionRedisState(redis, redisKey, initialMetaKey); boolean expiredGrantInstallationRejected; try { - bridgeOwner.installForTransition( + secondBridgeOwner.installForTransition( secondInstallation, secondTransitionId, secondBinding.worldRequest()); expiredGrantInstallationRejected = false; } catch (IllegalStateException expected) { @@ -1523,7 +1547,16 @@ public record SecondBinding( CanonicalInitialPlayerLocationRequest worldRequest, CanonicalPlayableTarget currentTarget, CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, - CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) {} + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + boolean freshGrant) { + public SecondBinding( + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient) { + this(worldRequest, currentTarget, worldRegionResolver, entityReferenceClient, false); + } + } public record TwoBindingProof( Proof first, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java index 9507565081..6fb9df206c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java @@ -195,7 +195,9 @@ static CanonicalInitialPlayerLocationRegionResponse toRegionResponse( || !"ACTIVE".equals(lifecycle.lifecycleStatus()) || lifecycle.lifecycleEpoch() != selection.activeLifecycleEpoch() || !lifecycleRequest.canonicalTenantId().equals(selection.canonicalTenantId()) - || !lifecycleRequest.readRequestId().equals(lifecycleReadRequestId(selection)) + || !lifecycleRequest + .readRequestId() + .equals(lifecycleReadRequestId(selection.placementOperationId())) || !lifecycleRequest.canonicalGameInstanceId().equals(selection.canonicalGameInstanceId()) || !lifecycleRequest.playableStateNamespaceId().equals(selection.playableStateNamespaceId()) || !lifecycleRequest.playableStateScope().equals(selection.playableStateScope()) @@ -233,9 +235,6 @@ static CanonicalInitialPlayerLocationRegionResponse toRegionResponse( .setObservedRuntimeRoomKey(result.runtimeRoomInstanceKey()) .setLifecycle(consequence) .build(); - if (response.getSerializedSize() > MAX_REGION_RESPONSE_BYTES) { - throw new IllegalStateException("World initial-location region response exceeds its bound"); - } return response; } @@ -251,9 +250,9 @@ private static UUID uuid(String value, String field) { } } - private static UUID lifecycleReadRequestId(Selection selection) { + static UUID lifecycleReadRequestId(UUID placementOperationId) { byte[] name = - ("firemud-world-initial-location-lifecycle-read/v1/" + selection.placementOperationId()) + ("firemud-world-initial-location-lifecycle-read/v1/" + placementOperationId) .getBytes(StandardCharsets.US_ASCII); return UUID.nameUUIDFromBytes(name); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java index 794feed246..c52527957b 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java @@ -152,15 +152,9 @@ public void readInitialPlayerLocationRegion( "A complete closed region-placement selector is required"); return; } - final Optional response; + final Optional retainedRegion; try { - response = - service - .readRegion(selection) - .map( - retained -> - CanonicalInitialPlayerLocationGrpcCodec.toRegionResponse( - selection, retained)); + retainedRegion = service.readRegion(selection); } catch (StatusRuntimeException rejected) { reportOwnerFailure( responseObserver, rejected, "World initial-player region read is unavailable"); @@ -179,6 +173,20 @@ public void readInitialPlayerLocationRegion( return; } + final Optional response; + try { + response = + retainedRegion.map( + retained -> + CanonicalInitialPlayerLocationGrpcCodec.toRegionResponse(selection, retained)); + } catch (IllegalStateException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Exact initial-placement region evidence is unavailable"); + return; + } + if (response.isEmpty()) { fail( responseObserver, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java index 888b8e93d3..e1b4df3b7e 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java @@ -9,7 +9,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; @@ -227,7 +226,8 @@ private WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( var release = association.completeLaunchBinding().evidence().releaseAttestation(); return new WorldCanonicalInstanceLifecycleEvidence.Request( WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, - lifecycleReadRequestId(selection.placementOperationId()), + CanonicalInitialPlayerLocationGrpcCodec.lifecycleReadRequestId( + selection.placementOperationId()), trustedNamespace, identity.canonicalTenantId(), identity.worldSlug(), @@ -409,13 +409,6 @@ private static String prefixedDigest(byte[] value) { } } - private static UUID lifecycleReadRequestId(UUID operationId) { - byte[] name = - ("firemud-world-initial-location-lifecycle-read/v1/" + operationId) - .getBytes(StandardCharsets.US_ASCII); - return UUID.nameUUIDFromBytes(name); - } - private static io.grpc.StatusRuntimeException failedPrecondition(String message) { return io.grpc.Status.FAILED_PRECONDITION.withDescription(message).asRuntimeException(); } diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java index 2d0b47b0ed..fbace8d715 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java @@ -64,6 +64,103 @@ void clearRequestContexts() { TransactionSynchronizationManager.clear(); } + @Test + void regionCodecMismatchAndSizeHaveDeterministicStatuses(@TempDir Path temporary) + throws Exception { + var pki = + LoopbackMtlsTestPki.create( + temporary, + "World region refusal proof CA", + identity("world", NAMESPACE, "world-management-service", true), + identity("game-session", NAMESPACE, "game-session-service", false)); + var owner = mock(CanonicalInitialPlayerLocationService.class); + var mismatched = controlledRegionResult(true); + var oversized = controlledRegionResult(false); + when(owner.readRegion(any())) + .thenReturn(Optional.of(mismatched), Optional.of(oversized)) + .thenThrow(new IllegalStateException("private owner failure")); + Server server = startServer(pki, owner); + try { + var channel = channel(pki, "game-session", server.getPort()); + try { + var stub = + CanonicalInitialPlayerLocationServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS); + for (var code : + List.of( + Status.Code.FAILED_PRECONDITION, + Status.Code.RESOURCE_EXHAUSTED, + Status.Code.UNAVAILABLE)) { + assertThatThrownBy(() -> stub.readInitialPlayerLocationRegion(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code); + assertThat(Status.fromThrowable(failure).getDescription()) + .doesNotContain("private"); + assertThat(Status.fromThrowable(failure).getCause()).isNull(); + }); + } + } finally { + stopChannel(channel); + } + } finally { + stopServer(server); + } + } + + /** Controlled owner-output corruption isolates mapping; it grants no World authority. */ + private static WorldCanonicalInitialPlayerLocationRepository.RegionResult controlledRegionResult( + boolean mismatchedRoom) { + var selection = CanonicalInitialPlayerLocationGrpcCodec.fromRegionRequest(request()); + var start = + new net.firedevops.firemud.common.world.RoomTemplateRef(TENANT, VERSION, UUID.randomUUID()); + var placement = + new Result( + Outcome.APPLIED, + null, + start, + 917L, + new byte[] {1}, + "sha256:" + "a".repeat(64), + new byte[] {2}, + "sha256:" + "b".repeat(64), + true); + var canonicalRegion = UUID.randomUUID(); + var operationalRegion = UUID.randomUUID(); + var request = + new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + CanonicalInitialPlayerLocationGrpcCodec.lifecycleReadRequestId(OPERATION), + NAMESPACE, + TENANT, + selection.worldSlug(), + GAME_INSTANCE, + PLAYABLE_NAMESPACE, + "SHARED", + true, + "controlled-region-read", + VERSION, + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64), + "sha256:" + "e".repeat(64)); + var lifecycle = + mock(net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.class); + when(lifecycle.request()).thenReturn(request); + when(lifecycle.startLocation()).thenReturn(start); + when(lifecycle.runtimeRoomInstanceId()).thenReturn(mismatchedRoom ? 918L : 917L); + when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycle.lifecycleEpoch()).thenReturn(selection.activeLifecycleEpoch()); + when(lifecycle.rowVersion()).thenReturn(1L); + when(lifecycle.captureId()).thenReturn(UUID.randomUUID()); + when(lifecycle.graphSha256()).thenReturn(mismatchedRoom ? "f".repeat(64) : "f".repeat(9000)); + when(lifecycle.preparationInputDigest()).thenReturn("sha256:" + "1".repeat(64)); + when(lifecycle.operationalRegionAssignments()) + .thenReturn(java.util.Map.of(canonicalRegion, operationalRegion)); + return new WorldCanonicalInitialPlayerLocationRepository.RegionResult( + placement, 4L, 917L, canonicalRegion, operationalRegion, lifecycle); + } + @Test void bothRpcMethodsRequireTheExactSameNamespaceGameSessionCertificate(@TempDir Path temporary) throws Exception { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java index c86d5ae6a6..5c6957a5a2 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java @@ -253,6 +253,14 @@ void emitsFreshRegionConsequenceOutsideTheImmutablePlacementResult() { .isLessThanOrEqualTo(CanonicalInitialPlayerLocationGrpcCodec.MAX_REGION_RESPONSE_BYTES); } + @Test + void lifecycleReadRequestIdRetainsPublishedNameUuidVector() { + assertThat( + CanonicalInitialPlayerLocationGrpcCodec.lifecycleReadRequestId( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"))) + .isEqualTo(uuid("5548bc3e-8d0e-3a87-9e7c-56a6647352c0")); + } + private static void assertInvalid(CanonicalInitialPlayerLocationRequest request) { assertThatThrownBy(() -> CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request)) .isInstanceOf(IllegalArgumentException.class); From 2f607019f5b13db5b8bf28e5571e26118c36a150 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 02:10:48 +1300 Subject: [PATCH 21/36] Reuse canonical lifecycle read ID in World composition proof --- ...essionPreparationOwnerCompositionCrossServiceTest.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) 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 ef62bde860..29a94bad1f 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 @@ -3439,7 +3439,7 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( var secondLifecycleRequest = new WorldCanonicalInstanceLifecycleEvidence.Request( originalLifecycleRequest.schemaVersion(), - worldInitialLocationLifecycleReadId(placementOperationId), + CanonicalInitialPlayerLocationGrpcCodec.lifecycleReadRequestId(placementOperationId), originalLifecycleRequest.targetNamespace(), originalLifecycleRequest.canonicalTenantId(), originalLifecycleRequest.worldSlug(), @@ -3561,12 +3561,6 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( secondRequest, currentTarget, secondWorldRegionResolver, entityReferenceClient); } - private static UUID worldInitialLocationLifecycleReadId(UUID placementOperationId) { - return UUID.nameUUIDFromBytes( - ("firemud-world-initial-location-lifecycle-read/v1/" + placementOperationId) - .getBytes(StandardCharsets.US_ASCII)); - } - private static AssignPreseededActorRequest toWire(PreseededActorAssignmentRequest request) { var target = request.expectedTarget(); return AssignPreseededActorRequest.newBuilder() From 0da087b37618e3f7fe8ff605469d8a8913ab5b88 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 05:19:04 +1300 Subject: [PATCH 22/36] fix: classify owner outages and prove fenced initialization cut --- .../game-session-service/runtime-and-data.md | 4 +- .../player-access-and-session.md | 4 + ...alPreseededActorAssignmentGrpcService.java | 15 ++- ...eseededActorAssignmentGrpcServiceTest.java | 62 +++++++++++- ...meplayRegionLeaseOwnerIntegrationTest.java | 97 +++++++++++++++++++ 5 files changed, 178 insertions(+), 4 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 09a2d44e75..168467e5ba 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -30,7 +30,7 @@ The sections below define the target-state runtime contract. Current implementat - Hidden same-type Game Session recovery within ADR 0013's qualifying conditions remains an implementation or proof gap; the target is to preserve the session through upstream rebind rather than require a player-visible re-`LOGIN` / re-`PLAY` cycle. - The live `startSession` path keeps the Game Session row and runtime projection `STARTING` until World confirms its fenced `PREPARING -> ACTIVE` transition, then records `RUNNING`; failures before an activation attempt use the existing pre-activation cleanup. Once activation may have been issued or committed, an activation error or ambiguous result, or a later local runtime-state save/finalization failure, retains both the runtime projection and local owner row as `STARTING`, and never calls stale-epoch `failPrepared` or deletes either record. A failure proven before any World termination request is issued may restore the prior `RUNNING` row and runtime state while the World remains `ACTIVE`; once a termination request may have been issued, an error or ambiguous result leaves the local row `STOPPING` and runtime projection absent. Confirmed World termination retries local `STOPPED` finalization and never restores `RUNNING`. Durable stable lifecycle-operation identity and lifecycle readback/reconciliation remain unimplemented, so these local fail-closed quarantines are not a replacement for the target durable lifecycle cleanup workflow. - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. -- The prepared, unregistered region owner consumes exact World initial-placement/currentness and lifecycle reads plus Entity’s authenticated runtime reference. It durably prepares a non-admitting initial timeline, conditionally installs complete same-slot initial Redis metadata and the actual region lease, installs the matching SQL executor fence, and records the first-NEW region bridge acknowledgement. The timeline begins at `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`); existing or reset state cannot be adopted as a new timeline. Original retries retain the preparation, source and lease evidence. The controlled authenticated actual-owner composition now has focused local proof; the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-initial-player-location-preparation) records its scope and remaining public qualification. Forward V1043 preserves the original timeline migration while aligning its binding-reference carrier with the existing 6,144-byte physical codec bound; the canonical three-UUID frame is 133 bytes and cannot fit the former 128-byte check. Forward V1044 makes the existing lease-bound runtime fence consume the exact retained Human completion, matching `COMMITTED` initial attempt, current `OPEN` pointer and audit under the existing runtime row lock. The original run-owned checks remain owner-specific; absence of both qualified sources is refused. This is manual owner preparation, not registered tick execution, final player binding or production admission. The [Redis owner contract](../../system-architecture-redis.md#key-naming-and-shard-discipline) remains authoritative for timeline and lease semantics. +- The prepared, unregistered region owner consumes exact World initial-placement/currentness and lifecycle reads plus Entity’s authenticated runtime reference. It durably prepares a non-admitting initial timeline, conditionally installs complete same-slot initial Redis metadata and the actual region lease, installs the matching SQL executor fence, and records the first-NEW region bridge acknowledgement. The timeline begins at `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`); existing or reset state cannot be adopted as a new timeline. Original retries retain the preparation, source and lease evidence. A committed `INITIALIZING` preparation whose Redis initialization never executes remains non-admitting and cannot automatically recover from absent keys; the scope must stay fenced pending the owning recovery process, as detailed below. The controlled authenticated actual-owner composition now has focused local proof; the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-initial-player-location-preparation) records its scope and remaining public qualification. Forward V1043 preserves the original timeline migration while aligning its binding-reference carrier with the existing 6,144-byte physical codec bound; the canonical three-UUID frame is 133 bytes and cannot fit the former 128-byte check. Forward V1044 makes the existing lease-bound runtime fence consume the exact retained Human completion, matching `COMMITTED` initial attempt, current `OPEN` pointer and audit under the existing runtime row lock. The original run-owned checks remain owner-specific; absence of both qualified sources is refused. This is manual owner preparation, not registered tick execution, final player binding or production admission. The [Redis owner contract](../../system-architecture-redis.md#key-naming-and-shard-discipline) remains authoritative for timeline and lease semantics. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). - The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. @@ -235,7 +235,7 @@ Tick coordination is region-scoped, not session-scoped. Tick queues, locks, time Session shutdown therefore cleans up session keys but does not implicitly delete region-level tick coordination keys. -Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. Once that permission is consumed, missing Redis metadata is ambiguous loss; the same-scope retry fails closed and cannot obtain a fresh create permission or rewrite the same-epoch baseline. No same-scope automated or operator repair is implemented, so this is a scope-local liveness limit. The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). +Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. If that SQL transition commits and the process stops before its Redis initialization call, the retained phase, operation and source remain, while both Redis metadata and lease can still be absent. A later attempt cannot distinguish never-executed initialization from lost metadata. It therefore fails closed without obtaining a fresh creation permission, acquiring a lease or rewriting the same-epoch baseline. This is a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for this cut. Retain and read the available preparation and incident evidence, keep the affected scope fenced, and escalate through the owning recovery process using the [current operator fallback](../../system-architecture-redis-reset-and-recovery.md#current-operator-fallback); SQL phase edits and raw Redis key surgery are not recovery authority. The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps), with focused first-NEW proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). ## Reconnection and Disconnect Handling diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index ba1c1036b1..ae8b2392aa 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -468,6 +468,10 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The ## Validation and Proof +The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. Preserve and read the retained preparation and incident evidence, keep the scope fenced, and escalate through the owning recovery process under the [current operator fallback](../../architecture/system-architecture-redis-reset-and-recovery.md#current-operator-fallback); neither SQL phase edits nor raw key surgery is a supported remedy. The [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md#tick-coordination-and-lease-ownership) records the local consequence. + +Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passes all 25 selected cases: 19 Entity runtime-reference/assignment boundary units, five native region-owner cases including this cut, and the inherited protected-admission concurrency case. Affected production and Game Session integration static checks, formatting and documentation pass; the aggregate fails only a test-observer capture warning in Entity. The test observer now captures immutable status-description and cause-presence observations for the same disclosure and terminal-callback assertions; focused recovery is recorded separately. This is bounded refusal proof and does not establish recovery or production activation. + The region-owner CLI correction gate passed 40 freshly executed tests across the World client and five native PostgreSQL/Redis suites. It verifies exact positive BIGINT executor-fence migration, refusal of fractional/overflow/nonfinite retained fences, a real healthy Human runtime repository save retaining its immutable completion as a lower bound, and stale refusal without writes for incomplete timeline metadata across lease read/renew, timeline initialize/verify and binding bridge. Malformed, ambient-transaction and closed-client guards cover all three World RPCs. Fresh jOOQ generation, migration-frontier validation, affected Checkstyle/SpotBugs, formatting and documentation checks also passed. This is focused manually composed proof; production registration, custody, activation and genuine external World authority remain outside this qualification. 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. 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 48ade7e6f9..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 @@ -23,6 +23,10 @@ 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 @@ -188,7 +192,16 @@ public void readPreseededActorRuntimeReference( final Optional stored; try { stored = Objects.requireNonNull(receiptService.readRuntimeReference(selector)); - } catch (RuntimeException unavailable) { + } 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; 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 24e60180de..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; @@ -585,6 +586,60 @@ void runtimeReferenceReturnsExactTypedProjectionOrOneBoundedFailure() { .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) { @@ -612,6 +667,8 @@ private static RuntimeObserver invokeRuntimeRead( private static final class RuntimeObserver implements StreamObserver { private ReadPreseededActorRuntimeReferenceResponse value; + private String errorDescription; + private boolean errorHasCause; private Status.Code errorCode; private int terminalCount; @@ -622,7 +679,10 @@ public void onNext(ReadPreseededActorRuntimeReferenceResponse next) { @Override public void onError(Throwable failure) { - errorCode = Status.fromThrowable(failure).getCode(); + Status status = Status.fromThrowable(failure); + errorDescription = status.getDescription(); + errorHasCause = failure.getCause() != null; + errorCode = status.getCode(); terminalCount++; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 54649194da..7a454bd288 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -532,6 +532,103 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws } } + @Test + void initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry() + throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try (RedisFixture redis = RedisFixture.open()) { + var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var redisOwner = + new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + // World, provisional binding and stable-incarnation authority are controlled inputs; + // PostgreSQL preparation, the Redis absence probe and subsequent region owner are actual. + WorldFixture world = WorldFixture.open(); + var bindingEvidence = provisionalEvidence(world.request()); + var bindingInventory = mock(CanonicalGameplayBindingInventoryRepository.class); + when(bindingInventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(bindingEvidence); + var incarnationSource = new ControlledStableIncarnationSource(); + var qualifiedSource = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(qualifiedSource)); + byte[] leaseKey = + ascii( + CanonicalGameplayRegionRedisKeys.lease( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId())); + byte[] metaKey = + ascii( + CanonicalGameplayRegionRedisKeys.meta( + qualifiedSource.tenantId(), + qualifiedSource.gameInstanceId(), + qualifiedSource.regionId())); + var preparation = + statusRepository.prepareInitialTimeline( + bindingEvidence, + world.request(), + world.resolver().resolve(world.request()), + qualifiedSource, + incarnation, + redisOwner.requireTimelineAbsent(qualifiedSource, incarnation), + NOW); + assertThat(preparation.phase()) + .isEqualTo( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.PREPARED); + assertThat(redis.admin().type(leaseKey)).isEqualTo("none"); + assertThat(redis.admin().type(metaKey)).isEqualTo("none"); + + // Model process loss after the SQL commit but before any INITIALIZE Redis call: + // discard the sole returned creation permit, without changing SQL or deleting keys. + assertThat(statusRepository.beginInitialTimeline(preparation, NOW)).isPresent(); + var initializing = statusRepository.findTimelinePreparation(qualifiedSource).orElseThrow(); + assertThat(initializing.phase()) + .isEqualTo( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INITIALIZING); + assertThat(initializing.operationId()).isEqualTo(preparation.operationId()); + assertThat(initializing.sourceDigest()).isEqualTo(preparation.sourceDigest()); + assertThat(initializing.source()).isEqualTo(qualifiedSource); + String retainedSqlImage = + testSchema + .dsl() + .fetch( + "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", + TRANSITION_ID) + .formatJSON(); + var retryOwner = + owner( + bindingInventory, + statusRepository, + redisOwner, + world, + "retry-after-initializing-commit", + incarnationSource); + for (int retry = 0; retry < 2; retry++) { + assertThat(redis.admin().type(leaseKey)).isEqualTo("none"); + assertThat(redis.admin().type(metaKey)).isEqualTo("none"); + assertThat(statusRepository.beginInitialTimeline(initializing, NOW)).isEmpty(); + assertThatThrownBy(() -> retryOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Canonical Game Session region lease is unavailable") + .satisfies(failure -> assertThat(failure.getCause()).isNull()); + assertThat(redis.admin().type(leaseKey)).isEqualTo("none"); + assertThat(redis.admin().type(metaKey)).isEqualTo("none"); + assertThat(statusRepository.find(qualifiedSource)).isEmpty(); + assertThat( + testSchema + .dsl() + .fetch( + "SELECT * FROM game_session_region_timeline_preparation WHERE transition_id = ?", + TRANSITION_ID) + .formatJSON()) + .isEqualTo(retainedSqlImage); + } + } finally { + dropSchema(testSchema.schema()); + } + } + @Test void accountMemberAcknowledgementAfterRegionBridgePreservesOriginalBridgeEvidence() throws Exception { From 09979e9dd16ea8284d0a1fbbd20f85b0972af46b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 06:34:52 +1300 Subject: [PATCH 23/36] refactor: share initial lifecycle read identity and clarify proof --- .../player-access-and-session.md | 2 +- ...rldCanonicalInstanceLifecycleEvidence.java | 9 +++++++++ ...anonicalInstanceLifecycleEvidenceTest.java | 20 +++++++++++++++++++ .../CanonicalInitialPlayerLocationClient.java | 14 +++++-------- ...meplayRegionLeaseOwnerIntegrationTest.java | 6 ++---- ...alInitialPlayerLocationClientMtlsTest.java | 6 ++---- ...onicalInitialPlayerLocationClientTest.java | 19 +++++++++--------- ...nonicalInitialPlayerLocationGrpcCodec.java | 12 +++-------- ...CanonicalInitialPlayerLocationService.java | 2 +- ...tialPlayerLocationGrpcServiceMtlsTest.java | 3 ++- ...ationOwnerCompositionCrossServiceTest.java | 3 ++- ...calInitialPlayerLocationGrpcCodecTest.java | 14 ++----------- 12 files changed, 59 insertions(+), 51 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index b6a119fb90..c7830a3da1 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -470,7 +470,7 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. Preserve and read the retained preparation and incident evidence, keep the scope fenced, and escalate through the owning recovery process under the [current operator fallback](../../architecture/system-architecture-redis-reset-and-recovery.md#current-operator-fallback); neither SQL phase edits nor raw key surgery is a supported remedy. The [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md#tick-coordination-and-lease-ownership) records the local consequence. -Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passes all 25 selected cases: 19 Entity runtime-reference/assignment boundary units, five native region-owner cases including this cut, and the inherited protected-admission concurrency case. Affected production and Game Session integration static checks, formatting and documentation pass; the aggregate fails only a test-observer capture warning in Entity. The test observer now captures immutable status-description and cause-presence observations for the same disclosure and terminal-callback assertions; focused recovery is recorded separately. This is bounded refusal proof and does not establish recovery or production activation. +Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passes all 25 selected cases: 19 Entity runtime-reference/assignment boundary units, five native region-owner cases including this cut, and the inherited protected-admission concurrency case. Affected production and Game Session integration static checks, formatting and documentation pass, but R890's aggregate fails Entity test SpotBugs on mutable failure capture and remains a failed aggregate. R891's attempted annotation correction fails compilation because the Entity test source set lacks the annotation dependency; no cases execute in that run. After replacing the capture with immutable status-description and cause-presence snapshots, R893 freshly passes 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 pass in R893. That focused recovery preserves the disclosure and terminal-callback assertions; it does not relabel R890 or R891 as successful aggregates. This is bounded refusal proof and does not establish recovery or production activation. The region-owner CLI correction gate passed 40 freshly executed tests across the World client and five native PostgreSQL/Redis suites. It verifies exact positive BIGINT executor-fence migration, refusal of fractional/overflow/nonfinite retained fences, a real healthy Human runtime repository save retaining its immutable completion as a lower bound, and stale refusal without writes for incomplete timeline metadata across lease read/renew, timeline initialize/verify and binding bridge. Malformed, ambient-transaction and closed-client guards cover all three World RPCs. Fresh jOOQ generation, migration-frontier validation, affected Checkstyle/SpotBugs, formatting and documentation checks also passed. This is focused manually composed proof; production registration, custody, activation and genuine external World authority remain outside this qualification. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java index cef01812bf..dc4e77bde3 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java @@ -117,6 +117,15 @@ public record WorldCanonicalInstanceLifecycleEvidence( requireExactBinding(request, launchBinding, startLocation, graphSha256); } + /** Stable lifecycle-read correlation for one initial placement; it grants no authority. */ + public static UUID initialLocationReadRequestId(UUID placementOperationId) { + requireNonNil(placementOperationId, "placementOperationId"); + byte[] name = + ("firemud-world-initial-location-lifecycle-read/v1/" + placementOperationId) + .getBytes(StandardCharsets.US_ASCII); + return UUID.nameUUIDFromBytes(name); + } + /** Returns an immutable ordered copy without exposing the retained map representation. */ @Override public Map operationalRegionAssignments() { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java index aa13f65fa8..1870730ea2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java @@ -19,6 +19,26 @@ class WorldCanonicalInstanceLifecycleEvidenceTest { private static final UUID NIL = new UUID(0L, 0L); + @Test + void initialLocationReadRequestIdRetainsPublishedNameUuidVector() { + assertThat( + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"))) + .isEqualTo(uuid("5548bc3e-8d0e-3a87-9e7c-56a6647352c0")); + } + + @Test + void initialLocationReadRequestIdRejectsAbsentAndNilPlacementIdentity() { + assertThatThrownBy( + () -> WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("placementOperationId must be a non-nil UUID"); + assertThatThrownBy( + () -> WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId(NIL)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("placementOperationId must be a non-nil UUID"); + } + @Test void completeOwnerCaptureAndExactRequestEchoRoundTrip() throws Exception { WorldCanonicalInstanceLifecycleEvidence expected = evidence(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java index ad468a6133..67b6e7bfd0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClient.java @@ -2,7 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -314,7 +313,11 @@ private void requireRegionResponse( var target = request.getExpectedTarget(); if (!lifecycleRequest.canonicalTenantId().toString().equals(target.getCanonicalTenantUuid()) || !namespace.equals(lifecycleRequest.targetNamespace()) - || !lifecycleRequest.readRequestId().equals(lifecycleReadRequestId(request)) + || !lifecycleRequest + .readRequestId() + .equals( + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( + UUID.fromString(request.getPlacementOperationUuid()))) || !lifecycleRequest.canonicalGameInstanceId().toString().equals(target.getGameInstanceId()) || !lifecycleRequest .playableStateNamespaceId() @@ -414,13 +417,6 @@ private static void requireResponseUuid(String value, String field) { } } - private static UUID lifecycleReadRequestId(CanonicalInitialPlayerLocationRequest request) { - byte[] name = - ("firemud-world-initial-location-lifecycle-read/v1/" + request.getPlacementOperationUuid()) - .getBytes(StandardCharsets.US_ASCII); - return UUID.nameUUIDFromBytes(name); - } - private static IllegalStateException invalidResponse(String message) { return new IllegalStateException( "World initial player location response is invalid: " + message); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 7a454bd288..c77998dcdf 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -742,10 +742,8 @@ void laterPlacementAcquiresFreshGrantWithoutChangingInitialTimeline() throws Exc var secondLifecycle = new WorldCanonicalInstanceLifecycleEvidence.Request( original.schemaVersion(), - UUID.nameUUIDFromBytes( - ("firemud-world-initial-location-lifecycle-read/v1/" - + secondRequest.getPlacementOperationUuid()) - .getBytes(StandardCharsets.US_ASCII)), + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( + UUID.fromString(secondRequest.getPlacementOperationUuid())), original.targetNamespace(), original.canonicalTenantId(), original.worldSlug(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientMtlsTest.java index 4165860186..6786fe5c9f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientMtlsTest.java @@ -234,10 +234,8 @@ private static CanonicalInitialPlayerLocationRegionResponse regionResponse( var lifecycleRequest = new WorldCanonicalInstanceLifecycleEvidence.Request( WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, - java.util.UUID.nameUUIDFromBytes( - ("firemud-world-initial-location-lifecycle-read/v1/" - + request.getPlacementOperationUuid()) - .getBytes(java.nio.charset.StandardCharsets.US_ASCII)), + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( + java.util.UUID.fromString(request.getPlacementOperationUuid())), NAMESPACE, java.util.UUID.fromString(target.getCanonicalTenantUuid()), target.getWorldSlug(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java index 7a89d32c64..c0a07288a7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java @@ -628,12 +628,20 @@ private static CanonicalInitialPlayerLocationResponse conflictResponse( private static CanonicalInitialPlayerLocationRegionResponse regionResponse( CanonicalInitialPlayerLocationRequest request) { - return regionResponse(request, NAMESPACE, lifecycleReadRequestId(request)); + return regionResponse( + request, + NAMESPACE, + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( + java.util.UUID.fromString(request.getPlacementOperationUuid()))); } private static CanonicalInitialPlayerLocationRegionResponse regionResponse( CanonicalInitialPlayerLocationRequest request, String lifecycleTargetNamespace) { - return regionResponse(request, lifecycleTargetNamespace, lifecycleReadRequestId(request)); + return regionResponse( + request, + lifecycleTargetNamespace, + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( + java.util.UUID.fromString(request.getPlacementOperationUuid()))); } private static CanonicalInitialPlayerLocationRegionResponse regionResponse( @@ -679,11 +687,4 @@ private static CanonicalInitialPlayerLocationRegionResponse regionResponse( .setLifecycle(lifecycle) .build(); } - - private static java.util.UUID lifecycleReadRequestId( - CanonicalInitialPlayerLocationRequest request) { - return java.util.UUID.nameUUIDFromBytes( - ("firemud-world-initial-location-lifecycle-read/v1/" + request.getPlacementOperationUuid()) - .getBytes(java.nio.charset.StandardCharsets.US_ASCII)); - } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java index 6fb9df206c..ba2c8c61c9 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodec.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.worldmanagement.tenant; import com.google.protobuf.ByteString; -import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; @@ -197,7 +196,9 @@ static CanonicalInitialPlayerLocationRegionResponse toRegionResponse( || !lifecycleRequest.canonicalTenantId().equals(selection.canonicalTenantId()) || !lifecycleRequest .readRequestId() - .equals(lifecycleReadRequestId(selection.placementOperationId())) + .equals( + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( + selection.placementOperationId())) || !lifecycleRequest.canonicalGameInstanceId().equals(selection.canonicalGameInstanceId()) || !lifecycleRequest.playableStateNamespaceId().equals(selection.playableStateNamespaceId()) || !lifecycleRequest.playableStateScope().equals(selection.playableStateScope()) @@ -250,13 +251,6 @@ private static UUID uuid(String value, String field) { } } - static UUID lifecycleReadRequestId(UUID placementOperationId) { - byte[] name = - ("firemud-world-initial-location-lifecycle-read/v1/" + placementOperationId) - .getBytes(StandardCharsets.US_ASCII); - return UUID.nameUUIDFromBytes(name); - } - private static String rawDigest(String value, String field) { if (!RAW_SHA256.matcher(value).matches()) { throw invalid(field + " must be a lowercase SHA-256 digest"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java index e1b4df3b7e..3043244bb6 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationService.java @@ -226,7 +226,7 @@ private WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( var release = association.completeLaunchBinding().evidence().releaseAttestation(); return new WorldCanonicalInstanceLifecycleEvidence.Request( WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, - CanonicalInitialPlayerLocationGrpcCodec.lifecycleReadRequestId( + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( selection.placementOperationId()), trustedNamespace, identity.canonicalTenantId(), diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java index fbace8d715..29e4a348e4 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java @@ -131,7 +131,8 @@ private static WorldCanonicalInitialPlayerLocationRepository.RegionResult contro var request = new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request( 1, - CanonicalInitialPlayerLocationGrpcCodec.lifecycleReadRequestId(OPERATION), + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + .initialLocationReadRequestId(OPERATION), NAMESPACE, TENANT, selection.worldSlug(), 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 29a94bad1f..7e4386f8f5 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 @@ -3439,7 +3439,8 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( var secondLifecycleRequest = new WorldCanonicalInstanceLifecycleEvidence.Request( originalLifecycleRequest.schemaVersion(), - CanonicalInitialPlayerLocationGrpcCodec.lifecycleReadRequestId(placementOperationId), + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( + placementOperationId), originalLifecycleRequest.targetNamespace(), originalLifecycleRequest.canonicalTenantId(), originalLifecycleRequest.worldSlug(), diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java index 5c6957a5a2..862c67e11a 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java @@ -205,10 +205,8 @@ void emitsFreshRegionConsequenceOutsideTheImmutablePlacementResult() { var lifecycleRequest = new WorldCanonicalInstanceLifecycleEvidence.Request( WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, - UUID.nameUUIDFromBytes( - ("firemud-world-initial-location-lifecycle-read/v1/" - + selection.placementOperationId()) - .getBytes(java.nio.charset.StandardCharsets.US_ASCII)), + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId( + selection.placementOperationId()), "world-management", TENANT, selection.worldSlug(), @@ -253,14 +251,6 @@ void emitsFreshRegionConsequenceOutsideTheImmutablePlacementResult() { .isLessThanOrEqualTo(CanonicalInitialPlayerLocationGrpcCodec.MAX_REGION_RESPONSE_BYTES); } - @Test - void lifecycleReadRequestIdRetainsPublishedNameUuidVector() { - assertThat( - CanonicalInitialPlayerLocationGrpcCodec.lifecycleReadRequestId( - uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"))) - .isEqualTo(uuid("5548bc3e-8d0e-3a87-9e7c-56a6647352c0")); - } - private static void assertInvalid(CanonicalInitialPlayerLocationRequest request) { assertThatThrownBy(() -> CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request)) .isInstanceOf(IllegalArgumentException.class); From e60a30e7e8db935db44bd010b81d7873fd6fcfe3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:30:22 +1300 Subject: [PATCH 24/36] test(gamesession): account for region executor type rewrite --- ...rtitionBuildRepositoryIntegrationTest.java | 76 ++++++++++++++++++- 1 file changed, 73 insertions(+), 3 deletions(-) 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 2797ef2a3f..44d423aa24 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 @@ -476,6 +476,9 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu List inventoryClockBefore = rowImages(testSchema.dsl(), "game_session_canonical_binding_inventory_clock"); List migrationHistoryBefore = migrationHistorySnapshot(testSchema.dsl()); + String retainedRegionBridgeTable = "game_session_canonical_binding_region_bridge_obligation"; + List regionBridgeRowsWithXminBefore = + rowImagesWithXmin(testSchema.dsl(), retainedRegionBridgeTable); List retainedSourceTables = List.of( "game_session_canonical_gameplay_binding_inventory", @@ -531,6 +534,44 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu .toList()) .isEqualTo(retainedRowsWithXminAt1031); + migrateThrough1044_1(testSchema); + List migrationHistoryBeforeExecutorFenceConversion = + migrationHistorySnapshot(testSchema.dsl()); + List regionBridgeRowsBeforeExecutorFenceConversion = + rowImages(testSchema.dsl(), retainedRegionBridgeTable); + assertThat(rowImagesWithXmin(testSchema.dsl(), retainedRegionBridgeTable)) + .containsExactlyElementsOf(regionBridgeRowsWithXminBefore); + + migrateThrough1044_2(testSchema); + List migrationHistoryAfterExecutorFenceConversion = + migrationHistorySnapshot(testSchema.dsl()); + assertThat(migrationHistoryAfterExecutorFenceConversion) + .hasSize(migrationHistoryBeforeExecutorFenceConversion.size() + 1); + assertThat( + migrationHistoryAfterExecutorFenceConversion.subList( + 0, migrationHistoryBeforeExecutorFenceConversion.size())) + .containsExactlyElementsOf(migrationHistoryBeforeExecutorFenceConversion); + assertThat( + testSchema + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1044.2'") + .get(0, String.class)) + .isEqualTo("V1044.2__region_executor_and_human_runtime_fence.sql"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT data_type FROM information_schema.columns" + + " WHERE table_schema = current_schema()" + + " AND table_name = 'game_session_canonical_binding_region_bridge_obligation'" + + " AND column_name = 'executor_fence'") + .get(0, String.class)) + .isEqualTo("bigint"); + assertThat(rowImages(testSchema.dsl(), retainedRegionBridgeTable)) + .containsExactlyElementsOf(regionBridgeRowsBeforeExecutorFenceConversion); + assertThat(rowImagesWithXmin(testSchema.dsl(), retainedRegionBridgeTable)) + .isNotEqualTo(regionBridgeRowsWithXminBefore); + migrateRemaining(testSchema); List migrationHistoryAfterCurrent = migrationHistorySnapshot(testSchema.dsl()); assertThat(migrationHistoryAfterCurrent.subList(0, migrationHistoryAfter1032.size())) @@ -687,9 +728,14 @@ void populatedPendingIntentRetainsCompleteCohortAndBothCoverageTuplesAcrossConcu assertThat(migrationHistoryAfter).containsExactlyElementsOf(migrationHistoryAfterCurrent); assertThat( retainedSourceTables.stream() + .filter(table -> !table.equals(retainedRegionBridgeTable)) .map(table -> rowImagesWithXmin(testSchema.dsl(), table)) .toList()) - .isEqualTo(retainedRowsWithXminBefore); + .containsExactlyElementsOf( + retainedSourceTables.stream() + .filter(table -> !table.equals(retainedRegionBridgeTable)) + .map(table -> retainedRowsWithXminBefore.get(retainedSourceTables.indexOf(table))) + .toList()); } finally { executor.shutdownNow(); dropSchema(testSchema.schema()); @@ -2193,6 +2239,30 @@ private static void migrateThrough1038(TestSchema testSchema) { .migrate(); } + private static void migrateThrough1044_1(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1044.1")) + .load() + .migrate(); + } + + private static void migrateThrough1044_2(TestSchema testSchema) { + Flyway.configure() + .dataSource(testSchema.dataSource()) + .schemas(testSchema.schema()) + .defaultSchema(testSchema.schema()) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("1044.2")) + .load() + .migrate(); + } + private static void migrateRemaining(TestSchema testSchema) { Flyway.configure() .dataSource(testSchema.dataSource()) @@ -2396,8 +2466,8 @@ private static DriverManagerDataSource dataSource(String schema) { } private static String retainedPreBridgeRegionImage(DSLContext dsl) { - // This populated V1030 fixture retains its original columns and physical xmin. A later - // nullable schema extension changes to_jsonb's field set without changing those values. + // Keep the populated V1030 fixture's original source columns comparable across nullable + // schema extensions; the explicit V1044.2 type conversion separately accounts for xmin. String originalFields = "ARRAY['transition_id', 'binding_ref', 'account_id', 'tenant_id', 'game_instance_id'," + " 'runtime_game_instance_id', 'session_id', 'binding_generation', 'region_id'," From ec666c760dff5cd8a9df61cff5a5f7cc26607950 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:04:38 +1300 Subject: [PATCH 25/36] refactor: share region runtime lock and proof fixtures --- .../game-session-service/operations.md | 2 +- .../gameplay-rules-entities-and-effects.md | 2 +- ...GameplayRegionRuntimeStatusRepository.java | 3 +- ...calGameplayBindingRuntimeTestFixtures.java | 140 ++++++++++++++++++ ...ayDecisionRuntimeFenceIntegrationTest.java | 132 +---------------- ...tionRepositoryPostgresIntegrationTest.java | 13 +- 6 files changed, 157 insertions(+), 135 deletions(-) diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index a2a13a1aa4..2fbdab3c5d 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -42,7 +42,7 @@ Before deploying the new Game Session admission validation, Automation must alre - Prometheus scrapes metrics from `/actuator/prometheus`. - Target state: logs, traces, and control-plane reads expose the active exact `{scriptPatchVersion, scriptPinEpoch}` execution fence so operators can identify the hotfix revision and selection epoch during incident triage without adding either raw value as ordinary high-cardinality metric labels. Current coverage is summarized in [Implementation Status](#implementation-status). -For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata is inconclusive loss. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. No same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). +For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata cannot distinguish never-executed initialization from metadata loss. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. No same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). ## Scaling and Region Rebalancing diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index c52efd2660..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 @@ -263,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/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index 35405cfa88..7fe28b97dc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -699,8 +699,7 @@ CanonicalGameplayRegionRuntimeStatus installOwner( return dsl.transactionResult( configuration -> { DSLContext transaction = DSL.using(configuration); - String scopeLockKey = "game-session-region-owner-install:v1:" + expectedTag; - transaction.fetch("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", scopeLockKey); + lockRegionScope(transaction, expectedTag); Record currentRow = transaction.fetchOne( "SELECT * FROM " diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index 3674a45168..d77573f681 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -1,11 +1,14 @@ package net.firedevops.firemud.gamesession.repository; import integration.net.firedevops.firemud.gamesession.repository.CanonicalHumanPublicationOwnerTestFixtures; +import java.nio.charset.StandardCharsets; +import java.sql.Timestamp; import java.time.Instant; import java.util.UUID; import javax.sql.DataSource; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; @@ -26,6 +29,8 @@ * Shared PostgreSQL fixtures for lease-bound binding tests that require a current launch target. * The source, policy, catalog, pin, and Starting records are written by their actual GS owners; * upstream producer inputs remain controlled test evidence and do not establish Account admission. + * Candidate, transition, and provisional lease helpers write controlled SQL inputs for downstream + * guards; they do not invoke gameplay binding or Account lease owners. */ public final class CanonicalGameplayBindingRuntimeTestFixtures { private static final String SHA256 = "sha256:" + "a".repeat(64); @@ -295,6 +300,141 @@ public static RuntimeTarget seedRunningLaunch( bundleRef); } + /** + * Writes controlled candidate and PREPARED transition inputs for downstream runtime-fence tests. + * These SQL inputs are not gameplay admission or Account lease-owner evidence. + */ + public static byte[] seedCandidateAndPreparedTransition( + DSLContext dsl, CanonicalPlayableTarget target) { + return seedCandidateAndPreparedTransition( + dsl, + target, + target.canonicalTenantId(), + target.gameInstanceId(), + target.canonicalGameInstanceId()); + } + + /** Allows the runtime-fence test to supply explicit candidate identity mismatches. */ + static byte[] seedCandidateAndPreparedTransition( + DSLContext dsl, + CanonicalPlayableTarget target, + UUID candidateTenant, + long candidateRuntimeId, + UUID candidateGameInstanceUuid) { + UUID transitionId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID characterId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + String issuerId = GameSessionAccountDelegationProfile.ISSUER; + UUID accountIndexFence = UUID.randomUUID(); + UUID issuerReservationId = UUID.randomUUID(); + byte[] candidateRef = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8); + + dsl.execute( + "INSERT INTO game_session_canonical_gameplay_binding_inventory" + + " (binding_ref, account_id, tenant_id, playable_state_namespace_id, character_id," + + " playable_state_scope, game_instance_id, runtime_game_instance_id, session_id," + + " binding_generation, region_id, region_epoch, issuer_id, issuer_auth_generation," + + " issuer_index_layout_version, issuer_index_partition_count," + + " issuer_index_partition_capacity, issuer_partition_id, account_index_fence," + + " issuer_reservation_id, transition_id, lifecycle, account_index_state," + + " issuer_index_state, inventory_revision)" + + " VALUES (?, ?, ?, ?, ?, 'SHARED', ?, ?, ?, 1, ?, 12, ?, 1, 1, 1, 1, 0, ?, ?, ?," + + " 'CANDIDATE_PREPARED', 'REPAIR_REQUIRED', 'REPAIR_REQUIRED', 1)", + candidateRef, + accountId, + candidateTenant, + target.playableStateNamespaceId(), + characterId, + candidateGameInstanceUuid, + candidateRuntimeId, + UUID.randomUUID().toString(), + regionId, + issuerId, + accountIndexFence, + issuerReservationId, + transitionId); + dsl.execute( + "INSERT INTO game_session_canonical_binding_transition" + + " (transition_id, tenant_id, playable_state_namespace_id, character_id," + + " expected_prior_binding_ref, expected_prior_binding_generation, candidate_binding_ref," + + " candidate_binding_generation, candidate_account_index_fence, issuer_reservation_id," + + " status, inventory_revision)" + + " VALUES (?, ?, ?, ?, NULL, NULL, ?, 1, ?, ?, 'PREPARED', 1)", + transitionId, + target.canonicalTenantId(), + target.playableStateNamespaceId(), + characterId, + candidateRef, + accountIndexFence, + issuerReservationId); + return candidateRef; + } + + /** + * Writes controlled provisional lease inputs so database guards can evaluate the supplied target. + * This SQL setup does not acquire an Account lease or establish actual admission authority. + */ + public static void markProvisional( + DSLContext dsl, CanonicalPlayableTarget target, byte[] candidateRef) { + dsl.execute( + "UPDATE game_session_canonical_binding_transition SET" + + " status = 'PROVISIONAL', admission_request_id = ?, admission_lease_id = ?," + + " admission_lease_fence = 1, admission_lease_kind = 'NEW_BINDING'," + + " admission_lease_digest = ?, admission_lease_evidence = '{}'," + + " admission_lease_expires_at = 9999999999999," + + " admission_target_namespace = ?, admission_target_tenant_slug = ?," + + " admission_target_tenant_id = ?, admission_target_world_slug = ?," + + " admission_target_world_display_name = ?, admission_target_realm_id = ?," + + " admission_target_realm_slug = ?, admission_target_realm_display_name = ?," + + " admission_target_game_session_tenant_id = ?, admission_target_game_instance_id = ?," + + " admission_target_playable_state_namespace_id = ?, admission_target_playable_state_scope = ?," + + " admission_target_canonical_game_instance_id = ?, admission_target_canonical_version_id = ?," + + " admission_target_runtime_version_id = ?, admission_target_catalog_revision = ?," + + " admission_target_pointer_version = ?, admission_target_pointer_snapshot_digest = ?," + + " admission_target_active_world_epoch = ?, admission_target_initial_admission_request_id = ?," + + " admission_target_initial_admission_request_digest = ?," + + " admission_target_origin_kind = 'NO_PRIOR_POINTER'," + + " admission_target_hold_id = ?, admission_target_hold_fence = ?," + + " admission_target_hold_binding_digest = ?, admission_target_audit_event_id = ?," + + " admission_target_owner_proof_digest = ?, admission_target_owner_proof_outcome = 'COMMITTED'," + + " admission_target_positive_durable_abort = FALSE, admission_target_terminal_at = ?," + + " admission_target_character_creation_policy = ?" + + " WHERE candidate_binding_ref = ?", + UUID.randomUUID(), + UUID.randomUUID(), + RAW_SHA256, + target.targetNamespace(), + target.tenantSlug(), + target.canonicalTenantId(), + target.worldSlug(), + target.worldDisplayName(), + target.realmId(), + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.canonicalVersionId(), + target.runtimeVersionId(), + target.catalogRevision(), + target.pointerVersion(), + target.admissionPointerSnapshotDigest(), + target.activeWorldEpoch(), + target.initialAdmissionRequestId(), + target.initialAdmissionRequestDigest(), + target.holdId(), + target.holdFence(), + target.holdBindingDigest(), + target.auditEventId(), + target.ownerProofDigest(), + Timestamp.from(target.ownerProofTerminalAt()), + target.characterCreationPolicy(), + candidateRef); + } + public record RuntimeTarget( String targetNamespace, String tenantSlug, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java index 08cb96a863..491d590a1e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java @@ -3,13 +3,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.sql.DriverManager; -import java.sql.Timestamp; import java.util.UUID; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -24,7 +20,7 @@ /** PostgreSQL proof for V34.2 canonical gameplay integrity and runtime fence behavior. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") -public class CanonicalGameplayDecisionRuntimeFenceIntegrationTest { +class CanonicalGameplayDecisionRuntimeFenceIntegrationTest { private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); private static final String RAW_SHA256 = "a".repeat(64); @@ -659,17 +655,6 @@ private static byte[] seedCandidateAndPreparedTransition( DSLContext dsl, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, CandidateMismatch mismatch) { - return seedCandidateAndPreparedTransition(dsl, target.playableTarget(), mismatch); - } - - public static byte[] seedCandidateAndPreparedTransition( - DSLContext dsl, CanonicalPlayableTarget target) { - return seedCandidateAndPreparedTransition(dsl, target, CandidateMismatch.NONE); - } - - private static byte[] seedCandidateAndPreparedTransition( - DSLContext dsl, CanonicalPlayableTarget target, CandidateMismatch mismatch) { - CanonicalPlayableTarget playableTarget = target; UUID candidateTenant = mismatch == CandidateMismatch.TENANT ? UUID.randomUUID() : target.canonicalTenantId(); long candidateRuntimeId = @@ -679,122 +664,21 @@ private static byte[] seedCandidateAndPreparedTransition( UUID candidateGameInstanceUuid = mismatch == CandidateMismatch.CANONICAL_GAME_INSTANCE_UUID ? UUID.randomUUID() - : target.canonicalGameInstanceId(); - UUID transitionId = UUID.randomUUID(); - UUID accountId = UUID.randomUUID(); - UUID characterId = UUID.randomUUID(); - UUID regionId = UUID.randomUUID(); - String issuerId = GameSessionAccountDelegationProfile.ISSUER; - UUID accountIndexFence = UUID.randomUUID(); - UUID issuerReservationId = UUID.randomUUID(); - byte[] candidateRef = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8); - - dsl.execute( - "INSERT INTO game_session_canonical_gameplay_binding_inventory" - + " (binding_ref, account_id, tenant_id, playable_state_namespace_id, character_id," - + " playable_state_scope, game_instance_id, runtime_game_instance_id, session_id," - + " binding_generation, region_id, region_epoch, issuer_id, issuer_auth_generation," - + " issuer_index_layout_version, issuer_index_partition_count," - + " issuer_index_partition_capacity, issuer_partition_id, account_index_fence," - + " issuer_reservation_id, transition_id, lifecycle, account_index_state," - + " issuer_index_state, inventory_revision)" - + " VALUES (?, ?, ?, ?, ?, 'SHARED', ?, ?, ?, 1, ?, 12, ?, 1, 1, 1, 1, 0, ?, ?, ?," - + " 'CANDIDATE_PREPARED', 'REPAIR_REQUIRED', 'REPAIR_REQUIRED', 1)", - candidateRef, - accountId, + : target.gameInstanceUuid(); + return CanonicalGameplayBindingRuntimeTestFixtures.seedCandidateAndPreparedTransition( + dsl, + target.playableTarget(), candidateTenant, - playableTarget.playableStateNamespaceId(), - characterId, - candidateGameInstanceUuid, candidateRuntimeId, - UUID.randomUUID().toString(), - regionId, - issuerId, - accountIndexFence, - issuerReservationId, - transitionId); - dsl.execute( - "INSERT INTO game_session_canonical_binding_transition" - + " (transition_id, tenant_id, playable_state_namespace_id, character_id," - + " expected_prior_binding_ref, expected_prior_binding_generation, candidate_binding_ref," - + " candidate_binding_generation, candidate_account_index_fence, issuer_reservation_id," - + " status, inventory_revision)" - + " VALUES (?, ?, ?, ?, NULL, NULL, ?, 1, ?, ?, 'PREPARED', 1)", - transitionId, - target.canonicalTenantId(), - playableTarget.playableStateNamespaceId(), - characterId, - candidateRef, - accountIndexFence, - issuerReservationId); - return candidateRef; + candidateGameInstanceUuid); } private static void markProvisional( DSLContext dsl, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget, byte[] candidateRef) { - markProvisional(dsl, runtimeTarget.playableTarget(), candidateRef); - } - - public static void markProvisional( - DSLContext dsl, CanonicalPlayableTarget target, byte[] candidateRef) { - dsl.execute( - "UPDATE game_session_canonical_binding_transition SET" - + " status = 'PROVISIONAL', admission_request_id = ?, admission_lease_id = ?," - + " admission_lease_fence = 1, admission_lease_kind = 'NEW_BINDING'," - + " admission_lease_digest = ?, admission_lease_evidence = '{}'," - + " admission_lease_expires_at = 9999999999999," - + " admission_target_namespace = ?, admission_target_tenant_slug = ?," - + " admission_target_tenant_id = ?, admission_target_world_slug = ?," - + " admission_target_world_display_name = ?, admission_target_realm_id = ?," - + " admission_target_realm_slug = ?, admission_target_realm_display_name = ?," - + " admission_target_game_session_tenant_id = ?, admission_target_game_instance_id = ?," - + " admission_target_playable_state_namespace_id = ?, admission_target_playable_state_scope = ?," - + " admission_target_canonical_game_instance_id = ?, admission_target_canonical_version_id = ?," - + " admission_target_runtime_version_id = ?, admission_target_catalog_revision = ?," - + " admission_target_pointer_version = ?, admission_target_pointer_snapshot_digest = ?," - + " admission_target_active_world_epoch = ?, admission_target_initial_admission_request_id = ?," - + " admission_target_initial_admission_request_digest = ?," - + " admission_target_origin_kind = 'NO_PRIOR_POINTER'," - + " admission_target_hold_id = ?, admission_target_hold_fence = ?," - + " admission_target_hold_binding_digest = ?, admission_target_audit_event_id = ?," - + " admission_target_owner_proof_digest = ?, admission_target_owner_proof_outcome = 'COMMITTED'," - + " admission_target_positive_durable_abort = FALSE, admission_target_terminal_at = ?," - + " admission_target_character_creation_policy = ?" - + " WHERE candidate_binding_ref = ?", - UUID.randomUUID(), - UUID.randomUUID(), - RAW_SHA256, - target.targetNamespace(), - target.tenantSlug(), - target.canonicalTenantId(), - target.worldSlug(), - target.worldDisplayName(), - target.realmId(), - target.realmSlug(), - target.realmDisplayName(), - target.gameSessionTenantId(), - target.gameInstanceId(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.canonicalVersionId(), - target.runtimeVersionId(), - target.catalogRevision(), - target.pointerVersion(), - target.admissionPointerSnapshotDigest(), - target.activeWorldEpoch(), - target.initialAdmissionRequestId(), - target.initialAdmissionRequestDigest(), - target.holdId(), - target.holdFence(), - target.holdBindingDigest(), - target.auditEventId(), - target.ownerProofDigest(), - Timestamp.from(target.ownerProofTerminalAt()), - target.characterCreationPolicy(), - candidateRef); + CanonicalGameplayBindingRuntimeTestFixtures.markProvisional( + dsl, runtimeTarget.playableTarget(), candidateRef); } private static void assertLaunchPreparationCatalogMismatchRejected( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java index 3fe11e5a76..31f3f0dd83 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java @@ -32,7 +32,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.repository.AccountInitialAdmissionProtectionBindingRepository; -import net.firedevops.firemud.gamesession.repository.CanonicalGameplayDecisionRuntimeFenceIntegrationTest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingRuntimeTestFixtures; import net.firedevops.firemud.gamesession.repository.CanonicalHumanRuntimeCompletionRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; @@ -974,19 +974,18 @@ void healthyHumanRunningRepositorySaveRetainsCompletionForLaterLeaseBoundDecisio assertThat(saved.getRowVersion()).isEqualTo(before.getRowVersion() + 1L); assertThat(completionImage(harness)).isEqualTo(originalCompletion); byte[] candidate = - CanonicalGameplayDecisionRuntimeFenceIntegrationTest.seedCandidateAndPreparedTransition( + CanonicalGameplayBindingRuntimeTestFixtures.seedCandidateAndPreparedTransition( harness.dsl(), target); // V1044 required equality with the immutable completion and refused this real owner save. assertThatThrownBy( () -> - CanonicalGameplayDecisionRuntimeFenceIntegrationTest.markProvisional( + CanonicalGameplayBindingRuntimeTestFixtures.markProvisional( harness.dsl(), target, candidate)) .hasMessageContaining("exact current RUNNING launch row and candidate identity"); harness.migrateLatest(); - CanonicalGameplayDecisionRuntimeFenceIntegrationTest.markProvisional( - harness.dsl(), target, candidate); + CanonicalGameplayBindingRuntimeTestFixtures.markProvisional(harness.dsl(), target, candidate); assertThat( harness @@ -1039,12 +1038,12 @@ void humanCompletionStillRefusesStoppedMismatchedAndEarlierRuntimeDecisions() th target.gameInstanceId()); } byte[] candidate = - CanonicalGameplayDecisionRuntimeFenceIntegrationTest.seedCandidateAndPreparedTransition( + CanonicalGameplayBindingRuntimeTestFixtures.seedCandidateAndPreparedTransition( harness.dsl(), target); assertThatThrownBy( () -> - CanonicalGameplayDecisionRuntimeFenceIntegrationTest.markProvisional( + CanonicalGameplayBindingRuntimeTestFixtures.markProvisional( harness.dsl(), target, candidate)) .as("Human runtime source mismatch %s", mismatch) .hasMessageContaining("exact current RUNNING launch row and candidate identity"); From 7c93587def68edf7340d0275d90d50a6d95b1706 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:23:26 +1300 Subject: [PATCH 26/36] fix: align runtime actor contracts and World proof digests --- .../entity-management-service/runtime-and-data.md | 4 ++-- .../implementation-tracking/player-access-and-session.md | 2 +- ...artSessionPreparationOwnerCompositionCrossServiceTest.java | 4 ++-- 3 files changed, 5 insertions(+), 5 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 734ea5854d..43eaee57c3 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -383,7 +383,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. The runtime ID comes from the canonical runtime allocator, or a narrow Entity-owned durable allocation when that allocator is unavailable; 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. Allocation guarantees concurrent uniqueness, stable exact retry and restart, and nonreuse throughout the required runtime and retention lifetime. Runtime replacement allocates a new projection generation and runtime ID while retaining and fencing the previous association; reconnect alone does not replace the projection. A controlled source cannot authorize production allocation. Allocation alone establishes neither World placement, an active lifecycle, a Game Session region lease nor admission. @@ -417,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/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 37b4ef932d..f60d5fd6d7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -470,7 +470,7 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The ## Validation and Proof -The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. Preserve and read the retained preparation and incident evidence, keep the scope fenced, and escalate through the owning recovery process under the [current operator fallback](../../architecture/system-architecture-redis-reset-and-recovery.md#current-operator-fallback); neither SQL phase edits nor raw key surgery is a supported remedy. The [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md#tick-coordination-and-lease-ownership) records the local consequence. +The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. The operator recovery boundary is recorded by the [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md#tick-coordination-and-lease-ownership). Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passes all 25 selected cases: 19 Entity runtime-reference/assignment boundary units, five native region-owner cases including this cut, and the inherited protected-admission concurrency case. Affected production and Game Session integration static checks, formatting and documentation pass, but R890's aggregate fails Entity test SpotBugs on mutable failure capture and remains a failed aggregate. R891's attempted annotation correction fails compilation because the Entity test source set lacks the annotation dependency; no cases execute in that run. After replacing the capture with immutable status-description and cause-presence snapshots, R893 freshly passes 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 pass in R893. That focused recovery preserves the disclosure and terminal-callback assertions; it does not relabel R890 or R891 as successful aggregates. This is bounded refusal proof and does not establish recovery or production activation. 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 7e4386f8f5..476f229b03 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 @@ -3476,8 +3476,8 @@ private static CanonicalInitialPlayerLocationRequest toWorldLocationRequest( .setCharacterUuid(secondRequest.getCharacterUuid()) .setAssignmentUuid(secondRequest.getAssignmentUuid()) .setAssignmentIntentDigest(secondRequest.getAssignmentIntentDigest()) - .setRequestDigest("d".repeat(64)) - .setResultDigest("e".repeat(64)) + .setRequestDigest("sha256:" + "d".repeat(64)) + .setResultDigest("sha256:" + "e".repeat(64)) .build(); var secondLifecycle = firstResolvedRegion.observation().getLifecycle().toBuilder() From 61ee960bedcafc1d4933ba17b45e782912751f6b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:35:33 +1300 Subject: [PATCH 27/36] fix: acquire runtime locks before region bridge transitions --- ...calGameplayBindingInventoryRepository.java | 10 ++ ...meplayRegionLeaseOwnerIntegrationTest.java | 101 ++++++++++++ ...GameplayRegionOwnerCompositionFixture.java | 144 +++++++++++++++++- 3 files changed, 251 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index 984a1468f1..a4c7780413 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -312,6 +312,11 @@ CanonicalGameplayBindingRegionBridgeObligation prepareRegionBridge( configuration -> { DSLContext transaction = DSL.using(configuration); BigInteger currentRevision = lockInventoryRevision(transaction); + lockLeaseBoundRuntimeBeforeTransition( + transaction, + expectedEvidence.transition().transitionId(), + expectedEvidence.candidate().bindingRef().bytes(), + null); CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = loadProvisionalCasEvidence( transaction, expectedEvidence.transition().transitionId(), true); @@ -390,6 +395,11 @@ RegionBridgeAcknowledgement acknowledgeRegionBridge( configuration -> { DSLContext transaction = DSL.using(configuration); BigInteger currentRevision = lockInventoryRevision(transaction); + lockLeaseBoundRuntimeBeforeTransition( + transaction, + prepared.transitionId(), + expectedEvidence.candidate().bindingRef().bytes(), + null); CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = loadProvisionalCasEvidence(transaction, prepared.transitionId(), true); requireSameProvisionalOperation(expectedEvidence, currentEvidence); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index c77998dcdf..17258f3f53 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -30,9 +30,11 @@ import java.time.ZoneOffset; import java.util.List; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import javax.sql.DataSource; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; @@ -629,6 +631,105 @@ void initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry } } + @Test + void bridgeSqlPhasesWaitForRuntimeBeforeLockingTransition() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema schema = newTestSchema(); + try { + try (RedisFixture redis = RedisFixture.open()) { + redis.admin().flushdb(); + } + var target = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + schema.dataSource(), UUID.randomUUID(), "firemud"); + WorldFixture world = WorldFixture.open(target); + var observed = + new java.util.EnumMap< + CanonicalGameplayRegionOwnerCompositionFixture.BridgeSqlPhase, Boolean>( + CanonicalGameplayRegionOwnerCompositionFixture.BridgeSqlPhase.class); + try (var entity = EntityReferenceFixture.open()) { + var proof = + CanonicalGameplayRegionOwnerCompositionFixture.installAndBridgeWithSqlPhaseRunner( + schema.dsl(), + REDIS.getHost(), + REDIS.getMappedPort(REDIS_PORT), + world.request(), + target.playableTarget(), + world.resolver(), + entity.client(), + new CanonicalGameplayRegionOwnerCompositionFixture.BridgeSqlPhaseRunner() { + @Override + public T run( + CanonicalGameplayRegionOwnerCompositionFixture.BridgeSqlPhase phase, + Supplier action) { + T result = runBridgePhaseAgainstRuntimeHolder(schema, target, action); + observed.put(phase, true); + return result; + } + }); + assertThat(proof.exactLostReplyRetry()).isTrue(); + } + assertThat(observed.keySet()) + .containsExactlyInAnyOrder( + CanonicalGameplayRegionOwnerCompositionFixture.BridgeSqlPhase.PREPARE, + CanonicalGameplayRegionOwnerCompositionFixture.BridgeSqlPhase.ACKNOWLEDGE); + } finally { + dropSchema(schema.schema()); + } + } + + private static T runBridgePhaseAgainstRuntimeHolder( + TestSchema schema, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, + Supplier action) { + CompletableFuture bridge = null; + try (Connection holder = schema.dataSource().getConnection()) { + holder.setAutoCommit(false); + DSLContext held = DSL.using(holder, SQLDialect.POSTGRES); + held.execute("SET LOCAL lock_timeout = '3s'"); + int holderPid = held.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + assertThat( + held.fetchOne( + "SELECT id FROM game_instances WHERE tenant_id = ? AND id = ?" + + " AND game_instance_uuid = ? FOR UPDATE", + target.gameSessionTenantId(), + target.gameInstanceId(), + target.gameInstanceUuid())) + .isNotNull(); + bridge = CompletableFuture.supplyAsync(action); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + Integer waitingPid = null; + while (System.nanoTime() < deadline && waitingPid == null) { + Record waiter = + schema + .dsl() + .fetchOne( + "SELECT pid FROM pg_stat_activity WHERE pid <> pg_backend_pid()" + + " AND ? = ANY(pg_blocking_pids(pid))" + + " AND query LIKE '%game_instances%' LIMIT 1", + holderPid); + if (waiter != null) waitingPid = waiter.get("pid", Integer.class); + } + assertThat(waitingPid).as("bridge waits on exact runtime holder").isNotNull(); + assertThat(bridge.isDone()).isFalse(); + // V34.2 takes the transition row in this runtime UPDATE trigger. It must complete while + // the bridge is blocked on our runtime row, before the holder releases that row. + assertThat( + held.execute( + "UPDATE game_instances SET status = status WHERE tenant_id = ? AND id = ?" + + " AND game_instance_uuid = ?", + target.gameSessionTenantId(), + target.gameInstanceId(), + target.gameInstanceUuid())) + .isEqualTo(1); + holder.commit(); + return bridge.get(10, TimeUnit.SECONDS); + } catch (Exception | AssertionError failure) { + if (bridge != null) bridge.cancel(true); + throw new AssertionError("Bridge/runtime lock-order proof failed", failure); + } + } + @Test void accountMemberAcknowledgementAfterRegionBridgePreservesOriginalBridgeEvidence() throws Exception { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index 7fecf6124f..93b5ca2cad 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -26,10 +26,12 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; @@ -89,6 +91,40 @@ public static Proof installAndBridge( .first(); } + enum BridgeSqlPhase { + PREPARE, + ACKNOWLEDGE + } + + @FunctionalInterface + interface BridgeSqlPhaseRunner { + T run(BridgeSqlPhase phase, Supplier action); + } + + static Proof installAndBridgeWithSqlPhaseRunner( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + BridgeSqlPhaseRunner phaseRunner) + throws Exception { + return installAndBridgeInternal( + dsl, + redisHost, + redisPort, + worldRequest, + currentTarget, + worldRegionResolver, + entityReferenceClient, + null, + null, + Objects.requireNonNull(phaseRunner, "phaseRunner")) + .first(); + } + /** Reacquires a real region grant after the bridge ACK and proves that the ACK remains closed. */ public static ChangedGrantProof installAndBridgeThenChangedGrantRefuses( DSLContext dsl, @@ -449,6 +485,31 @@ private static TwoBindingProof installAndBridgeInternal( SecondBinding secondBinding, AtomicReference changedGrantProofCapture) throws Exception { + return installAndBridgeInternal( + dsl, + redisHost, + redisPort, + worldRequest, + currentTarget, + worldRegionResolver, + entityReferenceClient, + secondBinding, + changedGrantProofCapture, + null); + } + + private static TwoBindingProof installAndBridgeInternal( + DSLContext dsl, + String redisHost, + int redisPort, + CanonicalInitialPlayerLocationRequest worldRequest, + CanonicalPlayableTarget currentTarget, + CanonicalInitialPlayerLocationRegionResolver worldRegionResolver, + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + SecondBinding secondBinding, + AtomicReference changedGrantProofCapture, + BridgeSqlPhaseRunner phaseRunner) + throws Exception { UUID transitionId = UUID.randomUUID(); UUID sessionId = UUID.randomUUID(); var resolved = worldRegionResolver.resolve(worldRequest); @@ -513,19 +574,24 @@ private static TwoBindingProof installAndBridgeInternal( "controlled-test-image"); CanonicalPreseededActorRuntimeReferenceClient bridgeEntityReferenceClient = secondBinding == null ? entityReferenceClient : secondBinding.entityReferenceClient(); - var bridgeOwner = - CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( + var leaseOwner = + CanonicalGameplayRegionLeaseOwnerFactory.compose( dsl, redis.ownerClient(), scriptCatalog, stableSource, worldRegionResolver, - bridgeEntityReferenceClient, runtimeIdentity, Duration.ofSeconds(30), Clock.systemUTC()); + var bridgeOwner = + new CanonicalGameplayRegionBindingBridgeOwner(leaseOwner, bridgeEntityReferenceClient); var installation = bridgeOwner.installForTransition(transitionId, worldRequest); - var firstAcknowledgement = bridgeOwner.bridge(installation); + var firstAcknowledgement = + phaseRunner == null + ? bridgeOwner.bridge(installation) + : bridgeWithSqlPhaseRunner( + leaseOwner, installation, bridgeEntityReferenceClient, phaseRunner); var lostReplyRetry = bridgeOwner.bridge(installation); var acknowledged = firstAcknowledgement.obligation(); var replayed = lostReplyRetry.obligation(); @@ -862,6 +928,76 @@ private static TwoBindingProof installAndBridgeInternal( } } + private static CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement + bridgeWithSqlPhaseRunner( + CanonicalGameplayRegionLeaseOwner leaseOwner, + CanonicalGameplayRegionLeaseOwner.Installation installation, + CanonicalPreseededActorRuntimeReferenceClient entityClient, + BridgeSqlPhaseRunner phaseRunner) { + var request = installation.worldRequest; + var initial = leaseOwner.currentBridgeContext(installation); + if (initial.evidence().expectedPrior() != null + || initial.evidence().transition().status() + != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot + .Status.PROVISIONAL) { + throw new IllegalStateException("Region bridge requires an exact first-NEW transition"); + } + var entityRequest = + ReadPreseededActorRuntimeReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(request.getAssignmentUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setExpectedTarget(request.getExpectedTarget()) + .setCharacterUuid(request.getCharacterUuid()) + .setIntentDigest(request.getAssignmentIntentDigest()) + .build(); + var reference = entityClient.read(entityRequest); + var preimage = leaseOwner.probeRegionSessionBinding(installation, reference); + phaseRunner.run( + BridgeSqlPhase.PREPARE, () -> leaseOwner.prepareBridge(installation, preimage, reference)); + var beforeWriteReference = entityClient.read(entityRequest); + requireSameBridgeReference(reference, beforeWriteReference); + var beforeWritePreimage = + leaseOwner.probeRegionSessionBinding(installation, beforeWriteReference); + leaseOwner.prepareBridge(installation, beforeWritePreimage, beforeWriteReference); + leaseOwner.applyRegionSessionBinding(installation, beforeWriteReference); + var currentReference = entityClient.read(entityRequest); + requireSameBridgeReference(reference, currentReference); + var beforeReadbackPreimage = + leaseOwner.probeRegionSessionBinding(installation, currentReference); + leaseOwner.prepareBridge(installation, beforeReadbackPreimage, currentReference); + var readback = + leaseOwner.readBackRegionSessionBinding( + installation, beforeReadbackPreimage.context().status(), currentReference); + var afterReadbackReference = entityClient.read(entityRequest); + requireSameBridgeReference(reference, afterReadbackReference); + var beforeAckPreimage = + leaseOwner.probeRegionSessionBinding(installation, afterReadbackReference); + if (!beforeReadbackPreimage.context().status().equals(beforeAckPreimage.context().status())) { + throw new IllegalStateException("Region bridge owner changed before acknowledgement"); + } + var prepared = + leaseOwner.prepareBridge(installation, beforeAckPreimage, afterReadbackReference); + return phaseRunner.run( + BridgeSqlPhase.ACKNOWLEDGE, + () -> + leaseOwner.acknowledgeBridge( + installation, + prepared, + beforeAckPreimage.context(), + afterReadbackReference, + readback)); + } + + private static void requireSameBridgeReference( + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference expected, + CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference actual) { + if (!CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(expected) + .equals(CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(actual))) { + throw new IllegalStateException("Region bridge Entity source changed"); + } + } + private static ChangedGrantProof reacquireGrantAfterAcknowledgement( DSLContext dsl, RegionRedis redis, From b815be3dcfad5ce40a2d2bf08f65d4e0723cd0b8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 13:31:31 +1300 Subject: [PATCH 28/36] docs: distinguish target runtime replacement from initial projection --- .../entity-management-service/runtime-and-data.md | 4 ++-- 1 file changed, 2 insertions(+), 2 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 43eaee57c3..cd7dcaf053 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -385,9 +385,9 @@ Character and NPC records remain the durable domain records for their respective 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. Runtime replacement allocates a new projection generation and runtime ID while retaining and fencing the previous association; reconnect alone does not replace the projection. A controlled source cannot authorize production allocation. Allocation alone establishes neither World placement, an active lifecycle, a Game Session region lease nor admission. +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 rejects update, delete, and truncate until the exact replacement-owner chain exists. 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. 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. From cf09f3e21e9fcea9c584487ed09371a90fd08a06 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:58:39 +1300 Subject: [PATCH 29/36] docs: remove duplicate blank after roster retention reconciliation --- .../implementation-tracking/player-access-and-session.md | 1 - 1 file changed, 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index baa6c81f69..5b4ee561b7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -488,7 +488,6 @@ The region-owner CLI correction gate passed 40 freshly executed tests across the 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. From f397f709d828015c654240e1d4009b4daa4c4329 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:07:08 +1300 Subject: [PATCH 30/36] fix(world): map unexpected region response conversion failures --- ...nicalInitialPlayerLocationGrpcService.java | 3 + ...tialPlayerLocationGrpcServiceMtlsTest.java | 61 +++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java index c52527957b..4e41e7a5cd 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java @@ -185,6 +185,9 @@ public void readInitialPlayerLocationRegion( Status.FAILED_PRECONDITION, "Exact initial-placement region evidence is unavailable"); return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.UNAVAILABLE, "World initial-player region read is unavailable"); + return; } if (response.isEmpty()) { diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java index 29e4a348e4..c304080b3d 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java @@ -37,6 +37,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository.Outcome; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository.Result; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationServiceGrpc; @@ -162,6 +163,66 @@ private static WorldCanonicalInitialPlayerLocationRepository.RegionResult contro placement, 4L, 917L, canonicalRegion, operationalRegion, lifecycle); } + @Test + void regionConversionRuntimeFailureUsesSanitizedUnavailableAndOneErrorCallback() { + var owner = mock(CanonicalInitialPlayerLocationService.class); + var retained = controlledRegionResult(false); + var privateFailure = new UnsupportedOperationException("private conversion detail"); + when(retained.lifecycleEvidence().request()).thenThrow(privateFailure); + when(owner.readRegion(any())).thenReturn(Optional.of(retained)); + var grpc = new CanonicalInitialPlayerLocationGrpcService(NAMESPACE, owner); + var nextCalls = new int[1]; + var errorCalls = new int[1]; + var completedCalls = new int[1]; + var errors = new Throwable[1]; + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(CanonicalInitialPlayerLocationRegionResponse response) { + nextCalls[0]++; + } + + @Override + public void onError(Throwable failure) { + errorCalls[0]++; + errors[0] = failure; + } + + @Override + public void onCompleted() { + completedCalls[0]++; + } + }; + + // This direct callback fixture isolates conversion failure mapping; it grants no World + // authority. + try (MockedStatic peer = + mockStatic(CanonicalInitialPlayerLocationPeerInterceptor.class)) { + peer.when(CanonicalInitialPlayerLocationPeerInterceptor::currentVerifiedPeer) + .thenReturn( + new GrpcPeerIdentity( + "spiffe://firemud/ns/firemud/sa/game-session-service", + NAMESPACE, + "game-session-service")); + peer.when(() -> CanonicalInitialPlayerLocationPeerInterceptor.requireVerifiedPeer(NAMESPACE)) + .thenCallRealMethod(); + + grpc.readInitialPlayerLocationRegion(request(), observer); + } + + assertThat(nextCalls[0]).isZero(); + assertThat(errorCalls[0]).isEqualTo(1); + assertThat(completedCalls[0]).isZero(); + assertThat(errors[0]).isInstanceOf(StatusRuntimeException.class); + var status = Status.fromThrowable(errors[0]); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("World initial-player region read is unavailable"); + assertThat(status.getDescription()).doesNotContain("private"); + assertThat(status.getCause()).isNull(); + verify(owner).readRegion(CanonicalInitialPlayerLocationGrpcCodec.fromRegionRequest(request())); + } + @Test void bothRpcMethodsRequireTheExactSameNamespaceGameSessionCertificate(@TempDir Path temporary) throws Exception { From 4ece97c5ad54bac647b94bbb8963f04bb7a00e10 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:34:03 +1300 Subject: [PATCH 31/36] style(gameplay): preserve formatted composition helper spacing --- ...lStartSessionPreparationOwnerCompositionCrossServiceTest.java | 1 - 1 file changed, 1 deletion(-) 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 d049ea16db..6d9ce9a046 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 @@ -2889,7 +2889,6 @@ private static void assertAccountAdmissionProtectionSettled( } } - /** * Extends the retained 2973 COMMITTED hold through actual Entity assignment, World placement, * authenticated current World reads, and the selected Game Session first-NEW region owners. From c0e6c9d1292202c7399acd824b933a36ce209977 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:45:22 +1300 Subject: [PATCH 32/36] fix(gameplay): preflight region timeline before one-shot claim --- .../game-session-service/operations.md | 2 +- .../game-session-service/runtime-and-data.md | 2 +- .../CanonicalGameplayRegionLeaseOwner.java | 29 +- ...anonicalGameplayRegionLeaseRedisOwner.java | 133 +++++++-- ...alInitialPlayerLocationRegionResolver.java | 1 + ...rtitionBuildRepositoryIntegrationTest.java | 22 +- ...meplayRegionLeaseOwnerIntegrationTest.java | 264 +++++++++++++++--- ...RegionBootstrapAssignmentResolverTest.java | 28 ++ ...onicalInitialPlayerLocationRepository.java | 7 +- 9 files changed, 403 insertions(+), 85 deletions(-) diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index 2fbdab3c5d..70de41b615 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -42,7 +42,7 @@ Before deploying the new Game Session admission validation, Automation must alre - Prometheus scrapes metrics from `/actuator/prometheus`. - Target state: logs, traces, and control-plane reads expose the active exact `{scriptPatchVersion, scriptPinEpoch}` execution fence so operators can identify the hotfix revision and selection epoch during incident triage without adding either raw value as ordinary high-cardinality metric labels. Current coverage is summarized in [Implementation Status](#implementation-status). -For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata cannot distinguish never-executed initialization from metadata loss. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. No same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). +For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata cannot distinguish never-executed initialization from metadata loss. Descriptor, source, connection, principal, or `SCRIPT LOAD` refusal during preflight does not change the preparation phase or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains valid, a corrected ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. A process stop between claim and `EVALSHA` or an ambiguous send/result leaves the scope held; there is no automatic same-scope retry or recovery. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. No same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). ## Scaling and Region Rebalancing diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index d29202ba64..19a034bb3c 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -243,7 +243,7 @@ Tick coordination is region-scoped, not session-scoped. Tick queues, locks, time Session shutdown therefore cleans up session keys but does not implicitly delete region-level tick coordination keys. -Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. If that SQL transition commits and the process stops before its Redis initialization call, the retained phase, operation and source remain, while both Redis metadata and lease can still be absent. A later attempt cannot distinguish never-executed initialization from lost metadata. It therefore fails closed without obtaining a fresh creation permission, acquiring a lease or rewriting the same-epoch baseline. This is a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for this cut. Retain and read the available preparation and incident evidence, keep the affected scope fenced, and escalate through the owning recovery process using the [current operator fallback](../../system-architecture-redis-reset-and-recovery.md#current-operator-fallback); SQL phase edits and raw Redis key surgery are not recovery authority. The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps), with focused first-NEW proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). +Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. Before that SQL claim, the owner validates the registered script descriptor and digest-checked bytes, connects, verifies `ACL WHOAMI`, and loads the script on the same connection it retains for the sole `EVALSHA`. A descriptor, source, connection, principal, or `SCRIPT LOAD` refusal closes that connection without changing the preparation or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains absent, a later ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. After the transition commits, the owner revalidates the current source and invokes that prepared session once. If the process stops between claim and send, or the send/result is ambiguous, the preparation remains `INITIALIZING`; a later attempt cannot distinguish never-executed initialization from lost metadata. It therefore fails closed without obtaining a fresh creation permission, acquiring a lease or rewriting the same-epoch baseline. This is a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for this cut. Retain and read the available preparation and incident evidence, keep the affected scope fenced, and escalate through the owning recovery process using the [current operator fallback](../../system-architecture-redis-reset-and-recovery.md#current-operator-fallback); SQL phase edits and raw Redis key surgery are not recovery authority. The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps), with focused first-NEW proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). ## Reconnection and Disconnect Handling diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 5e37cc1989..58c7fc237f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -115,11 +115,30 @@ Installation installForTransition( .INSTALLED) { throw unavailable(); } - Optional permit = - statusRepository.beginInitialTimeline(preparation, clock.instant()); - grant = - redisOwner.initializeOrResumeTimeline( - preparation, permit.orElse(null), leaseTtl, runtimeIdentity); + try (CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization session = + redisOwner.prepareTimelineInitialization(preparation, leaseTtl, runtimeIdentity)) { + Optional + permit = statusRepository.beginInitialTimeline(preparation, clock.instant()); + CanonicalGameplayBindingProvisionalCasEvidence afterClaimEvidence = + readCurrentProvisionalEvidence(transitionId); + bindingInventory.requireSameProvisionalSource(evidence, afterClaimEvidence); + ResolvedBridgeSource afterClaimWorld = + resolveExactBridgeSource(worldRequest, afterClaimEvidence); + requireSameSource(source, afterClaimWorld.source); + CanonicalGameplayRegionIncarnationSource.StableEvidence afterClaimIncarnation = + readCurrentIncarnation(source); + requireSameIncarnation(incarnation, afterClaimIncarnation); + if (!statusRepository.matchesTimelinePreparation( + preparation, + afterClaimEvidence, + worldRequest, + afterClaimWorld.resolvedRegion, + source, + afterClaimIncarnation)) { + throw unavailable(); + } + grant = session.initialize(permit.orElse(null)); + } redisOwner.verifyInitializedTimeline(grant, preparation); requireSameIncarnation(incarnation, readCurrentIncarnation(source)); ResolvedBridgeSource afterInitWorld = resolveExactBridgeSource(worldRequest, evidence); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index 7d4961c64e..955a1ddae8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -141,39 +141,70 @@ TimelineAbsenceProof requireTimelineAbsent( absenceProofDigest(source, incarnation)); } - LeaseGrant initializeOrResumeTimeline( + PreparedTimelineInitialization prepareTimelineInitialization( CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, - CanonicalGameplayRegionRuntimeStatusRepository.InitialInitializationPermit permit, Duration leaseTtl, RuntimeIdentity identity) { requireNoAmbientTransaction(); Objects.requireNonNull(preparation, "preparation"); + CanonicalGameplayRegionRuntimeStatusRepository.Source source = + Objects.requireNonNull(preparation.source(), "timeline source"); + UUID operationId = Objects.requireNonNull(preparation.operationId(), "timeline operation id"); + String sourceDigest = + Objects.requireNonNull(preparation.sourceDigest(), "timeline source digest"); + if (!sourceDigest.matches("[0-9a-f]{64}")) throw unavailable(); + requirePositive(preparation.regionEpoch(), "regionEpoch"); long ttlMillis = ttlMillis(leaseTtl); String ownerService = requireOwnerService(identity); String ownerInstance = requireOwnerInstance(identity); - boolean mayCreate = permit != null; - if (mayCreate - && (!permit.operationId().equals(preparation.operationId()) - || !permit.sourceDigest().equals(preparation.sourceDigest()))) { - throw unavailable(); - } LeaseGrant grant = new LeaseGrant( - preparation.source(), + source, preparation.regionEpoch(), UUID.randomUUID().toString(), ownerService, ownerInstance); - long outcome = - executeTimeline( - grant, - "INITIALIZE", - preparation.operationId(), - preparation.sourceDigest(), - ttlMillis, - mayCreate); - if (outcome != 1L && outcome != 2L) throw unavailable(); - return grant; + RedisScriptDescriptor descriptor = + requireDescriptor( + CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_ID, + CanonicalGameplayRegionLeaseRedisScriptContribution.TIMELINE_INITIALIZE_PATH, + TIMELINE_ARGUMENTS); + byte[] script = scriptSource(descriptor); + byte[][] keys = + new byte[][] { + ascii( + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId())), + ascii( + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())) + }; + byte[][] arguments = + new byte[][] { + ascii(TIMELINE_SCHEMA), + ascii("INITIALIZE"), + ascii(grant.token), + ascii(Long.toString(preparation.regionEpoch())), + ascii(operationId.toString()), + ascii(sourceDigest), + ascii(Long.toString(ttlMillis)), + ascii("0") + }; + if (arguments.length != TIMELINE_ARGUMENTS.size()) throw unavailable(); + + StatefulRedisConnection connection = null; + try { + connection = redisClient.connect(ByteArrayCodec.INSTANCE); + RedisAsyncCommands commands = connection.async(); + requirePrincipal(await(commands.aclWhoami())); + String loadedSha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(loadedSha)) throw unavailable(); + return new PreparedTimelineInitialization( + connection, commands, loadedSha, keys, arguments, grant, preparation); + } catch (RuntimeException failure) { + if (connection != null) connection.close(); + throw unavailable(failure); + } } void verifyInitializedTimeline( @@ -251,6 +282,70 @@ private long executeTimeline( mayCreate); } + /** + * Holds the one ACL-verified connection across the SQL creation-permission claim and its sole + * timeline EVALSHA. Closing without initialize leaves the timeline untouched. + */ + static final class PreparedTimelineInitialization implements AutoCloseable { + private final StatefulRedisConnection connection; + private final RedisAsyncCommands commands; + private final String loadedSha; + private final byte[][] keys; + private final byte[][] arguments; + private final LeaseGrant grant; + private final CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation; + private boolean initialized; + private boolean closed; + + private PreparedTimelineInitialization( + StatefulRedisConnection connection, + RedisAsyncCommands commands, + String loadedSha, + byte[][] keys, + byte[][] arguments, + LeaseGrant grant, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation) { + this.connection = connection; + this.commands = commands; + this.loadedSha = loadedSha; + this.keys = keys; + this.arguments = arguments; + this.grant = grant; + this.preparation = preparation; + } + + synchronized LeaseGrant initialize( + CanonicalGameplayRegionRuntimeStatusRepository.InitialInitializationPermit permit) { + requireNoAmbientTransaction(); + if (closed || initialized) throw unavailable(); + boolean mayCreate = permit != null; + if (mayCreate + && (!permit.operationId().equals(preparation.operationId()) + || !permit.sourceDigest().equals(preparation.sourceDigest()))) { + throw unavailable(); + } + initialized = true; + byte[][] evalArguments = arguments.clone(); + evalArguments[evalArguments.length - 1] = ascii(mayCreate ? "1" : "0"); + Long outcome; + try { + outcome = await(commands.evalsha(loadedSha, ScriptOutputType.INTEGER, keys, evalArguments)); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + if (outcome == null || (outcome != 1L && outcome != 2L)) throw unavailable(); + return grant; + } + + @Override + public synchronized void close() { + if (!closed) { + closed = true; + connection.close(); + } + } + } + private long executeTimeline( CanonicalGameplayRegionRuntimeStatusRepository.Source source, long regionEpoch, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java index b779c2d7fb..75f1c1cc7d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java @@ -47,6 +47,7 @@ public ResolvedRegion resolve(CanonicalInitialPlayerLocationRequest request) { || !lifecycle.getCaptureUuid().equals(current.captureId().toString()) || !lifecycle.getGraphSha256().equals(current.graphSha256()) || !lifecycle.getPreparationInputDigest().equals(current.preparationInputDigest()) + || !canonicalRegionId.equals(current.canonicalRegionId()) || !observed.getOperationalRegionUuid().equals(current.operationalRegionId().toString())) { throw new IllegalStateException( "World initial-location region consequence changed during lifecycle revalidation"); 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 cc7c557d3b..ee63ec3e7a 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 @@ -2199,27 +2199,13 @@ private static void migrateThrough1038(TestSchema testSchema) { } private static void migrateThrough1044_1(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1044.1")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, "1044.1"); } private static void migrateThrough1044_2(TestSchema testSchema) { - Flyway.configure() - .dataSource(testSchema.dataSource()) - .schemas(testSchema.schema()) - .defaultSchema(testSchema.schema()) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("1044.2")) - .load() - .migrate(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + testSchema.dataSource(), testSchema.schema(), MIGRATION_LOCATION, "1044.2"); } private static void migrateRemaining(TestSchema testSchema) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 17258f3f53..d38a2c65cf 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -28,6 +28,7 @@ import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -247,7 +248,9 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(redis.admin().type(redisKey)).isEqualTo("none"); assertThat(statusRepository.find(qualifiedSource)).isEmpty(); - world.setAfterRead(2, incarnationSource::changeRecoveryEvidence); + // Reads one and two are the initial source read and the new post-claim revalidation; read + // three runs after EVALSHA, where this case exercises recovery-evidence drift. + world.setAfterRead(3, incarnationSource::changeRecoveryEvidence); Throwable recoveryDriftFailure = catchThrowable(() -> firstOwner.installForTransition(TRANSITION_ID, world.request())); assertThat(recoveryDriftFailure).isInstanceOf(IllegalStateException.class); @@ -295,18 +298,8 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(redis.admin().hdel(ascii(initialMetaKey), ascii("current_tick_id"))).isEqualTo(1L); assertThatThrownBy( () -> - redisOwner.initializeOrResumeTimeline( - preparation, - null, - Duration.ofSeconds(30), - new RuntimeIdentity( - "game-session-service", - "instance-a", - "localhost", - NOW, - "controlled-test", - "controlled-sha", - "controlled-image"))) + initializeTimelineWithoutCreationPermission( + redisOwner, preparation, "instance-a")) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical Game Session region lease is unavailable") .satisfies(failure -> assertThat(failure.getCause()).isNull()); @@ -534,6 +527,133 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws } } + @Test + void timelinePreflightFailuresLeavePreparedPermissionAndAllowLaterFirstClaim() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(POSTGRES); + TestSchema testSchema = newTestSchema(); + try (RedisFixture redis = RedisFixture.open()) { + var statusRepository = new CanonicalGameplayRegionRuntimeStatusRepository(testSchema.dsl()); + var validRedisOwner = + new CanonicalGameplayRegionLeaseRedisOwner(redis.ownerClient(), redis.catalog()); + WorldFixture world = WorldFixture.open(); + var incarnationSource = new ControlledStableIncarnationSource(); + var bindingEvidence = provisionalEvidence(world.request()); + var bindingInventory = mock(CanonicalGameplayBindingInventoryRepository.class); + when(bindingInventory.readProvisionalCasEvidence(TRANSITION_ID)).thenReturn(bindingEvidence); + var source = source(world.originalEvidence()); + var incarnation = + incarnationSource.readCurrent( + CanonicalGameplayRegionIncarnationSource.RegionScope.from(source)); + var preparation = + statusRepository.prepareInitialTimeline( + bindingEvidence, + world.request(), + world.resolver().resolve(world.request()), + source, + incarnation, + validRedisOwner.requireTimelineAbsent(source, incarnation), + NOW); + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + + var missingDescriptorOwner = + owner( + bindingInventory, + statusRepository, + new CanonicalGameplayRegionLeaseRedisOwner( + redis.ownerClient(), RedisScriptCatalog.fromContributions(List.of())), + world, + "missing-descriptor", + incarnationSource); + assertThatThrownBy( + () -> missingDescriptorOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + + RedisClient unavailableClient = + RedisClient.create( + RedisURI.Builder.redis("127.0.0.1", 1).withTimeout(Duration.ofMillis(250)).build()); + unavailableClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); + try { + var connectionFailureOwner = + owner( + bindingInventory, + statusRepository, + new CanonicalGameplayRegionLeaseRedisOwner(unavailableClient, redis.catalog()), + world, + "connection-refused", + incarnationSource); + assertThatThrownBy( + () -> connectionFailureOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + } finally { + unavailableClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + + RedisClient wrongPrincipalClient = + redis.additionalClient("gamesession_coord_wrong", UUID.randomUUID().toString(), true); + var principalFailureOwner = + owner( + bindingInventory, + statusRepository, + new CanonicalGameplayRegionLeaseRedisOwner(wrongPrincipalClient, redis.catalog()), + world, + "wrong-principal", + incarnationSource); + assertThatThrownBy( + () -> principalFailureOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + + redis.setOwnerScriptLoadAllowed(false); + try { + var scriptLoadFailureOwner = + owner( + bindingInventory, + statusRepository, + validRedisOwner, + world, + "script-load-denied", + incarnationSource); + assertThatThrownBy( + () -> scriptLoadFailureOwner.installForTransition(TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + } finally { + redis.setOwnerScriptLoadAllowed(true); + } + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + + var validOwner = + owner( + bindingInventory, + statusRepository, + validRedisOwner, + world, + "valid-after-preflight-refusal", + incarnationSource); + var installation = validOwner.installForTransition(TRANSITION_ID, world.request()); + assertThat(installation).isNotNull(); + assertThat(statusRepository.findTimelinePreparation(source).orElseThrow().phase()) + .isEqualTo( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.INSTALLED); + String leaseKey = + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId()); + String metaKey = + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId()); + assertThat(redis.admin().type(ascii(leaseKey))).isEqualTo("string"); + assertThat(redis.admin().type(ascii(metaKey))).isEqualTo("hash"); + } finally { + dropSchema(testSchema.schema()); + } + } + @Test void initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry() throws Exception { @@ -1131,6 +1251,26 @@ private static CanonicalGameplayRegionLeaseOwner owner( Clock.fixed(NOW, ZoneOffset.UTC)); } + private static void initializeTimelineWithoutCreationPermission( + CanonicalGameplayRegionLeaseRedisOwner redisOwner, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation, + String instanceId) { + try (CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization session = + redisOwner.prepareTimelineInitialization( + preparation, + Duration.ofSeconds(30), + new RuntimeIdentity( + "game-session-service", + instanceId, + "localhost", + NOW, + "controlled-test", + "controlled-sha", + "controlled-image"))) { + session.initialize(null); + } + } + private static CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence( CanonicalInitialPlayerLocationRequest request) { return provisionalEvidence( @@ -1337,6 +1477,43 @@ private static byte[] ascii(String value) { return value.getBytes(StandardCharsets.US_ASCII); } + private static void assertPreparedTimelineUnchanged( + DSLContext dsl, + CanonicalGameplayRegionRuntimeStatusRepository statusRepository, + RedisFixture redis, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparation preparation) { + var observed = statusRepository.findTimelinePreparation(source).orElseThrow(); + assertThat(observed.operationId()).isEqualTo(preparation.operationId()); + assertThat(observed.sourceDigest()).isEqualTo(preparation.sourceDigest()); + assertThat(observed.phase()) + .isEqualTo( + CanonicalGameplayRegionRuntimeStatusRepository.TimelinePreparationPhase.PREPARED); + assertThat( + dsl.fetchSingle( + "SELECT phase FROM game_session_region_timeline_preparation" + + " WHERE initialization_operation_id = ?", + preparation.operationId()) + .get("phase", String.class)) + .isEqualTo("PREPARED"); + assertThat( + redis + .admin() + .type( + ascii( + CanonicalGameplayRegionRedisKeys.lease( + source.tenantId(), source.gameInstanceId(), source.regionId())))) + .isEqualTo("none"); + assertThat( + redis + .admin() + .type( + ascii( + CanonicalGameplayRegionRedisKeys.meta( + source.tenantId(), source.gameInstanceId(), source.regionId())))) + .isEqualTo("none"); + } + private static final class WorldFixture { private final WorldCanonicalInstanceLifecycleEvidence original; private final CanonicalInitialPlayerLocationRequest request; @@ -1500,6 +1677,7 @@ private static final class RedisFixture implements AutoCloseable { private final StatefulRedisConnection adminConnection; private final RedisCommands admin; private final RedisScriptCatalog catalog; + private final List additionalClients = new ArrayList<>(); private RedisFixture( RedisClient administrator, @@ -1520,28 +1698,7 @@ static RedisFixture open() { administrator.connect(ByteArrayCodec.INSTANCE); RedisCommands admin = adminConnection.sync(); admin.flushdb(); - admin.aclSetuser( - PRINCIPAL, - new AclSetuserArgs() - .reset() - .on() - .addPassword(PASSWORD) - .keyPattern("tick-executor-lease:*") - .keyPattern("tick:*") - .addCommand(CommandType.HELLO) - .addCommand(CommandType.PING) - .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) - .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) - .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) - .addCommand(CommandType.EVALSHA) - .addCommand(CommandType.TYPE) - .addCommand(CommandType.HGET) - .addCommand(CommandType.HSET) - .addCommand(CommandType.HLEN) - .addCommand(CommandType.PTTL) - .addCommand(CommandType.GET) - .addCommand(CommandType.SET) - .addCommand(CommandType.PEXPIRE)); + admin.aclSetuser(PRINCIPAL, ownerArguments(PASSWORD, true)); RedisClient ownerClient = createClient(PRINCIPAL, PASSWORD); RedisScriptCatalog catalog = RedisScriptCatalog.fromContributions( @@ -1571,9 +1728,46 @@ RedisScriptCatalog catalog() { return catalog; } + RedisClient additionalClient(String username, String password, boolean allowScriptLoad) { + admin.aclSetuser(username, ownerArguments(password, allowScriptLoad)); + RedisClient client = createClient(username, password); + additionalClients.add(client); + return client; + } + + void setOwnerScriptLoadAllowed(boolean allowed) { + admin.aclSetuser(PRINCIPAL, ownerArguments(PASSWORD, allowed)); + } + + private static AclSetuserArgs ownerArguments(String password, boolean allowScriptLoad) { + AclSetuserArgs args = + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("tick-executor-lease:*") + .keyPattern("tick:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HSET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRE); + if (allowScriptLoad) args.addCommand(CommandType.SCRIPT, CommandKeyword.LOAD); + return args; + } + @Override public void close() { adminConnection.close(); + additionalClients.forEach(client -> client.shutdown(Duration.ZERO, Duration.ofSeconds(2))); ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java index 01e7f94c6e..03abf446bc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolverTest.java @@ -224,6 +224,34 @@ void initialLocationRegionRejectsOperationalAssignmentSubstitution() { .hasMessageContaining("changed during lifecycle revalidation"); } + @Test + void initialLocationRegionRejectsCanonicalRegionSubstitution() { + var initialClient = mock(CanonicalInitialPlayerLocationClient.class); + var lifecycleResolver = mock(CanonicalRegionBootstrapAssignmentResolver.class); + var current = mock(CanonicalRegionBootstrapAssignmentResolver.Assignment.class); + when(current.request()).thenReturn(request); + when(current.canonicalRegionId()).thenReturn(CANONICAL_REGION_ID); + when(current.operationalRegionId()).thenReturn(OPERATIONAL_REGION_ID); + when(current.lifecycleStatus()).thenReturn(activeEvidence.lifecycleStatus()); + when(current.lifecycleEpoch()).thenReturn(activeEvidence.lifecycleEpoch()); + when(current.lifecycleRowVersion()).thenReturn(activeEvidence.rowVersion()); + when(current.captureId()).thenReturn(activeEvidence.captureId()); + when(current.graphSha256()).thenReturn(activeEvidence.graphSha256()); + when(current.preparationInputDigest()).thenReturn(activeEvidence.preparationInputDigest()); + when(lifecycleResolver.resolve(request, UNKNOWN_REGION_ID)).thenReturn(current); + var response = initialLocationRegionResponse(initialLocationRequest, activeEvidence); + var substitutedResponse = + response.toBuilder().setCanonicalRegionInstanceUuid(UNKNOWN_REGION_ID.toString()).build(); + when(initialClient.readInitialPlayerLocationRegion(initialLocationRequest)) + .thenReturn(substitutedResponse); + var resolver = + new CanonicalInitialPlayerLocationRegionResolver(initialClient, lifecycleResolver); + + assertThatThrownBy(() -> resolver.resolve(initialLocationRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed during lifecycle revalidation"); + } + private static CanonicalInitialPlayerLocationRequest initialLocationRequest( WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { var target = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java index dcc6a07d19..d8781e77df 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java @@ -234,12 +234,7 @@ public Optional readByOperationId(UUID operationId, RequestSelector sele requireReadOnlyRepeatableReadTransaction(); Record operation = readOperation(operationId); if (operation == null) return null; - Request retainedRequest = - new Request( - operationId, - required(operation, "request_digest", String.class), - required(operation, "request_bytes", byte[].class), - required(operation, "original_lifecycle_evidence_bytes", byte[].class)); + Request retainedRequest = retainedRequest(operation, operationId); ParsedRequest parsed = parseRequest(retainedRequest); selector.requireMatches(parsed); return readInOwnerTransaction(retainedRequest) From 5d96c1f0cd71ec290520a79833602b5d509df5fb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:05:41 +1300 Subject: [PATCH 33/36] fix(gameplay): revalidate timeline before dispatch claim --- .../game-session-service/operations.md | 2 +- .../game-session-service/runtime-and-data.md | 2 +- .../CanonicalGameplayRegionLeaseOwner.java | 24 +++++++++---------- ...meplayRegionLeaseOwnerIntegrationTest.java | 22 ++++++++++++++++- 4 files changed, 35 insertions(+), 15 deletions(-) diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index 70de41b615..822436f2d1 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -42,7 +42,7 @@ Before deploying the new Game Session admission validation, Automation must alre - Prometheus scrapes metrics from `/actuator/prometheus`. - Target state: logs, traces, and control-plane reads expose the active exact `{scriptPatchVersion, scriptPinEpoch}` execution fence so operators can identify the hotfix revision and selection epoch during incident triage without adding either raw value as ordinary high-cardinality metric labels. Current coverage is summarized in [Implementation Status](#implementation-status). -For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata cannot distinguish never-executed initialization from metadata loss. Descriptor, source, connection, principal, or `SCRIPT LOAD` refusal during preflight does not change the preparation phase or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains valid, a corrected ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. A process stop between claim and `EVALSHA` or an ambiguous send/result leaves the scope held; there is no automatic same-scope retry or recovery. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. No same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). +For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata cannot distinguish never-executed initialization from metadata loss. Descriptor, source, connection, principal, `SCRIPT LOAD`, or current-binding/World/incarnation revalidation refusal before the SQL claim does not change the preparation phase or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains valid, a corrected ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. After those checks pass, the owner claims the permission and immediately attempts the sole `EVALSHA`; a process stop between claim and send or an ambiguous send/result leaves the scope held, with no automatic same-scope retry or recovery. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. No same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). ## Scaling and Region Rebalancing diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 19a034bb3c..c6bbdfb051 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -243,7 +243,7 @@ Tick coordination is region-scoped, not session-scoped. Tick queues, locks, time Session shutdown therefore cleans up session keys but does not implicitly delete region-level tick coordination keys. -Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. Before that SQL claim, the owner validates the registered script descriptor and digest-checked bytes, connects, verifies `ACL WHOAMI`, and loads the script on the same connection it retains for the sole `EVALSHA`. A descriptor, source, connection, principal, or `SCRIPT LOAD` refusal closes that connection without changing the preparation or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains absent, a later ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. After the transition commits, the owner revalidates the current source and invokes that prepared session once. If the process stops between claim and send, or the send/result is ambiguous, the preparation remains `INITIALIZING`; a later attempt cannot distinguish never-executed initialization from lost metadata. It therefore fails closed without obtaining a fresh creation permission, acquiring a lease or rewriting the same-epoch baseline. This is a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for this cut. Retain and read the available preparation and incident evidence, keep the affected scope fenced, and escalate through the owning recovery process using the [current operator fallback](../../system-architecture-redis-reset-and-recovery.md#current-operator-fallback); SQL phase edits and raw Redis key surgery are not recovery authority. The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps), with focused first-NEW proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). +Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. Before that SQL claim, the owner validates the registered script descriptor and digest-checked bytes, connects, verifies `ACL WHOAMI`, and loads the script on the same connection it retains for the sole `EVALSHA`. While that prepared session remains open, it revalidates the provisional binding, current World assignment and lifecycle, stable incarnation, and retained preparation. A descriptor, source, connection, principal, `SCRIPT LOAD`, or current-context refusal closes the session without changing the preparation or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains absent, a later ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. Only after those checks succeed does the owner claim the SQL permission and immediately invoke the prepared session once. If the process stops between claim and send, or the send/result is ambiguous, the preparation remains `INITIALIZING`; a later attempt cannot distinguish never-executed initialization from lost metadata. It therefore fails closed without obtaining a fresh creation permission, acquiring a lease or rewriting the same-epoch baseline. This is a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for this cut. Retain and read the available preparation and incident evidence, keep the affected scope fenced, and escalate through the owning recovery process using the [current operator fallback](../../system-architecture-redis-reset-and-recovery.md#current-operator-fallback); SQL phase edits and raw Redis key surgery are not recovery authority. The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps), with focused first-NEW proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). ## Reconnection and Disconnect Handling diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 58c7fc237f..5645fd0c6e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -117,26 +117,26 @@ Installation installForTransition( } try (CanonicalGameplayRegionLeaseRedisOwner.PreparedTimelineInitialization session = redisOwner.prepareTimelineInitialization(preparation, leaseTtl, runtimeIdentity)) { - Optional - permit = statusRepository.beginInitialTimeline(preparation, clock.instant()); - CanonicalGameplayBindingProvisionalCasEvidence afterClaimEvidence = + CanonicalGameplayBindingProvisionalCasEvidence beforeClaimEvidence = readCurrentProvisionalEvidence(transitionId); - bindingInventory.requireSameProvisionalSource(evidence, afterClaimEvidence); - ResolvedBridgeSource afterClaimWorld = - resolveExactBridgeSource(worldRequest, afterClaimEvidence); - requireSameSource(source, afterClaimWorld.source); - CanonicalGameplayRegionIncarnationSource.StableEvidence afterClaimIncarnation = + bindingInventory.requireSameProvisionalSource(evidence, beforeClaimEvidence); + ResolvedBridgeSource beforeClaimWorld = + resolveExactBridgeSource(worldRequest, beforeClaimEvidence); + requireSameSource(source, beforeClaimWorld.source); + CanonicalGameplayRegionIncarnationSource.StableEvidence beforeClaimIncarnation = readCurrentIncarnation(source); - requireSameIncarnation(incarnation, afterClaimIncarnation); + requireSameIncarnation(incarnation, beforeClaimIncarnation); if (!statusRepository.matchesTimelinePreparation( preparation, - afterClaimEvidence, + beforeClaimEvidence, worldRequest, - afterClaimWorld.resolvedRegion, + beforeClaimWorld.resolvedRegion, source, - afterClaimIncarnation)) { + beforeClaimIncarnation)) { throw unavailable(); } + Optional + permit = statusRepository.beginInitialTimeline(preparation, clock.instant()); grant = session.initialize(permit.orElse(null)); } redisOwner.verifyInitializedTimeline(grant, preparation); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index d38a2c65cf..08b5fd9121 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -248,7 +248,7 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws assertThat(redis.admin().type(redisKey)).isEqualTo("none"); assertThat(statusRepository.find(qualifiedSource)).isEmpty(); - // Reads one and two are the initial source read and the new post-claim revalidation; read + // Reads one and two are the initial source read and the new pre-claim revalidation; read // three runs after EVALSHA, where this case exercises recovery-evidence drift. world.setAfterRead(3, incarnationSource::changeRecoveryEvidence); Throwable recoveryDriftFailure = @@ -628,6 +628,26 @@ void timelinePreflightFailuresLeavePreparedPermissionAndAllowLaterFirstClaim() t assertPreparedTimelineUnchanged( testSchema.dsl(), statusRepository, redis, source, preparation); + // The second World read follows Redis preflight and precedes the SQL permission claim. + world.setAfterRead(2, incarnationSource::changeRecoveryEvidence); + var preClaimDependencyFailureOwner = + owner( + bindingInventory, + statusRepository, + validRedisOwner, + world, + "preclaim-dependency-drift", + incarnationSource); + assertThatThrownBy( + () -> + preClaimDependencyFailureOwner.installForTransition( + TRANSITION_ID, world.request())) + .isInstanceOf(IllegalStateException.class); + assertPreparedTimelineUnchanged( + testSchema.dsl(), statusRepository, redis, source, preparation); + world.resetReads(); + incarnationSource.restoreRecoveryEvidence(); + var validOwner = owner( bindingInventory, From 87d970f92bfcf71269888bd0f96cf38bb893a720 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 00:28:03 +1300 Subject: [PATCH 34/36] fix(ci): qualify sufficient Redis ACK loss and canonical Node updates --- DEVELOPER_SETUP.md | 2 +- .../workflow_version_authority_contract.py | 4 +- ...eplayLoginContextRedisIntegrationTest.java | 85 ++++++++++++++----- 3 files changed, 69 insertions(+), 22 deletions(-) diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index 5adca371b3..4c870684f3 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -7,7 +7,7 @@ This guide explains how to configure a local development environment for the Fir Install the following tools before building the services: - **Java 21+** – required for all Spring Boot microservices. -- **Node.js 24 LTS** – needed if you plan to build the React frontend. The repository's exact Node version is declared once in [`.node-version`](.node-version) and consumed by both Gradle and CI. +- **Node.js at the repository-pinned version** – needed if you plan to build the React frontend. The repository's exact Node version is declared once in [`.node-version`](.node-version) and consumed by both Gradle and CI. - **Docker** and **Docker Compose** – run the full stack locally. - **Git** – version control for cloning and contributing. - **Gradle** – optional; only needed for an intentional wrapper upgrade. diff --git a/dev-tools/tests/workflow_version_authority_contract.py b/dev-tools/tests/workflow_version_authority_contract.py index 2d026d2a12..b0eb57c2af 100644 --- a/dev-tools/tests/workflow_version_authority_contract.py +++ b/dev-tools/tests/workflow_version_authority_contract.py @@ -46,8 +46,8 @@ def authority(path): return out node = (root / ".node-version").read_text().strip() - if not re.fullmatch(r"24\.\d+\.\d+", node): - fail(".node-version must pin an exact Node 24 release") + if not re.fullmatch(r"[1-9]\d*\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)", node): + fail(".node-version must pin an exact Node release") python = (root / ".python-version").read_text().strip() if not re.fullmatch(r"3\.\d+\.\d+", python): fail(".python-version must pin an exact Python patch release") diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index 1530da691c..7d2c646fe8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -472,7 +472,8 @@ void physicallyDroppedWaitAofNetworkResponseHoldsCleanupWithoutAccountDispatch() throws Exception { var original = coordinates(); seed(original); - try (var wire = new AckResponseDropper(PRIMARY.getMappedPort(PORT))) { + var policy = new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 500); + try (var wire = new AckResponseDropper(PRIMARY.getMappedPort(PORT), policy)) { var uri = RedisURI.Builder.redis("127.0.0.1", wire.port()) .withAuthentication(PRINCIPAL, PASSWORD) @@ -487,14 +488,24 @@ void physicallyDroppedWaitAofNetworkResponseHoldsCleanupWithoutAccountDispatch() try { var account = mock(CanonicalGameplayLoginAccountClient.class); var authority = new ControlledAuthority(); - var owner = cleanup(client(new TracedProvider(interruptedClient), authority, 1), account); + var owner = + cleanup(client(new TracedProvider(interruptedClient), authority, policy), account); owner.reserve(original); - assertThat(owner.abandonAndRetire(original).status()) - .isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); - assertThat(wire.dropped.await(5, TimeUnit.SECONDS)) - .as("real WAITAOF response dropped on physical loopback socket") - .isTrue(); - assertThat(wire.acknowledgedBeforeDrop.get()) + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + do { + // Insufficient replies remain real HELD outcomes; retry only this original closure. + assertThat(owner.abandonAndRetire(original).status()) + .isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); + verify(account, never()).retireInitialGameplayLogin(any()); + assertThat(authority.active).isFalse(); + } while (wire.dropped.getCount() != 0 && System.nanoTime() < deadline); + assertThat(wire.dropped.getCount()) + .as( + "sufficient WAITAOF response dropped on physical loopback socket; last response: %s", + wire.lastWaitAofResponse.get()) + .isZero(); + var acknowledged = Optional.ofNullable(wire.acknowledgedBeforeDrop.get()).orElseThrow(); + assertThat(acknowledged.satisfies(policy)) .as("actual local and replica AOF response was sufficient before network loss") .isTrue(); verify(account, never()).retireInitialGameplayLogin(any()); @@ -857,9 +868,14 @@ private InitialGameplayLoginCleanupOwner cleanup( private static InitialGameplayLoginContextRedisClient client( TracedProvider provider, ControlledAuthority authority, int replicas) { + return client( + provider, authority, new AcknowledgementPolicy(Profile.REPLICATED, 1, replicas, 500)); + } + + private static InitialGameplayLoginContextRedisClient client( + TracedProvider provider, ControlledAuthority authority, AcknowledgementPolicy policy) { return new InitialGameplayLoginContextRedisClient( - new InitialGameplayLoginRedisBinding( - BINDING, provider, new AcknowledgementPolicy(Profile.REPLICATED, 1, replicas, 500)), + new InitialGameplayLoginRedisBinding(BINDING, provider, policy), RedisScriptCatalog.loadInstalled( InitialGameplayLoginContextRedisIntegrationTest.class.getClassLoader()), authority); @@ -942,19 +958,23 @@ private static boolean containsSequence(byte[] value, byte[] sequence) { return false; } - /** Test-only RESP2 loopback relay drops the actual first WAITAOF response, never its request. */ + /** Test-only RESP2 relay drops the first sufficient WAITAOF response, never its request. */ private static final class AckResponseDropper implements AutoCloseable { private final ServerSocket listener; private final int upstreamPort; + private final AcknowledgementPolicy policy; private final ExecutorService workers = Executors.newCachedThreadPool(); private final Set sockets = ConcurrentHashMap.newKeySet(); private final AtomicBoolean stopping = new AtomicBoolean(); private final AtomicBoolean dropNext = new AtomicBoolean(true); private final CountDownLatch dropped = new CountDownLatch(1); - private final AtomicBoolean acknowledgedBeforeDrop = new AtomicBoolean(); + private final AtomicReference acknowledgedBeforeDrop = new AtomicReference<>(); + private final AtomicReference lastWaitAofResponse = + new AtomicReference<>("not observed"); - private AckResponseDropper(int upstreamPort) throws IOException { + private AckResponseDropper(int upstreamPort, AcknowledgementPolicy policy) throws IOException { this.upstreamPort = upstreamPort; + this.policy = policy; listener = new ServerSocket(0, 8, InetAddress.getByName("127.0.0.1")); workers.submit( () -> { @@ -988,12 +1008,16 @@ private void relay(Socket downstream) { byte[] response = frame(upstream.getInputStream()); boolean waitAof = new String(request, StandardCharsets.US_ASCII).startsWith("*4\r\n$7\r\nWAITAOF\r\n"); - if (waitAof && dropNext.compareAndSet(true, false)) { - // Read the genuine response first, then sever both sockets without delivering bytes. - acknowledgedBeforeDrop.set( - new String(response, StandardCharsets.US_ASCII).equals("*2\r\n:1\r\n:1\r\n")); - dropped.countDown(); - return; + if (waitAof) { + var counts = aofCounts(response); + lastWaitAofResponse.set(counts.map(AofCounts::toString).orElse("non-count response")); + if (counts.filter(value -> value.satisfies(policy)).isPresent() + && dropNext.compareAndSet(true, false)) { + // Only a genuine sufficient ACK qualifies the network response-loss boundary. + acknowledgedBeforeDrop.set(counts.orElseThrow()); + dropped.countDown(); + return; + } } downstream.getOutputStream().write(response); downstream.getOutputStream().flush(); @@ -1005,6 +1029,29 @@ private void relay(Socket downstream) { } } + private static Optional aofCounts(byte[] response) { + String[] fields = new String(response, StandardCharsets.US_ASCII).split("\r\n", -1); + if (fields.length != 4 + || !fields[0].equals("*2") + || !fields[3].isEmpty() + || !fields[1].matches(":(0|[1-9][0-9]*)") + || !fields[2].matches(":(0|[1-9][0-9]*)")) return Optional.empty(); + try { + return Optional.of( + new AofCounts( + Long.parseLong(fields[1].substring(1)), Long.parseLong(fields[2].substring(1)))); + } catch (NumberFormatException malformed) { + return Optional.empty(); + } + } + + private record AofCounts(long local, long replicas) { + private boolean satisfies(AcknowledgementPolicy policy) { + return local >= policy.requiredLocalAofCount() + && replicas >= policy.requiredReplicaAofCount(); + } + } + private static byte[] frame(InputStream input) throws IOException { var bytes = new ByteArrayOutputStream(); readFrame(input, bytes); From 9a3fd6d4de40e8e8cd1614d76dd807ad97a15e75 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 01:00:39 +1300 Subject: [PATCH 35/36] fix(region): exercise actual bridge phases and canonicalize recovery proof --- .../game-session-service/operations.md | 2 + .../game-session-service/runtime-and-data.md | 4 +- .../gameplay-rules-entities-and-effects.md | 2 + .../player-access-and-session.md | 2 +- .../world-runtime-and-movement.md | 2 +- ...nicalGameplayRegionBindingBridgeOwner.java | 62 +++++++++++-- ...meplayRegionLeaseOwnerIntegrationTest.java | 6 +- ...GameplayRegionOwnerCompositionFixture.java | 92 ++++--------------- 8 files changed, 85 insertions(+), 87 deletions(-) diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index 822436f2d1..8ac074510c 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -42,6 +42,8 @@ Before deploying the new Game Session admission validation, Automation must alre - Prometheus scrapes metrics from `/actuator/prometheus`. - Target state: logs, traces, and control-plane reads expose the active exact `{scriptPatchVersion, scriptPinEpoch}` execution fence so operators can identify the hotfix revision and selection epoch during incident triage without adding either raw value as ordinary high-cardinality metric labels. Current coverage is summarized in [Implementation Status](#implementation-status). +### Initial region timeline recovery boundary + For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata cannot distinguish never-executed initialization from metadata loss. Descriptor, source, connection, principal, `SCRIPT LOAD`, or current-binding/World/incarnation revalidation refusal before the SQL claim does not change the preparation phase or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains valid, a corrected ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. After those checks pass, the owner claims the permission and immediately attempts the sole `EVALSHA`; a process stop between claim and send or an ambiguous send/result leaves the scope held, with no automatic same-scope retry or recovery. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. No same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). ## Scaling and Region Rebalancing diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index c6bbdfb051..f260531c05 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -38,7 +38,7 @@ The sections below define the target-state runtime contract. Current implementat - Hidden same-type Game Session recovery within ADR 0013's qualifying conditions remains an implementation or proof gap; the target is to preserve the session through upstream rebind rather than require a player-visible re-`LOGIN` / re-`PLAY` cycle. - The live `startSession` path keeps the Game Session row and runtime projection `STARTING` until World confirms its fenced `PREPARING -> ACTIVE` transition, then records `RUNNING`; failures before an activation attempt use the existing pre-activation cleanup. Once activation may have been issued or committed, an activation error or ambiguous result, or a later local runtime-state save/finalization failure, retains both the runtime projection and local owner row as `STARTING`, and never calls stale-epoch `failPrepared` or deletes either record. A failure proven before any World termination request is issued may restore the prior `RUNNING` row and runtime state while the World remains `ACTIVE`; once a termination request may have been issued, an error or ambiguous result leaves the local row `STOPPING` and runtime projection absent. Confirmed World termination retries local `STOPPED` finalization and never restores `RUNNING`. Durable stable lifecycle-operation identity and lifecycle readback/reconciliation remain unimplemented, so these local fail-closed quarantines are not a replacement for the target durable lifecycle cleanup workflow. - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. -- The prepared, unregistered region owner consumes exact World initial-placement/currentness and lifecycle reads plus Entity’s authenticated runtime reference. It durably prepares a non-admitting initial timeline, conditionally installs complete same-slot initial Redis metadata and the actual region lease, installs the matching SQL executor fence, and records the first-NEW region bridge acknowledgement. The timeline begins at `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`); existing or reset state cannot be adopted as a new timeline. Original retries retain the preparation, source and lease evidence. A committed `INITIALIZING` preparation whose Redis initialization never executes remains non-admitting and cannot automatically recover from absent keys; the scope must stay fenced pending the owning recovery process, as detailed below. The controlled authenticated actual-owner composition now has focused local proof; the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-initial-player-location-preparation) records its scope and remaining public qualification. Forward V1043 preserves the original timeline migration while aligning its binding-reference carrier with the existing 6,144-byte physical codec bound; the canonical three-UUID frame is 133 bytes and cannot fit the former 128-byte check. Forward V1044 makes the existing lease-bound runtime fence consume the exact retained Human completion, matching `COMMITTED` initial attempt, current `OPEN` pointer and audit under the existing runtime row lock. The original run-owned checks remain owner-specific; absence of both qualified sources is refused. This is manual owner preparation, not registered tick execution, final player binding or production admission. The [Redis owner contract](../../system-architecture-redis.md#key-naming-and-shard-discipline) remains authoritative for timeline and lease semantics. +- The prepared, unregistered region owner consumes exact World initial-placement/currentness and lifecycle reads plus Entity’s authenticated runtime reference. It durably prepares a non-admitting initial timeline, conditionally installs complete same-slot initial Redis metadata and the actual region lease, installs the matching SQL executor fence, and records the first-NEW region bridge acknowledgement. The timeline begins at `regionEpoch=1` and `lastCommittedTickId=-1` (first tick `0`); existing or reset state cannot be adopted as a new timeline. Original retries retain the preparation, source and lease evidence. A committed `INITIALIZING` preparation whose Redis initialization never executes remains non-admitting and cannot automatically recover from absent keys; the scope remains fenced under the [operations recovery boundary](./operations.md#initial-region-timeline-recovery-boundary). The controlled authenticated actual-owner composition now has focused local proof; the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-initial-player-location-preparation) records its scope and remaining public qualification. Forward V1043 preserves the original timeline migration while aligning its binding-reference carrier with the existing 6,144-byte physical codec bound; the canonical three-UUID frame is 133 bytes and cannot fit the former 128-byte check. Forward V1044 makes the existing lease-bound runtime fence consume the exact retained Human completion, matching `COMMITTED` initial attempt, current `OPEN` pointer and audit under the existing runtime row lock. The original run-owned checks remain owner-specific; absence of both qualified sources is refused. This is manual owner preparation, not registered tick execution, final player binding or production admission. The [Redis owner contract](../../system-architecture-redis.md#key-naming-and-shard-discipline) remains authoritative for timeline and lease semantics. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). - The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. @@ -243,7 +243,7 @@ Tick coordination is region-scoped, not session-scoped. Tick queues, locks, time Session shutdown therefore cleans up session keys but does not implicitly delete region-level tick coordination keys. -Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. Before that SQL claim, the owner validates the registered script descriptor and digest-checked bytes, connects, verifies `ACL WHOAMI`, and loads the script on the same connection it retains for the sole `EVALSHA`. While that prepared session remains open, it revalidates the provisional binding, current World assignment and lifecycle, stable incarnation, and retained preparation. A descriptor, source, connection, principal, `SCRIPT LOAD`, or current-context refusal closes the session without changing the preparation or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains absent, a later ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. Only after those checks succeed does the owner claim the SQL permission and immediately invoke the prepared session once. If the process stops between claim and send, or the send/result is ambiguous, the preparation remains `INITIALIZING`; a later attempt cannot distinguish never-executed initialization from lost metadata. It therefore fails closed without obtaining a fresh creation permission, acquiring a lease or rewriting the same-epoch baseline. This is a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for this cut. Retain and read the available preparation and incident evidence, keep the affected scope fenced, and escalate through the owning recovery process using the [current operator fallback](../../system-architecture-redis-reset-and-recovery.md#current-operator-fallback); SQL phase edits and raw Redis key surgery are not recovery authority. The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps), with focused first-NEW proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). +Initial timeline creation has one durable, single-use permission: only the `PREPARED`-to-`INITIALIZING` transition grants permission to create the initial Redis metadata from a proved-absent preimage. Before that SQL claim, the owner validates the registered script descriptor and digest-checked bytes, connects, verifies `ACL WHOAMI`, and loads the script on the same connection it retains for the sole `EVALSHA`. While that prepared session remains open, it revalidates the provisional binding, current World assignment and lifecycle, stable incarnation, and retained preparation. A descriptor, source, connection, principal, `SCRIPT LOAD`, or current-context refusal closes the session without changing the preparation or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains absent, a later ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. Only after those checks succeed does the owner claim the SQL permission and immediately invoke the prepared session once. If the process stops between claim and send, or the send/result is ambiguous, the preparation remains `INITIALIZING`; a later attempt cannot distinguish never-executed initialization from lost metadata. It therefore fails closed without obtaining a fresh creation permission, acquiring a lease or rewriting the same-epoch baseline. This is a scope-local liveness limit; no in-place automatic recovery, dedicated alert or operator repair surface is shipped for this cut. SQL phase edits and raw Redis key surgery are not recovery authority. Operator handling and authorized scope retirement belong to the [initial timeline recovery boundary](./operations.md#initial-region-timeline-recovery-boundary). The canonical region-bootstrap, timeline, and recovery gaps remain recorded in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps), with focused first-NEW proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#validation-and-proof). ## Reconnection and Disconnect Handling 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 9732ff72d7..b873f2f094 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 @@ -48,6 +48,8 @@ The full causal current supersession after original issuance → recovery/retire ### Canonical sealed roster retention prerequisite +The historical region-PR receiving repair preserves the intentional V1011/V1017 Entity roster-retention migration fixtures. They now seed explicitly historical assignment receipts, actors and snapshots without calling the fresh V1022 projection allocator before upgrade; current-schema assignments still use the production owner. No applied migration or production compatibility/backfill path changes. R722 executes 584 Entity methods: 454 unit and 65 native cases pass, while 46 retention setup cases expose a placeholder error in the new fixture and 19 other native cases fail PostgreSQL connection setup. R723 corrects only the placeholder and freshly passes all 65 affected native cases with zero failures, errors or skips. All 584 distinct methods therefore have passing execution across the two runs; the failed full-check aggregate stays retained. Enabled affected static analysis and formatting pass. This is fixture and regression evidence for those historical receiving invocations; it does not establish current-head public CI or runtime activation. + The latest recovery correction refuses to close an Entity admission as no-capture when the authenticated Game Session owner retains a roster receipt but Entity lacks its local original. Existing OPEN admissions remain byte-for-byte unchanged, and a provisional admission insert rolls back. The Game Session recovery writer independently rejects a missing or mismatched receipt against a recorded original. Oversized selectors now return `INVALID_SELECTOR` before roster reservation or outcome recording, preserving ambient-transaction and context checks. R360 freshly passes all 36 Entity retention PostgreSQL cases and all 30 Game Session reference PostgreSQL cases with zero failures, errors or skips, alongside root checks, affected main/integration static analysis and documentation checks. Its new selector test initially failed compilation because the fixture declares a checked exception; after correcting that declaration, R361 freshly passes all 14 selector and ten retention-service unit cases plus test static analysis and formatting. The earlier R358 broad check was interrupted after repeated local PostgreSQL endpoint refusals and supplies no complete aggregate qualification; the original failure log is retained. These controlled regression results do not establish production registration, genuine authority or the canonical playable journey. A focused independent database review finds malformed retained Game Session originals can prevent bounded cleanup progress. The correction pages candidates by their actual operation UUID, preserving the target fence while advancing past invalid originals; a later valid original on the same fence can therefore reach the owner. Recovery isolates protobuf/closed-binding validation failures while retaining durable non-authoritative attempt ordering, unchanged recovery identity/start time and all protection/terminal guards. R356 freshly passes ten retention-service unit cases and two current-schema PostgreSQL cases, with zero failures, errors or skips, plus enabled main/test/integration static analysis and formatting. The PostgreSQL cases preserve malformed source bytes, reject semantic and row/fence binding contradictions, drive actual bounded sweeps across service/repository reconstruction and permit later valid recovery attempts without dispatching or terminalizing the bad original. Current-route/OPEN and Entity-client responses are controlled; this does not establish genuine current supersession, process-death recovery or production registration. Published SQL and migration history are unchanged. 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 19f92d1dd9..e8a465aed9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -482,7 +482,7 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The ## Validation and Proof -The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. The operator recovery boundary is recorded by the [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md#tick-coordination-and-lease-ownership). +The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. The operator recovery boundary is recorded by [Game Session operations](../../architecture/microservices/game-session-service/operations.md#initial-region-timeline-recovery-boundary). Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passed all five native region-owner cases, including this cut, and the inherited protected-admission concurrency case; its aggregate still failed Entity test SpotBugs. The extracted Entity producer's R890/R891/R893 history is recorded separately below. This is bounded refusal proof and does not establish recovery or production activation. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index a5c2e65a0e..1f89e2c69e 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -16,7 +16,7 @@ The next receiving checkpoint at `63bfad5b657d6fafc2880345355074e68b3945e2` rece Historical subsequent receiving checkpoint `cc90e783280a99aa6c247e32377fd7cf283be9c4` receives published #2973 `8e15d7af318808a5cab6c460da22db917f66dbb2` and #3310 `8cf137b8fb31be2728978e1397ffce7012bf313e`. Its 83-path comparison preserves all 82 owned source postimages from the qualified boundary; only this shared tracker receives parent proof attribution. R720 freshly passes the actual Human-to-region composed owner case and all seven runtime-fence cases, with zero failures, errors or skips and enabled affected static analysis, formatting and documentation checks. All eight R720 observed containers are independently absent. This is current-parent receiving proof supplementing the separately scoped 92-method qualification above. Controlled authority, registration, tick execution, final player CAS, production custody/PKI and activation limits remain unchanged. -The first region-PR CI repair preserves the intentional V1011/V1017 Entity roster-retention migration fixtures. They now seed explicitly historical assignment receipts, actors and snapshots without calling the fresh V1022 projection allocator before upgrade; current-schema assignments still use the production owner. No applied migration or production compatibility/backfill path changes. R722 executes 584 Entity methods: 454 unit and 65 native cases pass, while 46 retention setup cases expose a placeholder error in the new fixture and 19 other native cases fail PostgreSQL connection setup. R723 corrects only the placeholder and freshly passes all 65 affected native cases with zero failures, errors or skips. All 584 distinct methods therefore have passing execution across the two runs; the failed full-check aggregate stays retained. Enabled affected static analysis and formatting pass. This is current-parent fixture and regression proof; replacement public CI is still required. +Entity roster-retention migration-fixture repair and its R722/R723 evidence are recorded at the [owning Gameplay prerequisite](./gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). The [initial-placement API](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-player-location) is prepared as an unregistered owner service, transport and immediate Game Session client over the existing V1019 storage boundary. It receives the necessary existing canonical hold reader, Game Session terminal client and Common response decoder; their donor source remains preserved. The distinct World-only Entity receipt read supplies persisted assignment provenance without widening the Game Session roster allowlists. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java index 302b68b745..9370297808 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java @@ -2,12 +2,34 @@ import java.util.Objects; import java.util.UUID; +import java.util.function.Supplier; import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; import net.firedevops.firemud.gamesession.client.CanonicalPreseededActorRuntimeReferenceClient; /** Manual owner for the initial-NEW region binding mutation and its durable local ACK. */ final class CanonicalGameplayRegionBindingBridgeOwner { + enum SqlPhase { + PREPARE, + ACKNOWLEDGE + } + + /** + * Package-private SQL seam for owner-composition lock-order proof; production uses direct calls. + */ + @FunctionalInterface + interface SqlPhaseRunner { + T run(SqlPhase phase, Supplier action); + } + + private static final SqlPhaseRunner DIRECT_SQL_PHASE_RUNNER = + new SqlPhaseRunner() { + @Override + public T run(SqlPhase phase, Supplier action) { + return action.get(); + } + }; + private final CanonicalGameplayRegionLeaseOwner regionLeaseOwner; private final CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient; @@ -50,7 +72,13 @@ CanonicalGameplayRegionLeaseOwner.Installation installForTransition( /** Executes only an exact first-NEW bridge from a privately created region installation. */ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( CanonicalGameplayRegionLeaseOwner.Installation installation) { + return bridge(installation, DIRECT_SQL_PHASE_RUNNER); + } + + CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( + CanonicalGameplayRegionLeaseOwner.Installation installation, SqlPhaseRunner sqlPhaseRunner) { Objects.requireNonNull(installation, "installation"); + Objects.requireNonNull(sqlPhaseRunner, "sqlPhaseRunner"); CanonicalGameplayRegionLeaseOwner.BridgeContext initial = regionLeaseOwner.currentBridgeContext(installation); if (initial.evidence().expectedPrior() != null @@ -66,7 +94,9 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( entityReferenceClient.read(entityRequest); CanonicalGameplayRegionLeaseOwner.RegionBridgePreimage initialPreimage = regionLeaseOwner.probeRegionSessionBinding(installation, reference); - regionLeaseOwner.prepareBridge(installation, initialPreimage, reference); + sqlPhaseRunner.run( + SqlPhase.PREPARE, + () -> regionLeaseOwner.prepareBridge(installation, initialPreimage, reference)); // The stable operation and current SQL fence are durable before this first physical write. CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference beforeWriteReference = @@ -75,7 +105,11 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( CanonicalGameplayRegionLeaseOwner.RegionBridgePreimage beforeWritePreimage = regionLeaseOwner.probeRegionSessionBinding(installation, beforeWriteReference); CanonicalGameplayBindingRegionBridgeObligation prepared = - regionLeaseOwner.prepareBridge(installation, beforeWritePreimage, beforeWriteReference); + sqlPhaseRunner.run( + SqlPhase.PREPARE, + () -> + regionLeaseOwner.prepareBridge( + installation, beforeWritePreimage, beforeWriteReference)); regionLeaseOwner.applyRegionSessionBinding(installation, beforeWriteReference); CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference currentReference = @@ -84,7 +118,11 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( CanonicalGameplayRegionLeaseOwner.RegionBridgePreimage beforeReadbackPreimage = regionLeaseOwner.probeRegionSessionBinding(installation, currentReference); prepared = - regionLeaseOwner.prepareBridge(installation, beforeReadbackPreimage, currentReference); + sqlPhaseRunner.run( + SqlPhase.PREPARE, + () -> + regionLeaseOwner.prepareBridge( + installation, beforeReadbackPreimage, currentReference)); CanonicalGameplayRegionLeaseRedisOwner.BindingReadback readback = regionLeaseOwner.readBackRegionSessionBinding( @@ -98,10 +136,22 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( throw unavailable(); } prepared = - regionLeaseOwner.prepareBridge(installation, beforeAckPreimage, afterReadbackReference); + sqlPhaseRunner.run( + SqlPhase.PREPARE, + () -> + regionLeaseOwner.prepareBridge( + installation, beforeAckPreimage, afterReadbackReference)); - return regionLeaseOwner.acknowledgeBridge( - installation, prepared, beforeAckPreimage.context(), afterReadbackReference, readback); + CanonicalGameplayBindingRegionBridgeObligation acknowledgementPreparation = prepared; + return sqlPhaseRunner.run( + SqlPhase.ACKNOWLEDGE, + () -> + regionLeaseOwner.acknowledgeBridge( + installation, + acknowledgementPreparation, + beforeAckPreimage.context(), + afterReadbackReference, + readback)); } private static ReadPreseededActorRuntimeReferenceRequest entityRequest( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 08b5fd9121..d829339227 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -848,7 +848,11 @@ private static T runBridgePhaseAgainstRuntimeHolder( + " AND ? = ANY(pg_blocking_pids(pid))" + " AND query LIKE '%game_instances%' LIMIT 1", holderPid); - if (waiter != null) waitingPid = waiter.get("pid", Integer.class); + if (waiter != null) { + waitingPid = waiter.get("pid", Integer.class); + } else { + Thread.sleep(10L); + } } assertThat(waitingPid).as("bridge waits on exact runtime holder").isNotNull(); assertThat(bridge.isDone()).isFalse(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index 93b5ca2cad..374f940e4c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -31,7 +31,6 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import net.firedevops.firemud.entitymanagement.v1.ReadPreseededActorRuntimeReferenceRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionAbortSource; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; @@ -590,8 +589,7 @@ private static TwoBindingProof installAndBridgeInternal( var firstAcknowledgement = phaseRunner == null ? bridgeOwner.bridge(installation) - : bridgeWithSqlPhaseRunner( - leaseOwner, installation, bridgeEntityReferenceClient, phaseRunner); + : bridgeOwner.bridge(installation, actualBridgeSqlPhaseRunner(phaseRunner)); var lostReplyRetry = bridgeOwner.bridge(installation); var acknowledged = firstAcknowledgement.obligation(); var replayed = lostReplyRetry.obligation(); @@ -928,74 +926,15 @@ private static TwoBindingProof installAndBridgeInternal( } } - private static CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement - bridgeWithSqlPhaseRunner( - CanonicalGameplayRegionLeaseOwner leaseOwner, - CanonicalGameplayRegionLeaseOwner.Installation installation, - CanonicalPreseededActorRuntimeReferenceClient entityClient, - BridgeSqlPhaseRunner phaseRunner) { - var request = installation.worldRequest; - var initial = leaseOwner.currentBridgeContext(installation); - if (initial.evidence().expectedPrior() != null - || initial.evidence().transition().status() - != net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot - .Status.PROVISIONAL) { - throw new IllegalStateException("Region bridge requires an exact first-NEW transition"); - } - var entityRequest = - ReadPreseededActorRuntimeReferenceRequest.newBuilder() - .setSchemaVersion(1) - .setAssignmentUuid(request.getAssignmentUuid()) - .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) - .setExpectedTarget(request.getExpectedTarget()) - .setCharacterUuid(request.getCharacterUuid()) - .setIntentDigest(request.getAssignmentIntentDigest()) - .build(); - var reference = entityClient.read(entityRequest); - var preimage = leaseOwner.probeRegionSessionBinding(installation, reference); - phaseRunner.run( - BridgeSqlPhase.PREPARE, () -> leaseOwner.prepareBridge(installation, preimage, reference)); - var beforeWriteReference = entityClient.read(entityRequest); - requireSameBridgeReference(reference, beforeWriteReference); - var beforeWritePreimage = - leaseOwner.probeRegionSessionBinding(installation, beforeWriteReference); - leaseOwner.prepareBridge(installation, beforeWritePreimage, beforeWriteReference); - leaseOwner.applyRegionSessionBinding(installation, beforeWriteReference); - var currentReference = entityClient.read(entityRequest); - requireSameBridgeReference(reference, currentReference); - var beforeReadbackPreimage = - leaseOwner.probeRegionSessionBinding(installation, currentReference); - leaseOwner.prepareBridge(installation, beforeReadbackPreimage, currentReference); - var readback = - leaseOwner.readBackRegionSessionBinding( - installation, beforeReadbackPreimage.context().status(), currentReference); - var afterReadbackReference = entityClient.read(entityRequest); - requireSameBridgeReference(reference, afterReadbackReference); - var beforeAckPreimage = - leaseOwner.probeRegionSessionBinding(installation, afterReadbackReference); - if (!beforeReadbackPreimage.context().status().equals(beforeAckPreimage.context().status())) { - throw new IllegalStateException("Region bridge owner changed before acknowledgement"); - } - var prepared = - leaseOwner.prepareBridge(installation, beforeAckPreimage, afterReadbackReference); - return phaseRunner.run( - BridgeSqlPhase.ACKNOWLEDGE, - () -> - leaseOwner.acknowledgeBridge( - installation, - prepared, - beforeAckPreimage.context(), - afterReadbackReference, - readback)); - } - - private static void requireSameBridgeReference( - CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference expected, - CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference actual) { - if (!CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(expected) - .equals(CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(actual))) { - throw new IllegalStateException("Region bridge Entity source changed"); - } + private static CanonicalGameplayRegionBindingBridgeOwner.SqlPhaseRunner + actualBridgeSqlPhaseRunner(BridgeSqlPhaseRunner fixtureRunner) { + return new CanonicalGameplayRegionBindingBridgeOwner.SqlPhaseRunner() { + @Override + public T run( + CanonicalGameplayRegionBindingBridgeOwner.SqlPhase phase, Supplier action) { + return fixtureRunner.run(BridgeSqlPhase.valueOf(phase.name()), action); + } + }; } private static ChangedGrantProof reacquireGrantAfterAcknowledgement( @@ -1135,11 +1074,7 @@ private static boolean sameAbortSource( && left.targetEvidence().equals(right.targetEvidence()); } - /** - * Carries a controlled definitive Account abort through the actual repository after a real - * PostgreSQL/Redis bridge ACK, then proves exact cleanup retry/read preserves that ACK without - * promoting the candidate or claiming cleanup completion. - */ + /** Verifies the materialized bridge obligation appears exactly in the current issuer cohort. */ private static void requireMaterializedBridgeCaptured(DSLContext dsl, UUID transitionId) { String exactRow = dsl.fetchSingle( @@ -1170,6 +1105,11 @@ private static void requireMaterializedBridgeCaptured(DSLContext dsl, UUID trans } } + /** + * Carries a controlled definitive Account abort through the actual repository after a real + * PostgreSQL/Redis bridge ACK, then proves exact cleanup retry/read preserves that ACK without + * promoting the candidate or claiming cleanup completion. + */ public static AccountAbortProof abortAfterBridge(DSLContext dsl, Proof bridgeProof) { var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); var before = inventory.readFirstNewAdmissionAbortSource(bridgeProof.transitionId()); From b7bf14e1dd105b4104b6b49c1c19ea5a6941a81d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:11:08 +1300 Subject: [PATCH 36/36] ci: allow bounded completion of Game Session native validation --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f86e965042..c2fa0347bd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1052,8 +1052,8 @@ jobs: permissions: contents: read id-token: write - # Full checks, packaging and cleanup need 60 minutes for Account/Game Session (PostgreSQL/Redis issuer suites), 40 for World and 30 for Game Design. - timeout-minutes: ${{ (matrix.module == 'account-service' || matrix.module == 'game-session-service') && 60 || matrix.module == 'world-management-service' && 40 || matrix.module == 'game-design-service' && 30 || 20 }} + # Allow 90 minutes for the full Game Session native issuer suites; retain Account 60, World 40 and Game Design 30. + timeout-minutes: ${{ matrix.module == 'game-session-service' && 90 || matrix.module == 'account-service' && 60 || matrix.module == 'world-management-service' && 40 || matrix.module == 'game-design-service' && 30 || 20 }} strategy: fail-fast: false matrix: